Index: /issm/trunk-jpl-damage/AUTHORS
===================================================================
--- /issm/trunk-jpl-damage/AUTHORS	(revision 11330)
+++ /issm/trunk-jpl-damage/AUTHORS	(revision 11330)
@@ -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@jpl.nasa.gov>
+
+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/trunk-jpl-damage/COPYING
===================================================================
--- /issm/trunk-jpl-damage/COPYING	(revision 11330)
+++ /issm/trunk-jpl-damage/COPYING	(revision 11330)
@@ -0,0 +1,28 @@
+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/trunk-jpl-damage/ChangeLog
===================================================================
--- /issm/trunk-jpl-damage/ChangeLog	(revision 11330)
+++ /issm/trunk-jpl-damage/ChangeLog	(revision 11330)
@@ -0,0 +1,3 @@
+Go to
+
+https://issm.ess.uci.edu:80/trac/issm/timeline
Index: /issm/trunk-jpl-damage/INSTALL
===================================================================
--- /issm/trunk-jpl-damage/INSTALL	(revision 11330)
+++ /issm/trunk-jpl-damage/INSTALL	(revision 11330)
@@ -0,0 +1,2 @@
+For the installation process please go to the ISSM website 
+http://issm.jpl.nasa.gov/
Index: /issm/trunk-jpl-damage/LICENSE
===================================================================
--- /issm/trunk-jpl-damage/LICENSE	(revision 11330)
+++ /issm/trunk-jpl-damage/LICENSE	(revision 11330)
@@ -0,0 +1,28 @@
+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/trunk-jpl-damage/Makefile.am
===================================================================
--- /issm/trunk-jpl-damage/Makefile.am	(revision 11330)
+++ /issm/trunk-jpl-damage/Makefile.am	(revision 11330)
@@ -0,0 +1,2 @@
+EXTRA_DIST = reconf  scripts test INSTALLICE LICENSE m4 examples cron etc doc packages ChangeLogCielo ChangeLogIce contributors.txt run READMEICE startup.m startup.m startup.m startup.m  todo MakefileIce
+SUBDIRS = src bin
Index: /issm/trunk-jpl-damage/NEWS
===================================================================
--- /issm/trunk-jpl-damage/NEWS	(revision 11330)
+++ /issm/trunk-jpl-damage/NEWS	(revision 11330)
@@ -0,0 +1,4 @@
+
+please go to the ISSM website for the latest news:
+
+http://issm.jpl.nasa.gov/
Index: /issm/trunk-jpl-damage/README
===================================================================
--- /issm/trunk-jpl-damage/README	(revision 11330)
+++ /issm/trunk-jpl-damage/README	(revision 11330)
@@ -0,0 +1,52 @@
+------------------------------------------------------------------------------
+
+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          Eric Larour (Project Lead)
+Mathieu       Mathieu Morlighem (Anisotropic Meshing, Control Methods)
+Helene        Helene Seroussi (Coupling 2D-3D, Multi-model, full-Stokes)
+
+Email: issm@jpl.nasa.gov
+
+------------------------------------------------------------------------------
+License
+
+ISSM is California Institute of Technology Copyright.
+------------------------------------------------------------------------------
+Overview
+
+More to come
+
+Refer to http://issm.jpl.nasa.gov/ for additional information.
+------------------------------------------------------------------------------
+Distribution
+
+The directories contained in this distribution include:
+
+examples            Example problems 
+
+externalpackages    Other libraries 
+
+m4                  m4 macros used for supporting autoconf.
+
+doc                 The Users, Reference, and Developers Manuals are 
+                    maintained here.  Other references are available from
+                    the ISSM Web site (http://issm.jpl.nasa.gov/)
+
+src                 The main source code repository for the ISSM system.
+
+test                Files for regression and unit testing of the ISSM system.
+------------------------------------------------------------------------------
+Installation
+
+The installation procedure uses a standard GNU installation based on autoconf.
+The basic steps are to invoke 'configure' to generate Makefiles for your 
+particular system and then invoke 'make' to compile the sources.  See the 
+INSTALL file for detailed instructions.
+------------------------------------------------------------------------------
Index: /issm/trunk-jpl-damage/compile
===================================================================
--- /issm/trunk-jpl-damage/compile	(revision 11330)
+++ /issm/trunk-jpl-damage/compile	(revision 11330)
@@ -0,0 +1,142 @@
+#! /bin/sh
+# Wrapper for compilers which do not understand `-c -o'.
+
+scriptversion=2005-05-14.22
+
+# Copyright (C) 1999, 2000, 2003, 2004, 2005 Free Software Foundation, Inc.
+# Written by Tom Tromey <tromey@cygnus.com>.
+#
+# 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, 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, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# This file is maintained in Automake, please report
+# bugs to <bug-automake@gnu.org> or send patches to
+# <automake-patches@gnu.org>.
+
+case $1 in
+  '')
+     echo "$0: No command.  Try \`$0 --help' for more information." 1>&2
+     exit 1;
+     ;;
+  -h | --h*)
+    cat <<\EOF
+Usage: compile [--help] [--version] PROGRAM [ARGS]
+
+Wrapper for compilers which do not understand `-c -o'.
+Remove `-o dest.o' from ARGS, run PROGRAM with the remaining
+arguments, and rename the output as expected.
+
+If you are trying to build a whole package this is not the
+right script to run: please start by reading the file `INSTALL'.
+
+Report bugs to <bug-automake@gnu.org>.
+EOF
+    exit $?
+    ;;
+  -v | --v*)
+    echo "compile $scriptversion"
+    exit $?
+    ;;
+esac
+
+ofile=
+cfile=
+eat=
+
+for arg
+do
+  if test -n "$eat"; then
+    eat=
+  else
+    case $1 in
+      -o)
+	# configure might choose to run compile as `compile cc -o foo foo.c'.
+	# So we strip `-o arg' only if arg is an object.
+	eat=1
+	case $2 in
+	  *.o | *.obj)
+	    ofile=$2
+	    ;;
+	  *)
+	    set x "$@" -o "$2"
+	    shift
+	    ;;
+	esac
+	;;
+      *.c)
+	cfile=$1
+	set x "$@" "$1"
+	shift
+	;;
+      *)
+	set x "$@" "$1"
+	shift
+	;;
+    esac
+  fi
+  shift
+done
+
+if test -z "$ofile" || test -z "$cfile"; then
+  # If no `-o' option was seen then we might have been invoked from a
+  # pattern rule where we don't need one.  That is ok -- this is a
+  # normal compilation that the losing compiler can handle.  If no
+  # `.c' file was seen then we are probably linking.  That is also
+  # ok.
+  exec "$@"
+fi
+
+# Name of file we expect compiler to create.
+cofile=`echo "$cfile" | sed -e 's|^.*/||' -e 's/\.c$/.o/'`
+
+# Create the lock directory.
+# Note: use `[/.-]' here to ensure that we don't use the same name
+# that we are using for the .o file.  Also, base the name on the expected
+# object file name, since that is what matters with a parallel build.
+lockdir=`echo "$cofile" | sed -e 's|[/.-]|_|g'`.d
+while true; do
+  if mkdir "$lockdir" >/dev/null 2>&1; then
+    break
+  fi
+  sleep 1
+done
+# FIXME: race condition here if user kills between mkdir and trap.
+trap "rmdir '$lockdir'; exit 1" 1 2 15
+
+# Run the compile.
+"$@"
+ret=$?
+
+if test -f "$cofile"; then
+  mv "$cofile" "$ofile"
+elif test -f "${cofile}bj"; then
+  mv "${cofile}bj" "$ofile"
+fi
+
+rmdir "$lockdir"
+exit $ret
+
+# Local Variables:
+# mode: shell-script
+# sh-indentation: 2
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-end: "$"
+# End:
Index: /issm/trunk-jpl-damage/config.guess
===================================================================
--- /issm/trunk-jpl-damage/config.guess	(revision 11330)
+++ /issm/trunk-jpl-damage/config.guess	(revision 11330)
@@ -0,0 +1,1542 @@
+#! /bin/sh
+# Attempt to guess a canonical system name.
+#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
+#   Free Software Foundation, Inc.
+
+timestamp='2008-11-15'
+
+# This file 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.
+#
+# 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., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+
+# Originally written by Per Bothner <per@bothner.com>.
+# Please send patches to <config-patches@gnu.org>.  Submit a context
+# diff and a properly formatted ChangeLog entry.
+#
+# This script attempts to guess a canonical system name similar to
+# config.sub.  If it succeeds, it prints the system name on stdout, and
+# exits with 0.  Otherwise, it exits with 1.
+#
+# The plan is that this can be called by configure scripts if you
+# don't specify an explicit build system type.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION]
+
+Output the configuration name of the system \`$me' is run on.
+
+Operation modes:
+  -h, --help         print this help, then exit
+  -t, --time-stamp   print date of last modification, then exit
+  -v, --version      print version number, then exit
+
+Report bugs and patches to <config-patches@gnu.org>."
+
+version="\
+GNU config.guess ($timestamp)
+
+Originally written by Per Bothner.
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
+2002, 2003, 2004, 2005, 2006, 2007, 2008 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."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+  case $1 in
+    --time-stamp | --time* | -t )
+       echo "$timestamp" ; exit ;;
+    --version | -v )
+       echo "$version" ; exit ;;
+    --help | --h* | -h )
+       echo "$usage"; exit ;;
+    -- )     # Stop option processing
+       shift; break ;;
+    - )	# Use stdin as input.
+       break ;;
+    -* )
+       echo "$me: invalid option $1$help" >&2
+       exit 1 ;;
+    * )
+       break ;;
+  esac
+done
+
+if test $# != 0; then
+  echo "$me: too many arguments$help" >&2
+  exit 1
+fi
+
+trap 'exit 1' 1 2 15
+
+# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
+# compiler to aid in system detection is discouraged as it requires
+# temporary files to be created and, as you can see below, it is a
+# headache to deal with in a portable fashion.
+
+# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
+# use `HOST_CC' if defined, but it is deprecated.
+
+# Portable tmp directory creation inspired by the Autoconf team.
+
+set_cc_for_build='
+trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
+trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
+: ${TMPDIR=/tmp} ;
+ { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
+ { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
+ { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
+ { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
+dummy=$tmp/dummy ;
+tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
+case $CC_FOR_BUILD,$HOST_CC,$CC in
+ ,,)    echo "int x;" > $dummy.c ;
+	for c in cc gcc c89 c99 ; do
+	  if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
+	     CC_FOR_BUILD="$c"; break ;
+	  fi ;
+	done ;
+	if test x"$CC_FOR_BUILD" = x ; then
+	  CC_FOR_BUILD=no_compiler_found ;
+	fi
+	;;
+ ,,*)   CC_FOR_BUILD=$CC ;;
+ ,*,*)  CC_FOR_BUILD=$HOST_CC ;;
+esac ; set_cc_for_build= ;'
+
+# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
+# (ghazi@noc.rutgers.edu 1994-08-24)
+if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
+	PATH=$PATH:/.attbin ; export PATH
+fi
+
+UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
+UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
+UNAME_SYSTEM=`(uname -s) 2>/dev/null`  || UNAME_SYSTEM=unknown
+UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
+
+# Note: order is significant - the case branches are not exclusive.
+
+case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
+    *:NetBSD:*:*)
+	# NetBSD (nbsd) targets should (where applicable) match one or
+	# more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*,
+	# *-*-netbsdecoff* and *-*-netbsd*.  For targets that recently
+	# switched to ELF, *-*-netbsd* would select the old
+	# object file format.  This provides both forward
+	# compatibility and a consistent mechanism for selecting the
+	# object file format.
+	#
+	# Note: NetBSD doesn't particularly care about the vendor
+	# portion of the name.  We always set it to "unknown".
+	sysctl="sysctl -n hw.machine_arch"
+	UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
+	    /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
+	case "${UNAME_MACHINE_ARCH}" in
+	    armeb) machine=armeb-unknown ;;
+	    arm*) machine=arm-unknown ;;
+	    sh3el) machine=shl-unknown ;;
+	    sh3eb) machine=sh-unknown ;;
+	    sh5el) machine=sh5le-unknown ;;
+	    *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
+	esac
+	# The Operating System including object format, if it has switched
+	# to ELF recently, or will in the future.
+	case "${UNAME_MACHINE_ARCH}" in
+	    arm*|i386|m68k|ns32k|sh3*|sparc|vax)
+		eval $set_cc_for_build
+		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
+			| grep __ELF__ >/dev/null
+		then
+		    # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
+		    # Return netbsd for either.  FIX?
+		    os=netbsd
+		else
+		    os=netbsdelf
+		fi
+		;;
+	    *)
+	        os=netbsd
+		;;
+	esac
+	# The OS release
+	# Debian GNU/NetBSD machines have a different userland, and
+	# thus, need a distinct triplet. However, they do not need
+	# kernel version information, so it can be replaced with a
+	# suitable tag, in the style of linux-gnu.
+	case "${UNAME_VERSION}" in
+	    Debian*)
+		release='-gnu'
+		;;
+	    *)
+		release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+		;;
+	esac
+	# Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
+	# contains redundant information, the shorter form:
+	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
+	echo "${machine}-${os}${release}"
+	exit ;;
+    *:OpenBSD:*:*)
+	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
+	echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
+	exit ;;
+    *:ekkoBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
+	exit ;;
+    *:SolidBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}
+	exit ;;
+    macppc:MirBSD:*:*)
+	echo powerpc-unknown-mirbsd${UNAME_RELEASE}
+	exit ;;
+    *:MirBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
+	exit ;;
+    alpha:OSF1:*:*)
+	case $UNAME_RELEASE in
+	*4.0)
+		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
+		;;
+	*5.*)
+	        UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
+		;;
+	esac
+	# According to Compaq, /usr/sbin/psrinfo has been available on
+	# OSF/1 and Tru64 systems produced since 1995.  I hope that
+	# covers most systems running today.  This code pipes the CPU
+	# types through head -n 1, so we only detect the type of CPU 0.
+	ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^  The alpha \(.*\) processor.*$/\1/p' | head -n 1`
+	case "$ALPHA_CPU_TYPE" in
+	    "EV4 (21064)")
+		UNAME_MACHINE="alpha" ;;
+	    "EV4.5 (21064)")
+		UNAME_MACHINE="alpha" ;;
+	    "LCA4 (21066/21068)")
+		UNAME_MACHINE="alpha" ;;
+	    "EV5 (21164)")
+		UNAME_MACHINE="alphaev5" ;;
+	    "EV5.6 (21164A)")
+		UNAME_MACHINE="alphaev56" ;;
+	    "EV5.6 (21164PC)")
+		UNAME_MACHINE="alphapca56" ;;
+	    "EV5.7 (21164PC)")
+		UNAME_MACHINE="alphapca57" ;;
+	    "EV6 (21264)")
+		UNAME_MACHINE="alphaev6" ;;
+	    "EV6.7 (21264A)")
+		UNAME_MACHINE="alphaev67" ;;
+	    "EV6.8CB (21264C)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.8AL (21264B)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.8CX (21264D)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.9A (21264/EV69A)")
+		UNAME_MACHINE="alphaev69" ;;
+	    "EV7 (21364)")
+		UNAME_MACHINE="alphaev7" ;;
+	    "EV7.9 (21364A)")
+		UNAME_MACHINE="alphaev79" ;;
+	esac
+	# A Pn.n version is a patched version.
+	# A Vn.n version is a released version.
+	# A Tn.n version is a released field test version.
+	# A Xn.n version is an unreleased experimental baselevel.
+	# 1.2 uses "1.2" for uname -r.
+	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+	exit ;;
+    Alpha\ *:Windows_NT*:*)
+	# How do we know it's Interix rather than the generic POSIX subsystem?
+	# Should we change UNAME_MACHINE based on the output of uname instead
+	# of the specific Alpha model?
+	echo alpha-pc-interix
+	exit ;;
+    21064:Windows_NT:50:3)
+	echo alpha-dec-winnt3.5
+	exit ;;
+    Amiga*:UNIX_System_V:4.0:*)
+	echo m68k-unknown-sysv4
+	exit ;;
+    *:[Aa]miga[Oo][Ss]:*:*)
+	echo ${UNAME_MACHINE}-unknown-amigaos
+	exit ;;
+    *:[Mm]orph[Oo][Ss]:*:*)
+	echo ${UNAME_MACHINE}-unknown-morphos
+	exit ;;
+    *:OS/390:*:*)
+	echo i370-ibm-openedition
+	exit ;;
+    *:z/VM:*:*)
+	echo s390-ibm-zvmoe
+	exit ;;
+    *:OS400:*:*)
+        echo powerpc-ibm-os400
+	exit ;;
+    arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
+	echo arm-acorn-riscix${UNAME_RELEASE}
+	exit ;;
+    arm:riscos:*:*|arm:RISCOS:*:*)
+	echo arm-unknown-riscos
+	exit ;;
+    SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
+	echo hppa1.1-hitachi-hiuxmpp
+	exit ;;
+    Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
+	# akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
+	if test "`(/bin/universe) 2>/dev/null`" = att ; then
+		echo pyramid-pyramid-sysv3
+	else
+		echo pyramid-pyramid-bsd
+	fi
+	exit ;;
+    NILE*:*:*:dcosx)
+	echo pyramid-pyramid-svr4
+	exit ;;
+    DRS?6000:unix:4.0:6*)
+	echo sparc-icl-nx6
+	exit ;;
+    DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
+	case `/usr/bin/uname -p` in
+	    sparc) echo sparc-icl-nx7; exit ;;
+	esac ;;
+    sun4H:SunOS:5.*:*)
+	echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
+	echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
+	eval $set_cc_for_build
+	SUN_ARCH="i386"
+	# If there is a compiler, see if it is configured for 64-bit objects.
+	# Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
+	# This test works for both compilers.
+	if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+	    if echo '\n#ifdef __amd64\nIS_64BIT_ARCH\n#endif' | \
+		(CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+		grep IS_64BIT_ARCH >/dev/null
+	    then
+		SUN_ARCH="x86_64"
+	    fi
+	fi
+	echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4*:SunOS:6*:*)
+	# According to config.sub, this is the proper way to canonicalize
+	# SunOS6.  Hard to guess exactly what SunOS6 will be like, but
+	# it's likely to be more like Solaris than SunOS4.
+	echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4*:SunOS:*:*)
+	case "`/usr/bin/arch -k`" in
+	    Series*|S4*)
+		UNAME_RELEASE=`uname -v`
+		;;
+	esac
+	# Japanese Language versions have a version number like `4.1.3-JL'.
+	echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
+	exit ;;
+    sun3*:SunOS:*:*)
+	echo m68k-sun-sunos${UNAME_RELEASE}
+	exit ;;
+    sun*:*:4.2BSD:*)
+	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
+	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
+	case "`/bin/arch`" in
+	    sun3)
+		echo m68k-sun-sunos${UNAME_RELEASE}
+		;;
+	    sun4)
+		echo sparc-sun-sunos${UNAME_RELEASE}
+		;;
+	esac
+	exit ;;
+    aushp:SunOS:*:*)
+	echo sparc-auspex-sunos${UNAME_RELEASE}
+	exit ;;
+    # The situation for MiNT is a little confusing.  The machine name
+    # can be virtually everything (everything which is not
+    # "atarist" or "atariste" at least should have a processor
+    # > m68000).  The system name ranges from "MiNT" over "FreeMiNT"
+    # to the lowercase version "mint" (or "freemint").  Finally
+    # the system name "TOS" denotes a system which is actually not
+    # MiNT.  But MiNT is downward compatible to TOS, so this should
+    # be no problem.
+    atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
+        echo m68k-atari-mint${UNAME_RELEASE}
+	exit ;;
+    atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
+	echo m68k-atari-mint${UNAME_RELEASE}
+        exit ;;
+    *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
+        echo m68k-atari-mint${UNAME_RELEASE}
+	exit ;;
+    milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
+        echo m68k-milan-mint${UNAME_RELEASE}
+        exit ;;
+    hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
+        echo m68k-hades-mint${UNAME_RELEASE}
+        exit ;;
+    *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
+        echo m68k-unknown-mint${UNAME_RELEASE}
+        exit ;;
+    m68k:machten:*:*)
+	echo m68k-apple-machten${UNAME_RELEASE}
+	exit ;;
+    powerpc:machten:*:*)
+	echo powerpc-apple-machten${UNAME_RELEASE}
+	exit ;;
+    RISC*:Mach:*:*)
+	echo mips-dec-mach_bsd4.3
+	exit ;;
+    RISC*:ULTRIX:*:*)
+	echo mips-dec-ultrix${UNAME_RELEASE}
+	exit ;;
+    VAX*:ULTRIX*:*:*)
+	echo vax-dec-ultrix${UNAME_RELEASE}
+	exit ;;
+    2020:CLIX:*:* | 2430:CLIX:*:*)
+	echo clipper-intergraph-clix${UNAME_RELEASE}
+	exit ;;
+    mips:*:*:UMIPS | mips:*:*:RISCos)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+#ifdef __cplusplus
+#include <stdio.h>  /* for printf() prototype */
+	int main (int argc, char *argv[]) {
+#else
+	int main (argc, argv) int argc; char *argv[]; {
+#endif
+	#if defined (host_mips) && defined (MIPSEB)
+	#if defined (SYSTYPE_SYSV)
+	  printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
+	#endif
+	#if defined (SYSTYPE_SVR4)
+	  printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
+	#endif
+	#if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
+	  printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
+	#endif
+	#endif
+	  exit (-1);
+	}
+EOF
+	$CC_FOR_BUILD -o $dummy $dummy.c &&
+	  dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
+	  SYSTEM_NAME=`$dummy $dummyarg` &&
+	    { echo "$SYSTEM_NAME"; exit; }
+	echo mips-mips-riscos${UNAME_RELEASE}
+	exit ;;
+    Motorola:PowerMAX_OS:*:*)
+	echo powerpc-motorola-powermax
+	exit ;;
+    Motorola:*:4.3:PL8-*)
+	echo powerpc-harris-powermax
+	exit ;;
+    Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
+	echo powerpc-harris-powermax
+	exit ;;
+    Night_Hawk:Power_UNIX:*:*)
+	echo powerpc-harris-powerunix
+	exit ;;
+    m88k:CX/UX:7*:*)
+	echo m88k-harris-cxux7
+	exit ;;
+    m88k:*:4*:R4*)
+	echo m88k-motorola-sysv4
+	exit ;;
+    m88k:*:3*:R3*)
+	echo m88k-motorola-sysv3
+	exit ;;
+    AViiON:dgux:*:*)
+        # DG/UX returns AViiON for all architectures
+        UNAME_PROCESSOR=`/usr/bin/uname -p`
+	if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
+	then
+	    if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
+	       [ ${TARGET_BINARY_INTERFACE}x = x ]
+	    then
+		echo m88k-dg-dgux${UNAME_RELEASE}
+	    else
+		echo m88k-dg-dguxbcs${UNAME_RELEASE}
+	    fi
+	else
+	    echo i586-dg-dgux${UNAME_RELEASE}
+	fi
+ 	exit ;;
+    M88*:DolphinOS:*:*)	# DolphinOS (SVR3)
+	echo m88k-dolphin-sysv3
+	exit ;;
+    M88*:*:R3*:*)
+	# Delta 88k system running SVR3
+	echo m88k-motorola-sysv3
+	exit ;;
+    XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
+	echo m88k-tektronix-sysv3
+	exit ;;
+    Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
+	echo m68k-tektronix-bsd
+	exit ;;
+    *:IRIX*:*:*)
+	echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
+	exit ;;
+    ????????:AIX?:[12].1:2)   # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
+	echo romp-ibm-aix     # uname -m gives an 8 hex-code CPU id
+	exit ;;               # Note that: echo "'`uname -s`'" gives 'AIX '
+    i*86:AIX:*:*)
+	echo i386-ibm-aix
+	exit ;;
+    ia64:AIX:*:*)
+	if [ -x /usr/bin/oslevel ] ; then
+		IBM_REV=`/usr/bin/oslevel`
+	else
+		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+	fi
+	echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
+	exit ;;
+    *:AIX:2:3)
+	if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
+		eval $set_cc_for_build
+		sed 's/^		//' << EOF >$dummy.c
+		#include <sys/systemcfg.h>
+
+		main()
+			{
+			if (!__power_pc())
+				exit(1);
+			puts("powerpc-ibm-aix3.2.5");
+			exit(0);
+			}
+EOF
+		if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
+		then
+			echo "$SYSTEM_NAME"
+		else
+			echo rs6000-ibm-aix3.2.5
+		fi
+	elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
+		echo rs6000-ibm-aix3.2.4
+	else
+		echo rs6000-ibm-aix3.2
+	fi
+	exit ;;
+    *:AIX:*:[456])
+	IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
+	if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
+		IBM_ARCH=rs6000
+	else
+		IBM_ARCH=powerpc
+	fi
+	if [ -x /usr/bin/oslevel ] ; then
+		IBM_REV=`/usr/bin/oslevel`
+	else
+		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+	fi
+	echo ${IBM_ARCH}-ibm-aix${IBM_REV}
+	exit ;;
+    *:AIX:*:*)
+	echo rs6000-ibm-aix
+	exit ;;
+    ibmrt:4.4BSD:*|romp-ibm:BSD:*)
+	echo romp-ibm-bsd4.4
+	exit ;;
+    ibmrt:*BSD:*|romp-ibm:BSD:*)            # covers RT/PC BSD and
+	echo romp-ibm-bsd${UNAME_RELEASE}   # 4.3 with uname added to
+	exit ;;                             # report: romp-ibm BSD 4.3
+    *:BOSX:*:*)
+	echo rs6000-bull-bosx
+	exit ;;
+    DPX/2?00:B.O.S.:*:*)
+	echo m68k-bull-sysv3
+	exit ;;
+    9000/[34]??:4.3bsd:1.*:*)
+	echo m68k-hp-bsd
+	exit ;;
+    hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
+	echo m68k-hp-bsd4.4
+	exit ;;
+    9000/[34678]??:HP-UX:*:*)
+	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+	case "${UNAME_MACHINE}" in
+	    9000/31? )            HP_ARCH=m68000 ;;
+	    9000/[34]?? )         HP_ARCH=m68k ;;
+	    9000/[678][0-9][0-9])
+		if [ -x /usr/bin/getconf ]; then
+		    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
+                    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
+                    case "${sc_cpu_version}" in
+                      523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
+                      528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+                      532)                      # CPU_PA_RISC2_0
+                        case "${sc_kernel_bits}" in
+                          32) HP_ARCH="hppa2.0n" ;;
+                          64) HP_ARCH="hppa2.0w" ;;
+			  '') HP_ARCH="hppa2.0" ;;   # HP-UX 10.20
+                        esac ;;
+                    esac
+		fi
+		if [ "${HP_ARCH}" = "" ]; then
+		    eval $set_cc_for_build
+		    sed 's/^              //' << EOF >$dummy.c
+
+              #define _HPUX_SOURCE
+              #include <stdlib.h>
+              #include <unistd.h>
+
+              int main ()
+              {
+              #if defined(_SC_KERNEL_BITS)
+                  long bits = sysconf(_SC_KERNEL_BITS);
+              #endif
+                  long cpu  = sysconf (_SC_CPU_VERSION);
+
+                  switch (cpu)
+              	{
+              	case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
+              	case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
+              	case CPU_PA_RISC2_0:
+              #if defined(_SC_KERNEL_BITS)
+              	    switch (bits)
+              		{
+              		case 64: puts ("hppa2.0w"); break;
+              		case 32: puts ("hppa2.0n"); break;
+              		default: puts ("hppa2.0"); break;
+              		} break;
+              #else  /* !defined(_SC_KERNEL_BITS) */
+              	    puts ("hppa2.0"); break;
+              #endif
+              	default: puts ("hppa1.0"); break;
+              	}
+                  exit (0);
+              }
+EOF
+		    (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
+		    test -z "$HP_ARCH" && HP_ARCH=hppa
+		fi ;;
+	esac
+	if [ ${HP_ARCH} = "hppa2.0w" ]
+	then
+	    eval $set_cc_for_build
+
+	    # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
+	    # 32-bit code.  hppa64-hp-hpux* has the same kernel and a compiler
+	    # generating 64-bit code.  GNU and HP use different nomenclature:
+	    #
+	    # $ CC_FOR_BUILD=cc ./config.guess
+	    # => hppa2.0w-hp-hpux11.23
+	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
+	    # => hppa64-hp-hpux11.23
+
+	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
+		grep __LP64__ >/dev/null
+	    then
+		HP_ARCH="hppa2.0w"
+	    else
+		HP_ARCH="hppa64"
+	    fi
+	fi
+	echo ${HP_ARCH}-hp-hpux${HPUX_REV}
+	exit ;;
+    ia64:HP-UX:*:*)
+	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+	echo ia64-hp-hpux${HPUX_REV}
+	exit ;;
+    3050*:HI-UX:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#include <unistd.h>
+	int
+	main ()
+	{
+	  long cpu = sysconf (_SC_CPU_VERSION);
+	  /* The order matters, because CPU_IS_HP_MC68K erroneously returns
+	     true for CPU_PA_RISC1_0.  CPU_IS_PA_RISC returns correct
+	     results, however.  */
+	  if (CPU_IS_PA_RISC (cpu))
+	    {
+	      switch (cpu)
+		{
+		  case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
+		  case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
+		  case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
+		  default: puts ("hppa-hitachi-hiuxwe2"); break;
+		}
+	    }
+	  else if (CPU_IS_HP_MC68K (cpu))
+	    puts ("m68k-hitachi-hiuxwe2");
+	  else puts ("unknown-hitachi-hiuxwe2");
+	  exit (0);
+	}
+EOF
+	$CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
+		{ echo "$SYSTEM_NAME"; exit; }
+	echo unknown-hitachi-hiuxwe2
+	exit ;;
+    9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
+	echo hppa1.1-hp-bsd
+	exit ;;
+    9000/8??:4.3bsd:*:*)
+	echo hppa1.0-hp-bsd
+	exit ;;
+    *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
+	echo hppa1.0-hp-mpeix
+	exit ;;
+    hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
+	echo hppa1.1-hp-osf
+	exit ;;
+    hp8??:OSF1:*:*)
+	echo hppa1.0-hp-osf
+	exit ;;
+    i*86:OSF1:*:*)
+	if [ -x /usr/sbin/sysversion ] ; then
+	    echo ${UNAME_MACHINE}-unknown-osf1mk
+	else
+	    echo ${UNAME_MACHINE}-unknown-osf1
+	fi
+	exit ;;
+    parisc*:Lites*:*:*)
+	echo hppa1.1-hp-lites
+	exit ;;
+    C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
+	echo c1-convex-bsd
+        exit ;;
+    C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
+	if getsysinfo -f scalar_acc
+	then echo c32-convex-bsd
+	else echo c2-convex-bsd
+	fi
+        exit ;;
+    C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
+	echo c34-convex-bsd
+        exit ;;
+    C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
+	echo c38-convex-bsd
+        exit ;;
+    C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
+	echo c4-convex-bsd
+        exit ;;
+    CRAY*Y-MP:*:*:*)
+	echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*[A-Z]90:*:*:*)
+	echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
+	| sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
+	      -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
+	      -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*TS:*:*:*)
+	echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*T3E:*:*:*)
+	echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*SV1:*:*:*)
+	echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    *:UNICOS/mp:*:*)
+	echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
+	FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+        FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+        FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
+        echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+        exit ;;
+    5000:UNIX_System_V:4.*:*)
+        FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+        FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+        echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+	exit ;;
+    i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
+	echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
+	exit ;;
+    sparc*:BSD/OS:*:*)
+	echo sparc-unknown-bsdi${UNAME_RELEASE}
+	exit ;;
+    *:BSD/OS:*:*)
+	echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
+	exit ;;
+    *:FreeBSD:*:*)
+	case ${UNAME_MACHINE} in
+	    pc98)
+		echo i386-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	    amd64)
+		echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	    *)
+		echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	esac
+	exit ;;
+    i*:CYGWIN*:*)
+	echo ${UNAME_MACHINE}-pc-cygwin
+	exit ;;
+    *:MINGW*:*)
+	echo ${UNAME_MACHINE}-pc-mingw32
+	exit ;;
+    i*:windows32*:*)
+    	# uname -m includes "-pc" on this system.
+    	echo ${UNAME_MACHINE}-mingw32
+	exit ;;
+    i*:PW*:*)
+	echo ${UNAME_MACHINE}-pc-pw32
+	exit ;;
+    *:Interix*:[3456]*)
+    	case ${UNAME_MACHINE} in
+	    x86)
+		echo i586-pc-interix${UNAME_RELEASE}
+		exit ;;
+	    EM64T | authenticamd | genuineintel)
+		echo x86_64-unknown-interix${UNAME_RELEASE}
+		exit ;;
+	    IA64)
+		echo ia64-unknown-interix${UNAME_RELEASE}
+		exit ;;
+	esac ;;
+    [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
+	echo i${UNAME_MACHINE}-pc-mks
+	exit ;;
+    i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
+	# How do we know it's Interix rather than the generic POSIX subsystem?
+	# It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
+	# UNAME_MACHINE based on the output of uname instead of i386?
+	echo i586-pc-interix
+	exit ;;
+    i*:UWIN*:*)
+	echo ${UNAME_MACHINE}-pc-uwin
+	exit ;;
+    amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
+	echo x86_64-unknown-cygwin
+	exit ;;
+    p*:CYGWIN*:*)
+	echo powerpcle-unknown-cygwin
+	exit ;;
+    prep*:SunOS:5.*:*)
+	echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    *:GNU:*:*)
+	# the GNU system
+	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
+	exit ;;
+    *:GNU/*:*:*)
+	# other systems with GNU libc and userland
+	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu
+	exit ;;
+    i*86:Minix:*:*)
+	echo ${UNAME_MACHINE}-pc-minix
+	exit ;;
+    arm*:Linux:*:*)
+	eval $set_cc_for_build
+	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
+	    | grep -q __ARM_EABI__
+	then
+	    echo ${UNAME_MACHINE}-unknown-linux-gnu
+	else
+	    echo ${UNAME_MACHINE}-unknown-linux-gnueabi
+	fi
+	exit ;;
+    avr32*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    cris:Linux:*:*)
+	echo cris-axis-linux-gnu
+	exit ;;
+    crisv32:Linux:*:*)
+	echo crisv32-axis-linux-gnu
+	exit ;;
+    frv:Linux:*:*)
+    	echo frv-unknown-linux-gnu
+	exit ;;
+    ia64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    m32r*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    m68*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    mips:Linux:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#undef CPU
+	#undef mips
+	#undef mipsel
+	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+	CPU=mipsel
+	#else
+	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+	CPU=mips
+	#else
+	CPU=
+	#endif
+	#endif
+EOF
+	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
+	    /^CPU/{
+		s: ::g
+		p
+	    }'`"
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+	;;
+    mips64:Linux:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#undef CPU
+	#undef mips64
+	#undef mips64el
+	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+	CPU=mips64el
+	#else
+	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+	CPU=mips64
+	#else
+	CPU=
+	#endif
+	#endif
+EOF
+	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
+	    /^CPU/{
+		s: ::g
+		p
+	    }'`"
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+	;;
+    or32:Linux:*:*)
+	echo or32-unknown-linux-gnu
+	exit ;;
+    ppc:Linux:*:*)
+	echo powerpc-unknown-linux-gnu
+	exit ;;
+    ppc64:Linux:*:*)
+	echo powerpc64-unknown-linux-gnu
+	exit ;;
+    alpha:Linux:*:*)
+	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
+	  EV5)   UNAME_MACHINE=alphaev5 ;;
+	  EV56)  UNAME_MACHINE=alphaev56 ;;
+	  PCA56) UNAME_MACHINE=alphapca56 ;;
+	  PCA57) UNAME_MACHINE=alphapca56 ;;
+	  EV6)   UNAME_MACHINE=alphaev6 ;;
+	  EV67)  UNAME_MACHINE=alphaev67 ;;
+	  EV68*) UNAME_MACHINE=alphaev68 ;;
+        esac
+	objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null
+	if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
+	echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
+	exit ;;
+    padre:Linux:*:*)
+	echo sparc-unknown-linux-gnu
+	exit ;;
+    parisc:Linux:*:* | hppa:Linux:*:*)
+	# Look for CPU level
+	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
+	  PA7*) echo hppa1.1-unknown-linux-gnu ;;
+	  PA8*) echo hppa2.0-unknown-linux-gnu ;;
+	  *)    echo hppa-unknown-linux-gnu ;;
+	esac
+	exit ;;
+    parisc64:Linux:*:* | hppa64:Linux:*:*)
+	echo hppa64-unknown-linux-gnu
+	exit ;;
+    s390:Linux:*:* | s390x:Linux:*:*)
+	echo ${UNAME_MACHINE}-ibm-linux
+	exit ;;
+    sh64*:Linux:*:*)
+    	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    sh*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    sparc:Linux:*:* | sparc64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    vax:Linux:*:*)
+	echo ${UNAME_MACHINE}-dec-linux-gnu
+	exit ;;
+    x86_64:Linux:*:*)
+	echo x86_64-unknown-linux-gnu
+	exit ;;
+    xtensa*:Linux:*:*)
+    	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
+    i*86:Linux:*:*)
+	# The BFD linker knows what the default object file format is, so
+	# first see if it will tell us. cd to the root directory to prevent
+	# problems with other programs or directories called `ld' in the path.
+	# Set LC_ALL=C to ensure ld outputs messages in English.
+	ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \
+			 | sed -ne '/supported targets:/!d
+				    s/[ 	][ 	]*/ /g
+				    s/.*supported targets: *//
+				    s/ .*//
+				    p'`
+        case "$ld_supported_targets" in
+	  elf32-i386)
+		TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu"
+		;;
+	  a.out-i386-linux)
+		echo "${UNAME_MACHINE}-pc-linux-gnuaout"
+		exit ;;
+	  "")
+		# Either a pre-BFD a.out linker (linux-gnuoldld) or
+		# one that does not give us useful --help.
+		echo "${UNAME_MACHINE}-pc-linux-gnuoldld"
+		exit ;;
+	esac
+	# Determine whether the default compiler is a.out or elf
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#include <features.h>
+	#ifdef __ELF__
+	# ifdef __GLIBC__
+	#  if __GLIBC__ >= 2
+	LIBC=gnu
+	#  else
+	LIBC=gnulibc1
+	#  endif
+	# else
+	LIBC=gnulibc1
+	# endif
+	#else
+	#if defined(__INTEL_COMPILER) || defined(__PGI) || defined(__SUNPRO_C) || defined(__SUNPRO_CC)
+	LIBC=gnu
+	#else
+	LIBC=gnuaout
+	#endif
+	#endif
+	#ifdef __dietlibc__
+	LIBC=dietlibc
+	#endif
+EOF
+	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
+	    /^LIBC/{
+		s: ::g
+		p
+	    }'`"
+	test x"${LIBC}" != x && {
+		echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
+		exit
+	}
+	test x"${TENTATIVE}" != x && { echo "${TENTATIVE}"; exit; }
+	;;
+    i*86:DYNIX/ptx:4*:*)
+	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
+	# earlier versions are messed up and put the nodename in both
+	# sysname and nodename.
+	echo i386-sequent-sysv4
+	exit ;;
+    i*86:UNIX_SV:4.2MP:2.*)
+        # Unixware is an offshoot of SVR4, but it has its own version
+        # number series starting with 2...
+        # I am not positive that other SVR4 systems won't match this,
+	# I just have to hope.  -- rms.
+        # Use sysv4.2uw... so that sysv4* matches it.
+	echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
+	exit ;;
+    i*86:OS/2:*:*)
+	# If we were able to find `uname', then EMX Unix compatibility
+	# is probably installed.
+	echo ${UNAME_MACHINE}-pc-os2-emx
+	exit ;;
+    i*86:XTS-300:*:STOP)
+	echo ${UNAME_MACHINE}-unknown-stop
+	exit ;;
+    i*86:atheos:*:*)
+	echo ${UNAME_MACHINE}-unknown-atheos
+	exit ;;
+    i*86:syllable:*:*)
+	echo ${UNAME_MACHINE}-pc-syllable
+	exit ;;
+    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
+	echo i386-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    i*86:*DOS:*:*)
+	echo ${UNAME_MACHINE}-pc-msdosdjgpp
+	exit ;;
+    i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
+	UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
+	if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
+		echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
+	else
+		echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
+	fi
+	exit ;;
+    i*86:*:5:[678]*)
+    	# UnixWare 7.x, OpenUNIX and OpenServer 6.
+	case `/bin/uname -X | grep "^Machine"` in
+	    *486*)	     UNAME_MACHINE=i486 ;;
+	    *Pentium)	     UNAME_MACHINE=i586 ;;
+	    *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
+	esac
+	echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
+	exit ;;
+    i*86:*:3.2:*)
+	if test -f /usr/options/cb.name; then
+		UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
+		echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
+	elif /bin/uname -X 2>/dev/null >/dev/null ; then
+		UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
+		(/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
+		(/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
+			&& UNAME_MACHINE=i586
+		(/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
+			&& UNAME_MACHINE=i686
+		(/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
+			&& UNAME_MACHINE=i686
+		echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
+	else
+		echo ${UNAME_MACHINE}-pc-sysv32
+	fi
+	exit ;;
+    pc:*:*:*)
+	# Left here for compatibility:
+        # uname -m prints for DJGPP always 'pc', but it prints nothing about
+        # the processor, so we play safe by assuming i386.
+	echo i386-pc-msdosdjgpp
+        exit ;;
+    Intel:Mach:3*:*)
+	echo i386-pc-mach3
+	exit ;;
+    paragon:*:*:*)
+	echo i860-intel-osf1
+	exit ;;
+    i860:*:4.*:*) # i860-SVR4
+	if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
+	  echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
+	else # Add other i860-SVR4 vendors below as they are discovered.
+	  echo i860-unknown-sysv${UNAME_RELEASE}  # Unknown i860-SVR4
+	fi
+	exit ;;
+    mini*:CTIX:SYS*5:*)
+	# "miniframe"
+	echo m68010-convergent-sysv
+	exit ;;
+    mc68k:UNIX:SYSTEM5:3.51m)
+	echo m68k-convergent-sysv
+	exit ;;
+    M680?0:D-NIX:5.3:*)
+	echo m68k-diab-dnix
+	exit ;;
+    M68*:*:R3V[5678]*:*)
+	test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
+    3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
+	OS_REL=''
+	test -r /etc/.relid \
+	&& OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+	  && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+	  && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+    3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
+        /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+          && { echo i486-ncr-sysv4; exit; } ;;
+    m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
+	echo m68k-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    mc68030:UNIX_System_V:4.*:*)
+	echo m68k-atari-sysv4
+	exit ;;
+    TSUNAMI:LynxOS:2.*:*)
+	echo sparc-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    rs6000:LynxOS:2.*:*)
+	echo rs6000-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*)
+	echo powerpc-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    SM[BE]S:UNIX_SV:*:*)
+	echo mips-dde-sysv${UNAME_RELEASE}
+	exit ;;
+    RM*:ReliantUNIX-*:*:*)
+	echo mips-sni-sysv4
+	exit ;;
+    RM*:SINIX-*:*:*)
+	echo mips-sni-sysv4
+	exit ;;
+    *:SINIX-*:*:*)
+	if uname -p 2>/dev/null >/dev/null ; then
+		UNAME_MACHINE=`(uname -p) 2>/dev/null`
+		echo ${UNAME_MACHINE}-sni-sysv4
+	else
+		echo ns32k-sni-sysv
+	fi
+	exit ;;
+    PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
+                      # says <Richard.M.Bartel@ccMail.Census.GOV>
+        echo i586-unisys-sysv4
+        exit ;;
+    *:UNIX_System_V:4*:FTX*)
+	# From Gerald Hewes <hewes@openmarket.com>.
+	# How about differentiating between stratus architectures? -djm
+	echo hppa1.1-stratus-sysv4
+	exit ;;
+    *:*:*:FTX*)
+	# From seanf@swdc.stratus.com.
+	echo i860-stratus-sysv4
+	exit ;;
+    i*86:VOS:*:*)
+	# From Paul.Green@stratus.com.
+	echo ${UNAME_MACHINE}-stratus-vos
+	exit ;;
+    *:VOS:*:*)
+	# From Paul.Green@stratus.com.
+	echo hppa1.1-stratus-vos
+	exit ;;
+    mc68*:A/UX:*:*)
+	echo m68k-apple-aux${UNAME_RELEASE}
+	exit ;;
+    news*:NEWS-OS:6*:*)
+	echo mips-sony-newsos6
+	exit ;;
+    R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
+	if [ -d /usr/nec ]; then
+	        echo mips-nec-sysv${UNAME_RELEASE}
+	else
+	        echo mips-unknown-sysv${UNAME_RELEASE}
+	fi
+        exit ;;
+    BeBox:BeOS:*:*)	# BeOS running on hardware made by Be, PPC only.
+	echo powerpc-be-beos
+	exit ;;
+    BeMac:BeOS:*:*)	# BeOS running on Mac or Mac clone, PPC only.
+	echo powerpc-apple-beos
+	exit ;;
+    BePC:BeOS:*:*)	# BeOS running on Intel PC compatible.
+	echo i586-pc-beos
+	exit ;;
+    BePC:Haiku:*:*)	# Haiku running on Intel PC compatible.
+	echo i586-pc-haiku
+	exit ;;
+    SX-4:SUPER-UX:*:*)
+	echo sx4-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-5:SUPER-UX:*:*)
+	echo sx5-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-6:SUPER-UX:*:*)
+	echo sx6-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-7:SUPER-UX:*:*)
+	echo sx7-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8:SUPER-UX:*:*)
+	echo sx8-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8R:SUPER-UX:*:*)
+	echo sx8r-nec-superux${UNAME_RELEASE}
+	exit ;;
+    Power*:Rhapsody:*:*)
+	echo powerpc-apple-rhapsody${UNAME_RELEASE}
+	exit ;;
+    *:Rhapsody:*:*)
+	echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
+	exit ;;
+    *:Darwin:*:*)
+	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
+	case $UNAME_PROCESSOR in
+	    unknown) UNAME_PROCESSOR=powerpc ;;
+	esac
+	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
+	exit ;;
+    *:procnto*:*:* | *:QNX:[0123456789]*:*)
+	UNAME_PROCESSOR=`uname -p`
+	if test "$UNAME_PROCESSOR" = "x86"; then
+		UNAME_PROCESSOR=i386
+		UNAME_MACHINE=pc
+	fi
+	echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
+	exit ;;
+    *:QNX:*:4*)
+	echo i386-pc-qnx
+	exit ;;
+    NSE-?:NONSTOP_KERNEL:*:*)
+	echo nse-tandem-nsk${UNAME_RELEASE}
+	exit ;;
+    NSR-?:NONSTOP_KERNEL:*:*)
+	echo nsr-tandem-nsk${UNAME_RELEASE}
+	exit ;;
+    *:NonStop-UX:*:*)
+	echo mips-compaq-nonstopux
+	exit ;;
+    BS2000:POSIX*:*:*)
+	echo bs2000-siemens-sysv
+	exit ;;
+    DS/*:UNIX_System_V:*:*)
+	echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
+	exit ;;
+    *:Plan9:*:*)
+	# "uname -m" is not consistent, so use $cputype instead. 386
+	# is converted to i386 for consistency with other x86
+	# operating systems.
+	if test "$cputype" = "386"; then
+	    UNAME_MACHINE=i386
+	else
+	    UNAME_MACHINE="$cputype"
+	fi
+	echo ${UNAME_MACHINE}-unknown-plan9
+	exit ;;
+    *:TOPS-10:*:*)
+	echo pdp10-unknown-tops10
+	exit ;;
+    *:TENEX:*:*)
+	echo pdp10-unknown-tenex
+	exit ;;
+    KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
+	echo pdp10-dec-tops20
+	exit ;;
+    XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
+	echo pdp10-xkl-tops20
+	exit ;;
+    *:TOPS-20:*:*)
+	echo pdp10-unknown-tops20
+	exit ;;
+    *:ITS:*:*)
+	echo pdp10-unknown-its
+	exit ;;
+    SEI:*:*:SEIUX)
+        echo mips-sei-seiux${UNAME_RELEASE}
+	exit ;;
+    *:DragonFly:*:*)
+	echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
+	exit ;;
+    *:*VMS:*:*)
+    	UNAME_MACHINE=`(uname -p) 2>/dev/null`
+	case "${UNAME_MACHINE}" in
+	    A*) echo alpha-dec-vms ; exit ;;
+	    I*) echo ia64-dec-vms ; exit ;;
+	    V*) echo vax-dec-vms ; exit ;;
+	esac ;;
+    *:XENIX:*:SysV)
+	echo i386-pc-xenix
+	exit ;;
+    i*86:skyos:*:*)
+	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
+	exit ;;
+    i*86:rdos:*:*)
+	echo ${UNAME_MACHINE}-pc-rdos
+	exit ;;
+esac
+
+#echo '(No uname command or uname output not recognized.)' 1>&2
+#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2
+
+eval $set_cc_for_build
+cat >$dummy.c <<EOF
+#ifdef _SEQUENT_
+# include <sys/types.h>
+# include <sys/utsname.h>
+#endif
+main ()
+{
+#if defined (sony)
+#if defined (MIPSEB)
+  /* BFD wants "bsd" instead of "newsos".  Perhaps BFD should be changed,
+     I don't know....  */
+  printf ("mips-sony-bsd\n"); exit (0);
+#else
+#include <sys/param.h>
+  printf ("m68k-sony-newsos%s\n",
+#ifdef NEWSOS4
+          "4"
+#else
+	  ""
+#endif
+         ); exit (0);
+#endif
+#endif
+
+#if defined (__arm) && defined (__acorn) && defined (__unix)
+  printf ("arm-acorn-riscix\n"); exit (0);
+#endif
+
+#if defined (hp300) && !defined (hpux)
+  printf ("m68k-hp-bsd\n"); exit (0);
+#endif
+
+#if defined (NeXT)
+#if !defined (__ARCHITECTURE__)
+#define __ARCHITECTURE__ "m68k"
+#endif
+  int version;
+  version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
+  if (version < 4)
+    printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
+  else
+    printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
+  exit (0);
+#endif
+
+#if defined (MULTIMAX) || defined (n16)
+#if defined (UMAXV)
+  printf ("ns32k-encore-sysv\n"); exit (0);
+#else
+#if defined (CMU)
+  printf ("ns32k-encore-mach\n"); exit (0);
+#else
+  printf ("ns32k-encore-bsd\n"); exit (0);
+#endif
+#endif
+#endif
+
+#if defined (__386BSD__)
+  printf ("i386-pc-bsd\n"); exit (0);
+#endif
+
+#if defined (sequent)
+#if defined (i386)
+  printf ("i386-sequent-dynix\n"); exit (0);
+#endif
+#if defined (ns32000)
+  printf ("ns32k-sequent-dynix\n"); exit (0);
+#endif
+#endif
+
+#if defined (_SEQUENT_)
+    struct utsname un;
+
+    uname(&un);
+
+    if (strncmp(un.version, "V2", 2) == 0) {
+	printf ("i386-sequent-ptx2\n"); exit (0);
+    }
+    if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
+	printf ("i386-sequent-ptx1\n"); exit (0);
+    }
+    printf ("i386-sequent-ptx\n"); exit (0);
+
+#endif
+
+#if defined (vax)
+# if !defined (ultrix)
+#  include <sys/param.h>
+#  if defined (BSD)
+#   if BSD == 43
+      printf ("vax-dec-bsd4.3\n"); exit (0);
+#   else
+#    if BSD == 199006
+      printf ("vax-dec-bsd4.3reno\n"); exit (0);
+#    else
+      printf ("vax-dec-bsd\n"); exit (0);
+#    endif
+#   endif
+#  else
+    printf ("vax-dec-bsd\n"); exit (0);
+#  endif
+# else
+    printf ("vax-dec-ultrix\n"); exit (0);
+# endif
+#endif
+
+#if defined (alliant) && defined (i860)
+  printf ("i860-alliant-bsd\n"); exit (0);
+#endif
+
+  exit (1);
+}
+EOF
+
+$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
+	{ echo "$SYSTEM_NAME"; exit; }
+
+# Apollos put the system type in the environment.
+
+test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }
+
+# Convex versions that predate uname can use getsysinfo(1)
+
+if [ -x /usr/convex/getsysinfo ]
+then
+    case `getsysinfo -f cpu_type` in
+    c1*)
+	echo c1-convex-bsd
+	exit ;;
+    c2*)
+	if getsysinfo -f scalar_acc
+	then echo c32-convex-bsd
+	else echo c2-convex-bsd
+	fi
+	exit ;;
+    c34*)
+	echo c34-convex-bsd
+	exit ;;
+    c38*)
+	echo c38-convex-bsd
+	exit ;;
+    c4*)
+	echo c4-convex-bsd
+	exit ;;
+    esac
+fi
+
+cat >&2 <<EOF
+$0: unable to guess system type
+
+This script, last modified $timestamp, has failed to recognize
+the operating system you are using. It is advised that you
+download the most up to date version of the config scripts from
+
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+and
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+
+If the version you run ($0) is already up to date, please
+send the following data and any information you think might be
+pertinent to <config-patches@gnu.org> in order to provide the needed
+information to handle your system.
+
+config.guess timestamp = $timestamp
+
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null`
+
+hostinfo               = `(hostinfo) 2>/dev/null`
+/bin/universe          = `(/bin/universe) 2>/dev/null`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null`
+/bin/arch              = `(/bin/arch) 2>/dev/null`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
+
+UNAME_MACHINE = ${UNAME_MACHINE}
+UNAME_RELEASE = ${UNAME_RELEASE}
+UNAME_SYSTEM  = ${UNAME_SYSTEM}
+UNAME_VERSION = ${UNAME_VERSION}
+EOF
+
+exit 1
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
Index: /issm/trunk-jpl-damage/config.sub
===================================================================
--- /issm/trunk-jpl-damage/config.sub	(revision 11330)
+++ /issm/trunk-jpl-damage/config.sub	(revision 11330)
@@ -0,0 +1,1677 @@
+#! /bin/sh
+# Configuration validation subroutine script.
+#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
+#   Free Software Foundation, Inc.
+
+timestamp='2008-09-08'
+
+# This file is (in principle) common to ALL GNU software.
+# The presence of a machine in this file suggests that SOME GNU software
+# can handle that machine.  It does not imply ALL GNU software can.
+#
+# This file 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.
+#
+# 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., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+
+# Please send patches to <config-patches@gnu.org>.  Submit a context
+# diff and a properly formatted ChangeLog entry.
+#
+# Configuration subroutine to validate and canonicalize a configuration type.
+# Supply the specified configuration type as an argument.
+# If it is invalid, we print an error message on stderr and exit with code 1.
+# Otherwise, we print the canonical config type on stdout and succeed.
+
+# This file is supposed to be the same for all GNU packages
+# and recognize all the CPU types, system types and aliases
+# that are meaningful with *any* GNU software.
+# Each package is responsible for reporting which valid configurations
+# it does not support.  The user should be able to distinguish
+# a failure to support a valid configuration from a meaningless
+# configuration.
+
+# The goal of this file is to map all the various variations of a given
+# machine specification into a single specification in the form:
+#	CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
+# or in some cases, the newer four-part form:
+#	CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
+# It is wrong to echo any other type of specification.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION] CPU-MFR-OPSYS
+       $0 [OPTION] ALIAS
+
+Canonicalize a configuration name.
+
+Operation modes:
+  -h, --help         print this help, then exit
+  -t, --time-stamp   print date of last modification, then exit
+  -v, --version      print version number, then exit
+
+Report bugs and patches to <config-patches@gnu.org>."
+
+version="\
+GNU config.sub ($timestamp)
+
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
+2002, 2003, 2004, 2005, 2006, 2007, 2008 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."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+  case $1 in
+    --time-stamp | --time* | -t )
+       echo "$timestamp" ; exit ;;
+    --version | -v )
+       echo "$version" ; exit ;;
+    --help | --h* | -h )
+       echo "$usage"; exit ;;
+    -- )     # Stop option processing
+       shift; break ;;
+    - )	# Use stdin as input.
+       break ;;
+    -* )
+       echo "$me: invalid option $1$help"
+       exit 1 ;;
+
+    *local*)
+       # First pass through any local machine types.
+       echo $1
+       exit ;;
+
+    * )
+       break ;;
+  esac
+done
+
+case $# in
+ 0) echo "$me: missing argument$help" >&2
+    exit 1;;
+ 1) ;;
+ *) echo "$me: too many arguments$help" >&2
+    exit 1;;
+esac
+
+# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
+# Here we must recognize all the valid KERNEL-OS combinations.
+maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
+case $maybe_os in
+  nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \
+  uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \
+  storm-chaos* | os2-emx* | rtmk-nova*)
+    os=-$maybe_os
+    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
+    ;;
+  *)
+    basic_machine=`echo $1 | sed 's/-[^-]*$//'`
+    if [ $basic_machine != $1 ]
+    then os=`echo $1 | sed 's/.*-/-/'`
+    else os=; fi
+    ;;
+esac
+
+### Let's recognize common machines as not being operating systems so
+### that things like config.sub decstation-3100 work.  We also
+### recognize some manufacturers as not being operating systems, so we
+### can provide default operating systems below.
+case $os in
+	-sun*os*)
+		# Prevent following clause from handling this invalid input.
+		;;
+	-dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
+	-att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
+	-unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
+	-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
+	-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
+	-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
+	-apple | -axis | -knuth | -cray)
+		os=
+		basic_machine=$1
+		;;
+	-sim | -cisco | -oki | -wec | -winbond)
+		os=
+		basic_machine=$1
+		;;
+	-scout)
+		;;
+	-wrs)
+		os=-vxworks
+		basic_machine=$1
+		;;
+	-chorusos*)
+		os=-chorusos
+		basic_machine=$1
+		;;
+ 	-chorusrdb)
+ 		os=-chorusrdb
+		basic_machine=$1
+ 		;;
+	-hiux*)
+		os=-hiuxwe2
+		;;
+	-sco6)
+		os=-sco5v6
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco5)
+		os=-sco3.2v5
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco4)
+		os=-sco3.2v4
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco3.2.[4-9]*)
+		os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco3.2v[4-9]*)
+		# Don't forget version if it is 3.2v4 or newer.
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco5v6*)
+		# Don't forget version if it is 3.2v4 or newer.
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco*)
+		os=-sco3.2v2
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-udk*)
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-isc)
+		os=-isc2.2
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-clix*)
+		basic_machine=clipper-intergraph
+		;;
+	-isc*)
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-lynx*)
+		os=-lynxos
+		;;
+	-ptx*)
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
+		;;
+	-windowsnt*)
+		os=`echo $os | sed -e 's/windowsnt/winnt/'`
+		;;
+	-psos*)
+		os=-psos
+		;;
+	-mint | -mint[0-9]*)
+		basic_machine=m68k-atari
+		os=-mint
+		;;
+esac
+
+# Decode aliases for certain CPU-COMPANY combinations.
+case $basic_machine in
+	# Recognize the basic CPU types without company name.
+	# Some are omitted here because they have special meanings below.
+	1750a | 580 \
+	| a29k \
+	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
+	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
+	| am33_2.0 \
+	| arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \
+	| bfin \
+	| c4x | clipper \
+	| d10v | d30v | dlx | dsp16xx \
+	| fido | fr30 | frv \
+	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
+	| i370 | i860 | i960 | ia64 \
+	| ip2k | iq2000 \
+	| m32c | m32r | m32rle | m68000 | m68k | m88k \
+	| maxq | mb | microblaze | mcore | mep | metag \
+	| mips | mipsbe | mipseb | mipsel | mipsle \
+	| mips16 \
+	| mips64 | mips64el \
+	| mips64octeon | mips64octeonel \
+	| mips64orion | mips64orionel \
+	| mips64r5900 | mips64r5900el \
+	| mips64vr | mips64vrel \
+	| mips64vr4100 | mips64vr4100el \
+	| mips64vr4300 | mips64vr4300el \
+	| mips64vr5000 | mips64vr5000el \
+	| mips64vr5900 | mips64vr5900el \
+	| mipsisa32 | mipsisa32el \
+	| mipsisa32r2 | mipsisa32r2el \
+	| mipsisa64 | mipsisa64el \
+	| mipsisa64r2 | mipsisa64r2el \
+	| mipsisa64sb1 | mipsisa64sb1el \
+	| mipsisa64sr71k | mipsisa64sr71kel \
+	| mipstx39 | mipstx39el \
+	| mn10200 | mn10300 \
+	| mt \
+	| msp430 \
+	| nios | nios2 \
+	| ns16k | ns32k \
+	| or32 \
+	| pdp10 | pdp11 | pj | pjl \
+	| powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
+	| pyramid \
+	| score \
+	| sh | sh[1234] | sh[24]a | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
+	| sh64 | sh64le \
+	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
+	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
+	| spu | strongarm \
+	| tahoe | thumb | tic4x | tic80 | tron \
+	| v850 | v850e \
+	| we32k \
+	| x86 | xc16x | xscale | xscalee[bl] | xstormy16 | xtensa \
+	| z8k | z80)
+		basic_machine=$basic_machine-unknown
+		;;
+	m6811 | m68hc11 | m6812 | m68hc12)
+		# Motorola 68HC11/12.
+		basic_machine=$basic_machine-unknown
+		os=-none
+		;;
+	m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
+		;;
+	ms1)
+		basic_machine=mt-unknown
+		;;
+
+	# We use `pc' rather than `unknown'
+	# because (1) that's what they normally are, and
+	# (2) the word "unknown" tends to confuse beginning users.
+	i*86 | x86_64)
+	  basic_machine=$basic_machine-pc
+	  ;;
+	# Object if more than one company name word.
+	*-*-*)
+		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+		exit 1
+		;;
+	# Recognize the basic CPU types with company name.
+	580-* \
+	| a29k-* \
+	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
+	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
+	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
+	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
+	| avr-* | avr32-* \
+	| bfin-* | bs2000-* \
+	| c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \
+	| clipper-* | craynv-* | cydra-* \
+	| d10v-* | d30v-* | dlx-* \
+	| elxsi-* \
+	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
+	| h8300-* | h8500-* \
+	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
+	| i*86-* | i860-* | i960-* | ia64-* \
+	| ip2k-* | iq2000-* \
+	| m32c-* | m32r-* | m32rle-* \
+	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
+	| m88110-* | m88k-* | maxq-* | mcore-* | metag-* \
+	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
+	| mips16-* \
+	| mips64-* | mips64el-* \
+	| mips64octeon-* | mips64octeonel-* \
+	| mips64orion-* | mips64orionel-* \
+	| mips64r5900-* | mips64r5900el-* \
+	| mips64vr-* | mips64vrel-* \
+	| mips64vr4100-* | mips64vr4100el-* \
+	| mips64vr4300-* | mips64vr4300el-* \
+	| mips64vr5000-* | mips64vr5000el-* \
+	| mips64vr5900-* | mips64vr5900el-* \
+	| mipsisa32-* | mipsisa32el-* \
+	| mipsisa32r2-* | mipsisa32r2el-* \
+	| mipsisa64-* | mipsisa64el-* \
+	| mipsisa64r2-* | mipsisa64r2el-* \
+	| mipsisa64sb1-* | mipsisa64sb1el-* \
+	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
+	| mipstx39-* | mipstx39el-* \
+	| mmix-* \
+	| mt-* \
+	| msp430-* \
+	| nios-* | nios2-* \
+	| none-* | np1-* | ns16k-* | ns32k-* \
+	| orion-* \
+	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
+	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
+	| pyramid-* \
+	| romp-* | rs6000-* \
+	| sh-* | sh[1234]-* | sh[24]a-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
+	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
+	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
+	| sparclite-* \
+	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | strongarm-* | sv1-* | sx?-* \
+	| tahoe-* | thumb-* \
+	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* | tile-* \
+	| tron-* \
+	| v850-* | v850e-* | vax-* \
+	| we32k-* \
+	| x86-* | x86_64-* | xc16x-* | xps100-* | xscale-* | xscalee[bl]-* \
+	| xstormy16-* | xtensa*-* \
+	| ymp-* \
+	| z8k-* | z80-*)
+		;;
+	# Recognize the basic CPU types without company name, with glob match.
+	xtensa*)
+		basic_machine=$basic_machine-unknown
+		;;
+	# Recognize the various machine names and aliases which stand
+	# for a CPU type and a company and sometimes even an OS.
+	386bsd)
+		basic_machine=i386-unknown
+		os=-bsd
+		;;
+	3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
+		basic_machine=m68000-att
+		;;
+	3b*)
+		basic_machine=we32k-att
+		;;
+	a29khif)
+		basic_machine=a29k-amd
+		os=-udi
+		;;
+    	abacus)
+		basic_machine=abacus-unknown
+		;;
+	adobe68k)
+		basic_machine=m68010-adobe
+		os=-scout
+		;;
+	alliant | fx80)
+		basic_machine=fx80-alliant
+		;;
+	altos | altos3068)
+		basic_machine=m68k-altos
+		;;
+	am29k)
+		basic_machine=a29k-none
+		os=-bsd
+		;;
+	amd64)
+		basic_machine=x86_64-pc
+		;;
+	amd64-*)
+		basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	amdahl)
+		basic_machine=580-amdahl
+		os=-sysv
+		;;
+	amiga | amiga-*)
+		basic_machine=m68k-unknown
+		;;
+	amigaos | amigados)
+		basic_machine=m68k-unknown
+		os=-amigaos
+		;;
+	amigaunix | amix)
+		basic_machine=m68k-unknown
+		os=-sysv4
+		;;
+	apollo68)
+		basic_machine=m68k-apollo
+		os=-sysv
+		;;
+	apollo68bsd)
+		basic_machine=m68k-apollo
+		os=-bsd
+		;;
+	aux)
+		basic_machine=m68k-apple
+		os=-aux
+		;;
+	balance)
+		basic_machine=ns32k-sequent
+		os=-dynix
+		;;
+	blackfin)
+		basic_machine=bfin-unknown
+		os=-linux
+		;;
+	blackfin-*)
+		basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
+	c90)
+		basic_machine=c90-cray
+		os=-unicos
+		;;
+        cegcc)
+		basic_machine=arm-unknown
+		os=-cegcc
+		;;
+	convex-c1)
+		basic_machine=c1-convex
+		os=-bsd
+		;;
+	convex-c2)
+		basic_machine=c2-convex
+		os=-bsd
+		;;
+	convex-c32)
+		basic_machine=c32-convex
+		os=-bsd
+		;;
+	convex-c34)
+		basic_machine=c34-convex
+		os=-bsd
+		;;
+	convex-c38)
+		basic_machine=c38-convex
+		os=-bsd
+		;;
+	cray | j90)
+		basic_machine=j90-cray
+		os=-unicos
+		;;
+	craynv)
+		basic_machine=craynv-cray
+		os=-unicosmp
+		;;
+	cr16)
+		basic_machine=cr16-unknown
+		os=-elf
+		;;
+	crds | unos)
+		basic_machine=m68k-crds
+		;;
+	crisv32 | crisv32-* | etraxfs*)
+		basic_machine=crisv32-axis
+		;;
+	cris | cris-* | etrax*)
+		basic_machine=cris-axis
+		;;
+	crx)
+		basic_machine=crx-unknown
+		os=-elf
+		;;
+	da30 | da30-*)
+		basic_machine=m68k-da30
+		;;
+	decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
+		basic_machine=mips-dec
+		;;
+	decsystem10* | dec10*)
+		basic_machine=pdp10-dec
+		os=-tops10
+		;;
+	decsystem20* | dec20*)
+		basic_machine=pdp10-dec
+		os=-tops20
+		;;
+	delta | 3300 | motorola-3300 | motorola-delta \
+	      | 3300-motorola | delta-motorola)
+		basic_machine=m68k-motorola
+		;;
+	delta88)
+		basic_machine=m88k-motorola
+		os=-sysv3
+		;;
+	dicos)
+		basic_machine=i686-pc
+		os=-dicos
+		;;
+	djgpp)
+		basic_machine=i586-pc
+		os=-msdosdjgpp
+		;;
+	dpx20 | dpx20-*)
+		basic_machine=rs6000-bull
+		os=-bosx
+		;;
+	dpx2* | dpx2*-bull)
+		basic_machine=m68k-bull
+		os=-sysv3
+		;;
+	ebmon29k)
+		basic_machine=a29k-amd
+		os=-ebmon
+		;;
+	elxsi)
+		basic_machine=elxsi-elxsi
+		os=-bsd
+		;;
+	encore | umax | mmax)
+		basic_machine=ns32k-encore
+		;;
+	es1800 | OSE68k | ose68k | ose | OSE)
+		basic_machine=m68k-ericsson
+		os=-ose
+		;;
+	fx2800)
+		basic_machine=i860-alliant
+		;;
+	genix)
+		basic_machine=ns32k-ns
+		;;
+	gmicro)
+		basic_machine=tron-gmicro
+		os=-sysv
+		;;
+	go32)
+		basic_machine=i386-pc
+		os=-go32
+		;;
+	h3050r* | hiux*)
+		basic_machine=hppa1.1-hitachi
+		os=-hiuxwe2
+		;;
+	h8300hms)
+		basic_machine=h8300-hitachi
+		os=-hms
+		;;
+	h8300xray)
+		basic_machine=h8300-hitachi
+		os=-xray
+		;;
+	h8500hms)
+		basic_machine=h8500-hitachi
+		os=-hms
+		;;
+	harris)
+		basic_machine=m88k-harris
+		os=-sysv3
+		;;
+	hp300-*)
+		basic_machine=m68k-hp
+		;;
+	hp300bsd)
+		basic_machine=m68k-hp
+		os=-bsd
+		;;
+	hp300hpux)
+		basic_machine=m68k-hp
+		os=-hpux
+		;;
+	hp3k9[0-9][0-9] | hp9[0-9][0-9])
+		basic_machine=hppa1.0-hp
+		;;
+	hp9k2[0-9][0-9] | hp9k31[0-9])
+		basic_machine=m68000-hp
+		;;
+	hp9k3[2-9][0-9])
+		basic_machine=m68k-hp
+		;;
+	hp9k6[0-9][0-9] | hp6[0-9][0-9])
+		basic_machine=hppa1.0-hp
+		;;
+	hp9k7[0-79][0-9] | hp7[0-79][0-9])
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k78[0-9] | hp78[0-9])
+		# FIXME: really hppa2.0-hp
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
+		# FIXME: really hppa2.0-hp
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k8[0-9][13679] | hp8[0-9][13679])
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k8[0-9][0-9] | hp8[0-9][0-9])
+		basic_machine=hppa1.0-hp
+		;;
+	hppa-next)
+		os=-nextstep3
+		;;
+	hppaosf)
+		basic_machine=hppa1.1-hp
+		os=-osf
+		;;
+	hppro)
+		basic_machine=hppa1.1-hp
+		os=-proelf
+		;;
+	i370-ibm* | ibm*)
+		basic_machine=i370-ibm
+		;;
+# I'm not sure what "Sysv32" means.  Should this be sysv3.2?
+	i*86v32)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-sysv32
+		;;
+	i*86v4*)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-sysv4
+		;;
+	i*86v)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-sysv
+		;;
+	i*86sol2)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-solaris2
+		;;
+	i386mach)
+		basic_machine=i386-mach
+		os=-mach
+		;;
+	i386-vsta | vsta)
+		basic_machine=i386-unknown
+		os=-vsta
+		;;
+	iris | iris4d)
+		basic_machine=mips-sgi
+		case $os in
+		    -irix*)
+			;;
+		    *)
+			os=-irix4
+			;;
+		esac
+		;;
+	isi68 | isi)
+		basic_machine=m68k-isi
+		os=-sysv
+		;;
+	m68knommu)
+		basic_machine=m68k-unknown
+		os=-linux
+		;;
+	m68knommu-*)
+		basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
+	m88k-omron*)
+		basic_machine=m88k-omron
+		;;
+	magnum | m3230)
+		basic_machine=mips-mips
+		os=-sysv
+		;;
+	merlin)
+		basic_machine=ns32k-utek
+		os=-sysv
+		;;
+	mingw32)
+		basic_machine=i386-pc
+		os=-mingw32
+		;;
+	mingw32ce)
+		basic_machine=arm-unknown
+		os=-mingw32ce
+		;;
+	miniframe)
+		basic_machine=m68000-convergent
+		;;
+	*mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
+		basic_machine=m68k-atari
+		os=-mint
+		;;
+	mips3*-*)
+		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
+		;;
+	mips3*)
+		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
+		;;
+	monitor)
+		basic_machine=m68k-rom68k
+		os=-coff
+		;;
+	morphos)
+		basic_machine=powerpc-unknown
+		os=-morphos
+		;;
+	msdos)
+		basic_machine=i386-pc
+		os=-msdos
+		;;
+	ms1-*)
+		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
+		;;
+	mvs)
+		basic_machine=i370-ibm
+		os=-mvs
+		;;
+	ncr3000)
+		basic_machine=i486-ncr
+		os=-sysv4
+		;;
+	netbsd386)
+		basic_machine=i386-unknown
+		os=-netbsd
+		;;
+	netwinder)
+		basic_machine=armv4l-rebel
+		os=-linux
+		;;
+	news | news700 | news800 | news900)
+		basic_machine=m68k-sony
+		os=-newsos
+		;;
+	news1000)
+		basic_machine=m68030-sony
+		os=-newsos
+		;;
+	news-3600 | risc-news)
+		basic_machine=mips-sony
+		os=-newsos
+		;;
+	necv70)
+		basic_machine=v70-nec
+		os=-sysv
+		;;
+	next | m*-next )
+		basic_machine=m68k-next
+		case $os in
+		    -nextstep* )
+			;;
+		    -ns2*)
+		      os=-nextstep2
+			;;
+		    *)
+		      os=-nextstep3
+			;;
+		esac
+		;;
+	nh3000)
+		basic_machine=m68k-harris
+		os=-cxux
+		;;
+	nh[45]000)
+		basic_machine=m88k-harris
+		os=-cxux
+		;;
+	nindy960)
+		basic_machine=i960-intel
+		os=-nindy
+		;;
+	mon960)
+		basic_machine=i960-intel
+		os=-mon960
+		;;
+	nonstopux)
+		basic_machine=mips-compaq
+		os=-nonstopux
+		;;
+	np1)
+		basic_machine=np1-gould
+		;;
+	nsr-tandem)
+		basic_machine=nsr-tandem
+		;;
+	op50n-* | op60c-*)
+		basic_machine=hppa1.1-oki
+		os=-proelf
+		;;
+	openrisc | openrisc-*)
+		basic_machine=or32-unknown
+		;;
+	os400)
+		basic_machine=powerpc-ibm
+		os=-os400
+		;;
+	OSE68000 | ose68000)
+		basic_machine=m68000-ericsson
+		os=-ose
+		;;
+	os68k)
+		basic_machine=m68k-none
+		os=-os68k
+		;;
+	pa-hitachi)
+		basic_machine=hppa1.1-hitachi
+		os=-hiuxwe2
+		;;
+	paragon)
+		basic_machine=i860-intel
+		os=-osf
+		;;
+	parisc)
+		basic_machine=hppa-unknown
+		os=-linux
+		;;
+	parisc-*)
+		basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
+	pbd)
+		basic_machine=sparc-tti
+		;;
+	pbb)
+		basic_machine=m68k-tti
+		;;
+	pc532 | pc532-*)
+		basic_machine=ns32k-pc532
+		;;
+	pc98)
+		basic_machine=i386-pc
+		;;
+	pc98-*)
+		basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentium | p5 | k5 | k6 | nexgen | viac3)
+		basic_machine=i586-pc
+		;;
+	pentiumpro | p6 | 6x86 | athlon | athlon_*)
+		basic_machine=i686-pc
+		;;
+	pentiumii | pentium2 | pentiumiii | pentium3)
+		basic_machine=i686-pc
+		;;
+	pentium4)
+		basic_machine=i786-pc
+		;;
+	pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
+		basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentiumpro-* | p6-* | 6x86-* | athlon-*)
+		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
+		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentium4-*)
+		basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pn)
+		basic_machine=pn-gould
+		;;
+	power)	basic_machine=power-ibm
+		;;
+	ppc)	basic_machine=powerpc-unknown
+		;;
+	ppc-*)	basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ppcle | powerpclittle | ppc-le | powerpc-little)
+		basic_machine=powerpcle-unknown
+		;;
+	ppcle-* | powerpclittle-*)
+		basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ppc64)	basic_machine=powerpc64-unknown
+		;;
+	ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ppc64le | powerpc64little | ppc64-le | powerpc64-little)
+		basic_machine=powerpc64le-unknown
+		;;
+	ppc64le-* | powerpc64little-*)
+		basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ps2)
+		basic_machine=i386-ibm
+		;;
+	pw32)
+		basic_machine=i586-unknown
+		os=-pw32
+		;;
+	rdos)
+		basic_machine=i386-pc
+		os=-rdos
+		;;
+	rom68k)
+		basic_machine=m68k-rom68k
+		os=-coff
+		;;
+	rm[46]00)
+		basic_machine=mips-siemens
+		;;
+	rtpc | rtpc-*)
+		basic_machine=romp-ibm
+		;;
+	s390 | s390-*)
+		basic_machine=s390-ibm
+		;;
+	s390x | s390x-*)
+		basic_machine=s390x-ibm
+		;;
+	sa29200)
+		basic_machine=a29k-amd
+		os=-udi
+		;;
+	sb1)
+		basic_machine=mipsisa64sb1-unknown
+		;;
+	sb1el)
+		basic_machine=mipsisa64sb1el-unknown
+		;;
+	sde)
+		basic_machine=mipsisa32-sde
+		os=-elf
+		;;
+	sei)
+		basic_machine=mips-sei
+		os=-seiux
+		;;
+	sequent)
+		basic_machine=i386-sequent
+		;;
+	sh)
+		basic_machine=sh-hitachi
+		os=-hms
+		;;
+	sh5el)
+		basic_machine=sh5le-unknown
+		;;
+	sh64)
+		basic_machine=sh64-unknown
+		;;
+	sparclite-wrs | simso-wrs)
+		basic_machine=sparclite-wrs
+		os=-vxworks
+		;;
+	sps7)
+		basic_machine=m68k-bull
+		os=-sysv2
+		;;
+	spur)
+		basic_machine=spur-unknown
+		;;
+	st2000)
+		basic_machine=m68k-tandem
+		;;
+	stratus)
+		basic_machine=i860-stratus
+		os=-sysv4
+		;;
+	sun2)
+		basic_machine=m68000-sun
+		;;
+	sun2os3)
+		basic_machine=m68000-sun
+		os=-sunos3
+		;;
+	sun2os4)
+		basic_machine=m68000-sun
+		os=-sunos4
+		;;
+	sun3os3)
+		basic_machine=m68k-sun
+		os=-sunos3
+		;;
+	sun3os4)
+		basic_machine=m68k-sun
+		os=-sunos4
+		;;
+	sun4os3)
+		basic_machine=sparc-sun
+		os=-sunos3
+		;;
+	sun4os4)
+		basic_machine=sparc-sun
+		os=-sunos4
+		;;
+	sun4sol2)
+		basic_machine=sparc-sun
+		os=-solaris2
+		;;
+	sun3 | sun3-*)
+		basic_machine=m68k-sun
+		;;
+	sun4)
+		basic_machine=sparc-sun
+		;;
+	sun386 | sun386i | roadrunner)
+		basic_machine=i386-sun
+		;;
+	sv1)
+		basic_machine=sv1-cray
+		os=-unicos
+		;;
+	symmetry)
+		basic_machine=i386-sequent
+		os=-dynix
+		;;
+	t3e)
+		basic_machine=alphaev5-cray
+		os=-unicos
+		;;
+	t90)
+		basic_machine=t90-cray
+		os=-unicos
+		;;
+	tic54x | c54x*)
+		basic_machine=tic54x-unknown
+		os=-coff
+		;;
+	tic55x | c55x*)
+		basic_machine=tic55x-unknown
+		os=-coff
+		;;
+	tic6x | c6x*)
+		basic_machine=tic6x-unknown
+		os=-coff
+		;;
+	tile*)
+		basic_machine=tile-unknown
+		os=-linux-gnu
+		;;
+	tx39)
+		basic_machine=mipstx39-unknown
+		;;
+	tx39el)
+		basic_machine=mipstx39el-unknown
+		;;
+	toad1)
+		basic_machine=pdp10-xkl
+		os=-tops20
+		;;
+	tower | tower-32)
+		basic_machine=m68k-ncr
+		;;
+	tpf)
+		basic_machine=s390x-ibm
+		os=-tpf
+		;;
+	udi29k)
+		basic_machine=a29k-amd
+		os=-udi
+		;;
+	ultra3)
+		basic_machine=a29k-nyu
+		os=-sym1
+		;;
+	v810 | necv810)
+		basic_machine=v810-nec
+		os=-none
+		;;
+	vaxv)
+		basic_machine=vax-dec
+		os=-sysv
+		;;
+	vms)
+		basic_machine=vax-dec
+		os=-vms
+		;;
+	vpp*|vx|vx-*)
+		basic_machine=f301-fujitsu
+		;;
+	vxworks960)
+		basic_machine=i960-wrs
+		os=-vxworks
+		;;
+	vxworks68)
+		basic_machine=m68k-wrs
+		os=-vxworks
+		;;
+	vxworks29k)
+		basic_machine=a29k-wrs
+		os=-vxworks
+		;;
+	w65*)
+		basic_machine=w65-wdc
+		os=-none
+		;;
+	w89k-*)
+		basic_machine=hppa1.1-winbond
+		os=-proelf
+		;;
+	xbox)
+		basic_machine=i686-pc
+		os=-mingw32
+		;;
+	xps | xps100)
+		basic_machine=xps100-honeywell
+		;;
+	ymp)
+		basic_machine=ymp-cray
+		os=-unicos
+		;;
+	z8k-*-coff)
+		basic_machine=z8k-unknown
+		os=-sim
+		;;
+	z80-*-coff)
+		basic_machine=z80-unknown
+		os=-sim
+		;;
+	none)
+		basic_machine=none-none
+		os=-none
+		;;
+
+# Here we handle the default manufacturer of certain CPU types.  It is in
+# some cases the only manufacturer, in others, it is the most popular.
+	w89k)
+		basic_machine=hppa1.1-winbond
+		;;
+	op50n)
+		basic_machine=hppa1.1-oki
+		;;
+	op60c)
+		basic_machine=hppa1.1-oki
+		;;
+	romp)
+		basic_machine=romp-ibm
+		;;
+	mmix)
+		basic_machine=mmix-knuth
+		;;
+	rs6000)
+		basic_machine=rs6000-ibm
+		;;
+	vax)
+		basic_machine=vax-dec
+		;;
+	pdp10)
+		# there are many clones, so DEC is not a safe bet
+		basic_machine=pdp10-unknown
+		;;
+	pdp11)
+		basic_machine=pdp11-dec
+		;;
+	we32k)
+		basic_machine=we32k-att
+		;;
+	sh[1234] | sh[24]a | sh[34]eb | sh[1234]le | sh[23]ele)
+		basic_machine=sh-unknown
+		;;
+	sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
+		basic_machine=sparc-sun
+		;;
+	cydra)
+		basic_machine=cydra-cydrome
+		;;
+	orion)
+		basic_machine=orion-highlevel
+		;;
+	orion105)
+		basic_machine=clipper-highlevel
+		;;
+	mac | mpw | mac-mpw)
+		basic_machine=m68k-apple
+		;;
+	pmac | pmac-mpw)
+		basic_machine=powerpc-apple
+		;;
+	*-unknown)
+		# Make sure to match an already-canonicalized machine name.
+		;;
+	*)
+		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+		exit 1
+		;;
+esac
+
+# Here we canonicalize certain aliases for manufacturers.
+case $basic_machine in
+	*-digital*)
+		basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
+		;;
+	*-commodore*)
+		basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
+		;;
+	*)
+		;;
+esac
+
+# Decode manufacturer-specific aliases for certain operating systems.
+
+if [ x"$os" != x"" ]
+then
+case $os in
+        # First match some system type aliases
+        # that might get confused with valid system types.
+	# -solaris* is a basic system type, with this one exception.
+	-solaris1 | -solaris1.*)
+		os=`echo $os | sed -e 's|solaris1|sunos4|'`
+		;;
+	-solaris)
+		os=-solaris2
+		;;
+	-svr4*)
+		os=-sysv4
+		;;
+	-unixware*)
+		os=-sysv4.2uw
+		;;
+	-gnu/linux*)
+		os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
+		;;
+	# First accept the basic system types.
+	# The portable systems comes first.
+	# Each alternative MUST END IN A *, to match a version number.
+	# -sysv* is not here because it comes later, after sysvr4.
+	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
+	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\
+	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \
+	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
+	      | -aos* \
+	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
+	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
+	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
+	      | -openbsd* | -solidbsd* \
+	      | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
+	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
+	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
+	      | -chorusos* | -chorusrdb* | -cegcc* \
+	      | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
+	      | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \
+	      | -uxpv* | -beos* | -mpeix* | -udk* \
+	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
+	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
+	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
+	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
+	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
+	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
+	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops*)
+	# Remember, each alternative MUST END IN *, to match a version number.
+		;;
+	-qnx*)
+		case $basic_machine in
+		    x86-* | i*86-*)
+			;;
+		    *)
+			os=-nto$os
+			;;
+		esac
+		;;
+	-nto-qnx*)
+		;;
+	-nto*)
+		os=`echo $os | sed -e 's|nto|nto-qnx|'`
+		;;
+	-sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
+	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
+	      | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
+		;;
+	-mac*)
+		os=`echo $os | sed -e 's|mac|macos|'`
+		;;
+	-linux-dietlibc)
+		os=-linux-dietlibc
+		;;
+	-linux*)
+		os=`echo $os | sed -e 's|linux|linux-gnu|'`
+		;;
+	-sunos5*)
+		os=`echo $os | sed -e 's|sunos5|solaris2|'`
+		;;
+	-sunos6*)
+		os=`echo $os | sed -e 's|sunos6|solaris3|'`
+		;;
+	-opened*)
+		os=-openedition
+		;;
+        -os400*)
+		os=-os400
+		;;
+	-wince*)
+		os=-wince
+		;;
+	-osfrose*)
+		os=-osfrose
+		;;
+	-osf*)
+		os=-osf
+		;;
+	-utek*)
+		os=-bsd
+		;;
+	-dynix*)
+		os=-bsd
+		;;
+	-acis*)
+		os=-aos
+		;;
+	-atheos*)
+		os=-atheos
+		;;
+	-syllable*)
+		os=-syllable
+		;;
+	-386bsd)
+		os=-bsd
+		;;
+	-ctix* | -uts*)
+		os=-sysv
+		;;
+	-nova*)
+		os=-rtmk-nova
+		;;
+	-ns2 )
+		os=-nextstep2
+		;;
+	-nsk*)
+		os=-nsk
+		;;
+	# Preserve the version number of sinix5.
+	-sinix5.*)
+		os=`echo $os | sed -e 's|sinix|sysv|'`
+		;;
+	-sinix*)
+		os=-sysv4
+		;;
+        -tpf*)
+		os=-tpf
+		;;
+	-triton*)
+		os=-sysv3
+		;;
+	-oss*)
+		os=-sysv3
+		;;
+	-svr4)
+		os=-sysv4
+		;;
+	-svr3)
+		os=-sysv3
+		;;
+	-sysvr4)
+		os=-sysv4
+		;;
+	# This must come after -sysvr4.
+	-sysv*)
+		;;
+	-ose*)
+		os=-ose
+		;;
+	-es1800*)
+		os=-ose
+		;;
+	-xenix)
+		os=-xenix
+		;;
+	-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+		os=-mint
+		;;
+	-aros*)
+		os=-aros
+		;;
+	-kaos*)
+		os=-kaos
+		;;
+	-zvmoe)
+		os=-zvmoe
+		;;
+	-dicos*)
+		os=-dicos
+		;;
+	-none)
+		;;
+	*)
+		# Get rid of the `-' at the beginning of $os.
+		os=`echo $os | sed 's/[^-]*-//'`
+		echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
+		exit 1
+		;;
+esac
+else
+
+# Here we handle the default operating systems that come with various machines.
+# The value should be what the vendor currently ships out the door with their
+# machine or put another way, the most popular os provided with the machine.
+
+# Note that if you're going to try to match "-MANUFACTURER" here (say,
+# "-sun"), then you have to tell the case statement up towards the top
+# that MANUFACTURER isn't an operating system.  Otherwise, code above
+# will signal an error saying that MANUFACTURER isn't an operating
+# system, and we'll never get to this point.
+
+case $basic_machine in
+        score-*)
+		os=-elf
+		;;
+        spu-*)
+		os=-elf
+		;;
+	*-acorn)
+		os=-riscix1.2
+		;;
+	arm*-rebel)
+		os=-linux
+		;;
+	arm*-semi)
+		os=-aout
+		;;
+        c4x-* | tic4x-*)
+        	os=-coff
+		;;
+	# This must come before the *-dec entry.
+	pdp10-*)
+		os=-tops20
+		;;
+	pdp11-*)
+		os=-none
+		;;
+	*-dec | vax-*)
+		os=-ultrix4.2
+		;;
+	m68*-apollo)
+		os=-domain
+		;;
+	i386-sun)
+		os=-sunos4.0.2
+		;;
+	m68000-sun)
+		os=-sunos3
+		# This also exists in the configure program, but was not the
+		# default.
+		# os=-sunos4
+		;;
+	m68*-cisco)
+		os=-aout
+		;;
+        mep-*)
+		os=-elf
+		;;
+	mips*-cisco)
+		os=-elf
+		;;
+	mips*-*)
+		os=-elf
+		;;
+	or32-*)
+		os=-coff
+		;;
+	*-tti)	# must be before sparc entry or we get the wrong os.
+		os=-sysv3
+		;;
+	sparc-* | *-sun)
+		os=-sunos4.1.1
+		;;
+	*-be)
+		os=-beos
+		;;
+	*-haiku)
+		os=-haiku
+		;;
+	*-ibm)
+		os=-aix
+		;;
+    	*-knuth)
+		os=-mmixware
+		;;
+	*-wec)
+		os=-proelf
+		;;
+	*-winbond)
+		os=-proelf
+		;;
+	*-oki)
+		os=-proelf
+		;;
+	*-hp)
+		os=-hpux
+		;;
+	*-hitachi)
+		os=-hiux
+		;;
+	i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
+		os=-sysv
+		;;
+	*-cbm)
+		os=-amigaos
+		;;
+	*-dg)
+		os=-dgux
+		;;
+	*-dolphin)
+		os=-sysv3
+		;;
+	m68k-ccur)
+		os=-rtu
+		;;
+	m88k-omron*)
+		os=-luna
+		;;
+	*-next )
+		os=-nextstep
+		;;
+	*-sequent)
+		os=-ptx
+		;;
+	*-crds)
+		os=-unos
+		;;
+	*-ns)
+		os=-genix
+		;;
+	i370-*)
+		os=-mvs
+		;;
+	*-next)
+		os=-nextstep3
+		;;
+	*-gould)
+		os=-sysv
+		;;
+	*-highlevel)
+		os=-bsd
+		;;
+	*-encore)
+		os=-bsd
+		;;
+	*-sgi)
+		os=-irix
+		;;
+	*-siemens)
+		os=-sysv4
+		;;
+	*-masscomp)
+		os=-rtu
+		;;
+	f30[01]-fujitsu | f700-fujitsu)
+		os=-uxpv
+		;;
+	*-rom68k)
+		os=-coff
+		;;
+	*-*bug)
+		os=-coff
+		;;
+	*-apple)
+		os=-macos
+		;;
+	*-atari*)
+		os=-mint
+		;;
+	*)
+		os=-none
+		;;
+esac
+fi
+
+# Here we handle the case where we know the os, and the CPU type, but not the
+# manufacturer.  We pick the logical manufacturer.
+vendor=unknown
+case $basic_machine in
+	*-unknown)
+		case $os in
+			-riscix*)
+				vendor=acorn
+				;;
+			-sunos*)
+				vendor=sun
+				;;
+			-aix*)
+				vendor=ibm
+				;;
+			-beos*)
+				vendor=be
+				;;
+			-hpux*)
+				vendor=hp
+				;;
+			-mpeix*)
+				vendor=hp
+				;;
+			-hiux*)
+				vendor=hitachi
+				;;
+			-unos*)
+				vendor=crds
+				;;
+			-dgux*)
+				vendor=dg
+				;;
+			-luna*)
+				vendor=omron
+				;;
+			-genix*)
+				vendor=ns
+				;;
+			-mvs* | -opened*)
+				vendor=ibm
+				;;
+			-os400*)
+				vendor=ibm
+				;;
+			-ptx*)
+				vendor=sequent
+				;;
+			-tpf*)
+				vendor=ibm
+				;;
+			-vxsim* | -vxworks* | -windiss*)
+				vendor=wrs
+				;;
+			-aux*)
+				vendor=apple
+				;;
+			-hms*)
+				vendor=hitachi
+				;;
+			-mpw* | -macos*)
+				vendor=apple
+				;;
+			-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+				vendor=atari
+				;;
+			-vos*)
+				vendor=stratus
+				;;
+		esac
+		basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
+		;;
+esac
+
+echo $basic_machine$os
+exit
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
Index: /issm/trunk-jpl-damage/configs/config-altix64-castor.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-altix64-castor.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-altix64-castor.sh	(revision 11330)
@@ -0,0 +1,3 @@
+#!/bin/csh
+
+./configure --prefix=$ISSM_TIER --with-serial=no --with-metis-dir=$ISSM_TIER/externalpackages/metis/install --with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install --with-mpi-include=/usr/include  --with-mpi-lib="-L/usr/lib -lmpi" --with-petsc-arch=$ISSM_ARCH --with-dakota-dir=$ISSM_TIER/externalpackages/dakota/install --with-mkl-dir=/opt/intel/mkl/9.1.023/lib/64 --with-triangle-dir=$ISSM_TIER/externalpackages/triangle/install --with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/$ISSM_ARCH -lPLAPACK" --with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/$ISSM_ARCH/INCLUDE" --with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/$ISSM_ARCH/ --with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/$ISSM_ARCH/ --with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/$ISSM_ARCH --with-graphics-lib=/usr/X11R6/lib/libX11.so
Index: /issm/trunk-jpl-damage/configs/config-cosmos.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-cosmos.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-cosmos.sh	(revision 11330)
@@ -0,0 +1,3 @@
+#!/bin/csh
+
+./configure --prefix=$ISSM_TIER --with-serial=no --with-metis-dir=$ISSM_TIER/externalpackages/metis/install --with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install --with-mpi-include=/opt/mpich/gm/intel10.1/include  --with-mpi-lib="-L/opt/mpich/gm/intel10.1/lib -lmpich -L/usr/local/gm/lib/ -lgm  -lpthread  -lrt" --with-petsc-arch=$ISSM_ARCH --with-mkl-dir=/opt/intel/mkl/10.0.5.025/lib/32/  --with-plapack-dir="-L$ISSM_TIER/externalpackages/petsc/install/$ISSM_ARCH -lPLAPACK" --with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/$ISSM_ARCH/INCLUDE" --with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/$ISSM_ARCH/ --with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/$ISSM_ARCH/ --with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/$ISSM_ARCH  --with-vendor=intel-linux --with-graphics-lib=/usr/X11R6/lib/libX11.so
Index: /issm/trunk-jpl-damage/configs/config-linux64-astrid-ad.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-linux64-astrid-ad.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-linux64-astrid-ad.sh	(revision 11330)
@@ -0,0 +1,36 @@
+#!/bin/sh
+
+./configure \
+ --prefix=$ISSM_TIER \
+ --with-serial=no\
+ --with-metis-dir=$ISSM_TIER/externalpackages/metis/install \
+ --with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install \
+ --with-mpi-include=$ISSM_TIER/externalpackages/mpich2/install/include  \
+ --with-mpi-lib="-L$ISSM_TIER/externalpackages/mpich2/install/lib/ -lmpich" \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-blas-lapack-dir=$ISSM_TIER/externalpackages/petsc/install \
+ --with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/ -lPLAPACK" \
+ --with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
+ --with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-graphics-lib=/usr/lib64/libX11.so \
+ --with-cxxoptflags="-march=opteron -O2" \
+ --with-fortran-lib="-L/usr/lib/gcc/x86_64-redhat-linux/4.1.1/ -lgfortran" \
+ --with-rose-dir=$ISSM_TIER/externalpackages/rose/install/ \
+ --with-adic2-dir=$ISSM_TIER/externalpackages/adic/install/ \
+ --with-numthreads=24 \
+ --without-thermal \
+ --without-control \
+ --without-hydrology \
+ --without-diagnostic \
+ --without-balanced \
+ --without-responses \
+ --without-slope \
+ --without-rifts \
+ --without-steadystate \
+ --without-transient \
+ --without-3d \
+ --without-groundingline
+ 
+#--without-prognostic \
Index: /issm/trunk-jpl-damage/configs/config-linux64-astrid-mpich1.4.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-linux64-astrid-mpich1.4.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-linux64-astrid-mpich1.4.sh	(revision 11330)
@@ -0,0 +1,31 @@
+#!/bin/sh
+
+#External packages versions:
+#petsc 3.1 or 3.2
+#mpich 1.4
+
+./configure \
+ --prefix=$ISSM_TIER \
+ --with-matlab-dir=$MATLAB_DIR \
+ --with-triangle-dir=$ISSM_TIER/externalpackages/triangle/install \
+ --with-metis-dir=$ISSM_TIER/externalpackages/metis/install \
+ --with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install \
+ --with-tao-dir=$ISSM_TIER/externalpackages/tao/install \
+ --with-mpi-include=$ISSM_TIER/externalpackages/mpich2/install/include  \
+ --with-mpi-lib="-L$ISSM_TIER/externalpackages/mpich2/install/lib/ -lmpich -lmpl " \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-dakota-dir=$ISSM_TIER/externalpackages/dakota/install \
+ --with-blas-lapack-dir=$ISSM_TIER/externalpackages/petsc/install \
+ --with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/ -lPLAPACK" \
+ --with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
+ --with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-scotch-dir="$ISSM_TIER/externalpackages/scotch/install" \
+ --with-chaco-dir="$ISSM_TIER/externalpackages/chaco/install" \
+ --with-shapelib-dir="$ISSM_TIER/externalpackages/shapelib/install" \
+ --with-fortran-lib="-L/usr/lib/gcc/x86_64-redhat-linux/4.1.1/ -lgfortran" \
+ --with-graphics-lib=/usr/lib64/libX11.so \
+ --with-cxxoptflags="-march=opteron -O2" \
+ --with-numthreads=32 \
+ --enable-debugging
Index: /issm/trunk-jpl-damage/configs/config-linux64-astrid-petsc2.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-linux64-astrid-petsc2.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-linux64-astrid-petsc2.sh	(revision 11330)
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+#External packages versions:
+#petsc 2.6
+#mpich 1.0.2
+
+./configure --prefix=$ISSM_TIER --with-matlab-dir=$MATLAB_DIR --with-triangle-dir=$ISSM_TIER/externalpackages/triangle/install --with-metis-dir=$ISSM_TIER/externalpackages/metis/install --with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install --with-mpi-include=$ISSM_TIER/externalpackages/mpich2/install/include  --with-mpi-lib="-L$ISSM_TIER/externalpackages/mpich2/install/lib/ -lmpich" --with-petsc-arch=$ISSM_ARCH --with-dakota-dir=$ISSM_TIER/externalpackages/dakota/install --with-blas-lapack-dir=$ISSM_TIER/externalpackages/petsc/install/externalpackages/fblaslapack/$ISSM_ARCH --with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/$ISSM_ARCH -lPLAPACK" --with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/$ISSM_ARCH/INCLUDE" --with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/externalpackages/blacs-dev/$ISSM_ARCH --with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/externalpackages/SCALAPACK/$ISSM_ARCH --with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/externalpackages/MUMPS_4.6.3/$ISSM_ARCH --with-fortran-lib="-L/usr/lib/gcc/x86_64-redhat-linux/4.1.1/ -lgfortran" --with-graphics-lib=/usr/lib64/libX11.so --with-cxxoptflags="-march=opteron -O2" --with-numthreads=32 --with-scotch-dir=$ISSM_TIER/externalpackages/scotch/install --with-chaco-dir=$ISSM_TIER/externalpackages/chaco/install --enable-debugging --with-shapelib-dir=$ISSM_TIER/externalpackages/shapelib/install\
Index: /issm/trunk-jpl-damage/configs/config-linux64-astrid.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-linux64-astrid.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-linux64-astrid.sh	(revision 11330)
@@ -0,0 +1,31 @@
+#!/bin/sh
+
+#External packages versions:
+#petsc 3.1 or 3.2
+#mpich 1.0.2
+
+./configure \
+ --prefix=$ISSM_TIER \
+ --with-matlab-dir=$MATLAB_DIR \
+ --with-triangle-dir=$ISSM_TIER/externalpackages/triangle/install \
+ --with-metis-dir=$ISSM_TIER/externalpackages/metis/install \
+ --with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install \
+ --with-tao-dir=$ISSM_TIER/externalpackages/tao/install \
+ --with-mpi-include=$ISSM_TIER/externalpackages/mpich2/install/include  \
+ --with-mpi-lib="-L$ISSM_TIER/externalpackages/mpich2/install/lib/ -lmpich " \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-dakota-dir=$ISSM_TIER/externalpackages/dakota/install \
+ --with-blas-lapack-dir=$ISSM_TIER/externalpackages/petsc/install \
+ --with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/ -lPLAPACK" \
+ --with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
+ --with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-scotch-dir="$ISSM_TIER/externalpackages/scotch/install" \
+ --with-chaco-dir="$ISSM_TIER/externalpackages/chaco/install" \
+ --with-shapelib-dir="$ISSM_TIER/externalpackages/shapelib/install" \
+ --with-fortran-lib="-L/usr/lib/gcc/x86_64-redhat-linux/4.1.1/ -lgfortran" \
+ --with-graphics-lib=/usr/lib64/libX11.so \
+ --with-cxxoptflags="-march=opteron -O2" \
+ --with-numthreads=32 \
+ --enable-debugging
Index: /issm/trunk-jpl-damage/configs/config-linux64-murdo-ad.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-linux64-murdo-ad.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-linux64-murdo-ad.sh	(revision 11330)
@@ -0,0 +1,37 @@
+#!/bin/sh
+
+./configure \
+ --prefix=$ISSM_TIER \
+ --with-serial=no\
+ --with-metis-dir=$ISSM_TIER/externalpackages/metis/install \
+ --with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install \
+ --with-mpi-include=$ISSM_TIER/externalpackages/mpich2/install/include  \
+ --with-mpi-lib="-L$ISSM_TIER/externalpackages/mpich2/install/lib/ -lmpich" \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-blas-lapack-dir=$ISSM_TIER/externalpackages/petsc/install \
+ --with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/ -lPLAPACK" \
+ --with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
+ --with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-hypre-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-ml-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-graphics-lib=/usr/lib64/libX11.so \
+ --with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
+ --with-fortran-lib="-L/usr/lib/gcc/x86_64-redhat-linux/3.4.6/ -lg2c  /usr/lib/gcc/x86_64-redhat-linux/4.1.1/libgfortran.a" \
+ --with-adic2-dir=$ISSM_TIER/externalpackages/adic/install/ \
+--with-numthreads=24 \
+ --without-thermal \
+ --without-control \
+ --without-hydrology \
+ --without-diagnostic \
+ --without-balanced \
+ --without-responses \
+ --without-slope \
+ --without-rifts \
+ --without-steadystate \
+ --without-transient \
+ --without-3d \
+ --without-groundingline
+ 
+#--without-prognostic \
Index: /issm/trunk-jpl-damage/configs/config-linux64-murdo.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-linux64-murdo.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-linux64-murdo.sh	(revision 11330)
@@ -0,0 +1,28 @@
+#!/bin/sh
+
+./configure \
+ --prefix=$ISSM_TIER \
+ --with-matlab-dir=$MATLAB_DIR \
+ --with-triangle-dir=$ISSM_TIER/externalpackages/triangle/install \
+ --with-metis-dir=$ISSM_TIER/externalpackages/metis/install \
+ --with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install \
+ --with-mpi-include=$ISSM_TIER/externalpackages/mpich2/install/include  \
+ --with-mpi-lib="-L$ISSM_TIER/externalpackages/mpich2/install/lib/ -lmpich" \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-blas-lapack-dir=$ISSM_TIER/externalpackages/petsc/install \
+ --with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/ -lPLAPACK" \
+ --with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
+ --with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-scotch-dir="$ISSM_TIER/externalpackages/scotch/install" \
+ --with-chaco-dir="$ISSM_TIER/externalpackages/chaco/install" \
+ --with-graphics-lib=/usr/lib64/libX11.so \
+ --with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
+ --with-numthreads=18 \
+ --with-ml-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-hypre-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --enable-debugging
+ 
+ #--with-dakota-dir=$ISSM_TIER/externalpackages/dakota/install \
+ 
Index: /issm/trunk-jpl-damage/configs/config-macosx32-mathieu.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-macosx32-mathieu.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-macosx32-mathieu.sh	(revision 11330)
@@ -0,0 +1,31 @@
+#!/bin/sh
+
+#petsc 3.1 or 3.2
+#mpich 1.4
+
+export FCFLAGS=" -m32"
+export FFLAGS=" -m32"
+export CFLAGS=" -arch i386"
+export CXXFLAGS=" -arch i386"
+
+./configure \
+	--prefix=$ISSM_TIER \
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_TIER/externalpackages/triangle/install \
+	--with-metis-dir=$ISSM_TIER/externalpackages/metis/install \
+	--with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install  \
+	--with-mpi-include=$ISSM_TIER/externalpackages/mpich2/install/include  \
+	--with-mpi-lib=" $ISSM_TIER/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_TIER/externalpackages/mpich2/install/lib/libmpich.a $ISSM_TIER/externalpackages/mpich2/install/lib/libmpl.a " \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-dakota-dir=$ISSM_TIER/externalpackages/dakota/install \
+	--with-blas-lapack-dir=$ISSM_TIER/externalpackages/petsc/install \
+	--with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/ -lPLAPACK" \
+	--with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/include/ " \
+	--with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-fortran-lib="/usr/local/lib/libgfortran.a" \
+	--with-math-lib="/usr/lib/libm.dylib" \
+	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
+	--with-cxxoptflags=" -DMATLAB_MEX_FILE -fno-common -no-cpp-precomp -fexceptions -arch i386  -DMX_COMPAT_32 -O3 -DNDEBUG -w " \
+	--with-numthreads=8
Index: /issm/trunk-jpl-damage/configs/config-macosx32-ogive.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-macosx32-ogive.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-macosx32-ogive.sh	(revision 11330)
@@ -0,0 +1,26 @@
+#!/bin/sh
+
+#petsc 3.1 or 3.2
+#mpich 1.4
+
+./configure \
+	--prefix=$ISSM_TIER \
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_TIER/externalpackages/triangle/install \
+	--with-metis-dir=$ISSM_TIER/externalpackages/metis/install \
+	--with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install  \
+	--with-mpi-include=$ISSM_TIER/externalpackages/mpich2/install/include  \
+	--with-mpi-lib=" $ISSM_TIER/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_TIER/externalpackages/mpich2/install/lib/libmpich.a $ISSM_TIER/externalpackages/mpich2/install/lib/libmpl.a " \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-dakota-dir=$ISSM_TIER/externalpackages/dakota/install \
+	--with-blas-lapack-dir=$ISSM_TIER/externalpackages/petsc/install \
+	--with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/ -lPLAPACK" \
+	--with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/include/ " \
+	--with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
+	--with-math-lib="/usr/lib/libm.dylib" \
+	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
+	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch i386 -g -O3 -DNDEBUG -DMX_COMPAT_32" \
+	--with-numthreads=8
Index: /issm/trunk-jpl-damage/configs/config-macosx64-mathieu.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-macosx64-mathieu.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-macosx64-mathieu.sh	(revision 11330)
@@ -0,0 +1,26 @@
+#!/bin/sh
+
+#petsc 3.2
+#mpich 1.4
+
+./configure \
+	--prefix=$ISSM_TIER \
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_TIER/externalpackages/triangle/install \
+	--with-metis-dir=$ISSM_TIER/externalpackages/metis/install \
+	--with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install  \
+	--with-mpi-include=$ISSM_TIER/externalpackages/mpich2/install/include  \
+	--with-mpi-lib=" $ISSM_TIER/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_TIER/externalpackages/mpich2/install/lib/libmpich.a $ISSM_TIER/externalpackages/mpich2/install/lib/libmpl.a " \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-dakota-dir=$ISSM_TIER/externalpackages/dakota/install \
+	--with-blas-lapack-dir=$ISSM_TIER/externalpackages/petsc/install \
+	--with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/ -lPLAPACK" \
+	--with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/include/ " \
+	--with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-fortran-lib="/usr/local/lib/libgfortran.a" \
+	--with-math-lib="/usr/lib/libm.dylib" \
+	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
+	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
+	--with-numthreads=8
Index: /issm/trunk-jpl-damage/configs/config-macosx64-ogive.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-macosx64-ogive.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-macosx64-ogive.sh	(revision 11330)
@@ -0,0 +1,31 @@
+#!/bin/sh
+
+#petsc 3.2
+#mpich 1.4
+export FCFLAGS=" -m64"
+export FFLAGS=" -m64"
+export CFLAGS=" -arch x86_64"
+export CXXFLAGS=" -arch x86_64"
+
+./configure \
+	--prefix=$ISSM_TIER \
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_TIER/externalpackages/triangle/install \
+	--with-metis-dir=$ISSM_TIER/externalpackages/metis/install \
+	--with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install  \
+	--with-mpi-include=$ISSM_TIER/externalpackages/mpich2/install/include  \
+	--with-mpi-lib=" $ISSM_TIER/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_TIER/externalpackages/mpich2/install/lib/libmpich.a $ISSM_TIER/externalpackages/mpich2/install/lib/libmpl.a " \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-dakota-dir=$ISSM_TIER/externalpackages/dakota/install \
+	--with-blas-lapack-dir=$ISSM_TIER/externalpackages/petsc/install \
+	--with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/ -lPLAPACK" \
+	--with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/include/ " \
+	--with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-fortran-lib="/usr/local/gfortran/lib/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
+	#--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
Index: /issm/trunk-jpl-damage/configs/config-macosx64-sophie.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-macosx64-sophie.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-macosx64-sophie.sh	(revision 11330)
@@ -0,0 +1,30 @@
+#!/bin/sh
+
+#petsc 3.2
+#mpich 1.4
+export FCFLAGS=" -m64"
+export FFLAGS=" -m64"
+export CFLAGS=" -arch x86_64"
+export CXXFLAGS=" -arch x86_64"
+
+./configure \
+	--prefix=$ISSM_TIER \
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_TIER/externalpackages/triangle/install \
+	--with-metis-dir=$ISSM_TIER/externalpackages/metis/install \
+	--with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install  \
+	--with-mpi-include=$ISSM_TIER/externalpackages/mpich2/install/include  \
+	--with-mpi-lib=" $ISSM_TIER/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_TIER/externalpackages/mpich2/install/lib/libmpich.a $ISSM_TIER/externalpackages/mpich2/install/lib/libmpl.a " \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-dakota-dir=$ISSM_TIER/externalpackages/dakota/install \
+	--with-blas-lapack-dir=$ISSM_TIER/externalpackages/petsc/install \
+	--with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/ -lPLAPACK" \
+	--with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/include/ " \
+	--with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+	--with-fortran-lib="/sw/usr/local/lib/x86_64/libgfortran.a" \
+	--with-math-lib="/usr/lib/libm.dylib" \
+	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
+	--with-cxxoptflags=" -fno-common -Wno-write-strings -no-cpp-precomp -fexceptions -arch x86_64 -O3 -DNDEBUG -w "\
+	--with-numthreads=8
Index: /issm/trunk-jpl-damage/configs/config-pleiades-petsc2.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-pleiades-petsc2.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-pleiades-petsc2.sh	(revision 11330)
@@ -0,0 +1,21 @@
+#!/bin/csh
+
+./configure \
+ --prefix=$ISSM_TIER \
+ --with-serial=no \
+ --with-triangle-dir=$ISSM_TIER/externalpackages/triangle/install \
+ --with-metis-dir=$ISSM_TIER/externalpackages/metis/install \
+ --with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install \
+ --with-mpi-include=/nasa/sgi/mpt/1.25/include \
+ --with-mpi-lib="-L/nasa/sgi/mpt/1.25/lib/ -lmpi -lpthread -lgfortran" \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-dakota-dir=$ISSM_TIER/externalpackages/dakota/install \
+ --with-mkl-dir=/nasa/intel/mkl/10.0.011/lib/64/ \
+ --with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/ -lPLAPACK" \
+ --with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
+ --with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-graphics-lib=/usr/lib64/libX11.so \
+ --with-cxxoptflags="-O3 -xS" \
+ --with-vendor=intel-pleiades
Index: /issm/trunk-jpl-damage/configs/config-pleiades.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-pleiades.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-pleiades.sh	(revision 11330)
@@ -0,0 +1,21 @@
+#!/bin/csh
+
+./configure \
+ --prefix=$ISSM_TIER \
+ --with-serial=no \
+ --with-triangle-dir=$ISSM_TIER/externalpackages/triangle/install \
+ --with-metis-dir=$ISSM_TIER/externalpackages/metis/install \
+ --with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install \
+ --with-mpi-include=/nasa/sgi/mpt/1.25/include \
+ --with-mpi-lib="-L/nasa/sgi/mpt/1.25/lib/ -lmpi -lpthread -lgfortran" \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-dakota-dir=$ISSM_TIER/externalpackages/dakota/install \
+ --with-mkl-dir=/nasa/intel/mkl/10.0.011/lib/64/ \
+ --with-plapack-lib="-L$ISSM_TIER/externalpackages/petsc/install/ -lPLAPACK" \
+ --with-plapack-include="-I$ISSM_TIER/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
+ --with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-scalapack-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-blacs-dir=$ISSM_TIER/externalpackages/petsc/install/ \
+ --with-graphics-lib=/usr/lib64/libX11.so \
+ --with-cxxoptflags="-O3 -xS" \
+ --with-vendor=intel-pleiades
Index: /issm/trunk-jpl-damage/configs/config-win32-eric.sh
===================================================================
--- /issm/trunk-jpl-damage/configs/config-win32-eric.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/configs/config-win32-eric.sh	(revision 11330)
@@ -0,0 +1,6 @@
+#!/bin/sh
+
+
+#get configure.sh to pick up the intel compiler 
+
+./configure --prefix=$ISSM_TIER --with-parallel=no --with-vendor=intel-win  --with-matlab-dir=$MATLAB_DIR --with-triangle-dir=$ISSM_TIER/externalpackages/triangle/install --with-metis-dir=$ISSM_TIER/externalpackages/metis/install --with-petsc-dir=$ISSM_TIER/externalpackages/petsc/install  --with-petsc-arch=$ISSM_ARCH  --with-blas-lapack-dir=$ISSM_TIER/externalpackages/petsc/install/externalpackages/f2cblaslapack/$ISSM_ARCH
Index: /issm/trunk-jpl-damage/configure.ac
===================================================================
--- /issm/trunk-jpl-damage/configure.ac	(revision 11330)
+++ /issm/trunk-jpl-damage/configure.ac	(revision 11330)
@@ -0,0 +1,23 @@
+AC_INIT(ISSM,4.0,issm@jpl.nasa.gov)
+AM_CONFIG_HEADER(config.h)
+#AC_PROG_LIBTOOL
+#LT_INIT
+AC_CANONICAL_TARGET
+AM_INIT_AUTOMAKE
+AC_PROG_RANLIB
+AC_PROG_CC([gcc icl])
+AC_PROG_CPP
+AC_PROG_CXX([g++ icl])
+AC_PROG_F77([ifort g77 gfortran])
+AC_F77_LIBRARY_LDFLAGS
+AM_PROG_CC_C_O
+AC_PATH_XTRA
+ISSM_OPTIONS
+AC_CONFIG_FILES([Makefile
+			src/Makefile
+			src/c/Makefile
+			src/ad/Makefile
+			src/mex/Makefile
+			bin/Makefile])
+AC_OUTPUT
+
Index: /issm/trunk-jpl-damage/cron/README
===================================================================
--- /issm/trunk-jpl-damage/cron/README	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/README	(revision 11330)
@@ -0,0 +1,16 @@
+The Cron directory holds scripts that can be used to run 
+jobs periodically on *nix systems. 
+
+Just add an entry in the cron table to run the ice.sh script, 
+and all the scripts in this directory will be taken care of. 
+
+For example, if you add: 
+
+5 5 * * * cd $ISSM_TIER/cron && ./nightlyrun.sh
+
+This will run all the scripts in the Cron directory, every day, at 5:05 am. 
+
+
+
+If users want to add their own scripts, just add the script to the cron directory and
+add an entry in the issm.sh for this script.
Index: /issm/trunk-jpl-damage/cron/configs/linux64_larour
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/linux64_larour	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/linux64_larour	(revision 11330)
@@ -0,0 +1,93 @@
+#
+########### Configuration file for Eric Larour's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full paths)
+ISSM_DIR="/u/astrid-r1b/larour/issm/"
+ISSM_TIER="/u/astrid-r1b/larour/issm/trunk-jpl/cron/trunk-jpl"
+#ISSM_TIER="/u/wilkes-r1b/morlighe/svn/issm/trunk/cron/issm2.2"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#Machine configuration
+MACHINE="astrid"
+
+#MATLAB path
+MATLAB_PATH="/usr/local/pkgs/matlab-7.6/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="update"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/astrid-r1b/larour/issm/execution"
+
+#-----------------------------------#
+# 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="none"
+EXTERNALPACKAGESDIR="/u/astrid-r1b/larour/issm/trunk-jpl/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco"
+
+#---------------------#
+# 4: ISSM Compilation #
+#---------------------#
+
+#ISSM_COMPILATION can have 2 values:
+# - "yes" compile ISSM
+# - "no"  do not compile ISSM
+ISSM_COMPILATION="no"
+
+#----------------------#
+# 5: Mail notification #
+#----------------------#
+
+#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
+#sent to the adresses present in $ISSM_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="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 nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS=""
Index: /issm/trunk-jpl-damage/cron/configs/linux64_morlighem_daily
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/linux64_morlighem_daily	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/linux64_morlighem_daily	(revision 11330)
@@ -0,0 +1,93 @@
+#
+########### Configuration file for Mathieu Morlighem's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full paths)
+ISSM_DIR="/u/astrid-r1b/morlighe/svn/issm"
+ISSM_TIER="/u/astrid-r1b/morlighe/svn/issm/trunk-jpl/cron/trunk-jpl"
+#ISSM_TIER="/u/astrid-r1b/morlighe/svn/issm/trunk/cron/issm2.2"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#Machine configuration
+MACHINE="astrid"
+
+#MATLAB path
+MATLAB_PATH="/usr/local/pkgs/matlab-7.6/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="update"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/astrid-r1b/morlighe/ExecutionNightlyRun"
+
+#-----------------------------------#
+# 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="none"
+EXTERNALPACKAGESDIR="/u/astrid-r1b/morlighe/issm/trunk-jpl/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="automake autoconf matlab mpich2 petsc metis triangle dakota chaco"
+
+#---------------------#
+# 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_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="mathieu.morlighem@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=7
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS=""
Index: /issm/trunk-jpl-damage/cron/configs/linux64_morlighem_nightly
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/linux64_morlighem_nightly	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/linux64_morlighem_nightly	(revision 11330)
@@ -0,0 +1,93 @@
+#
+########### Configuration file for Mathieu Morlighem's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full path)
+ISSM_DIR="/u/astrid-r1b/morlighe/issm"
+ISSM_TIER="/u/astrid-r1b/morlighe/issm/trunk-jpl/cron/trunk-jpl"
+#ISSM_TIER="/u/astrid-r1b/morlighe/svn/issm/trunk/cron/issm2.2"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#Machine configuration
+MACHINE="astrid"
+
+#MATLAB path
+MATLAB_PATH="/usr/local/pkgs/matlab-7.6/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="checkout"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/astrid-r1b/morlighe/ExecutionNightlyRun"
+
+#-----------------------------------#
+# 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="/u/astrid-r1b/morlighe/issm/trunk-jpl/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco"
+
+#---------------------#
+# 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_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="mathieu.morlighem@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=1
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=7
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS=""
Index: /issm/trunk-jpl-damage/cron/configs/linux64_morlighem_validation
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/linux64_morlighem_validation	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/linux64_morlighem_validation	(revision 11330)
@@ -0,0 +1,92 @@
+########### Configuration file for Mathieu Morlighem's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full path)
+ISSM_DIR="/u/astrid-r1b/morlighe/issm"
+ISSM_TIER="/u/astrid-r1b/morlighe/issm/trunk-jpl/cron/trunk-jpl"
+#ISSM_TIER="/u/astrid-r1b/morlighe/svn/issm/trunk/cron/issm2.2"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#Machine configuration
+MACHINE="astrid"
+
+#MATLAB path
+MATLAB_PATH="/usr/local/pkgs/matlab-7.6/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="checkout"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/astrid-r1b/morlighe/ExecutionNightlyRun"
+
+#-----------------------------------#
+# 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="/u/astrid-r1b/morlighe/issm/trunk-jpl/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco yams"
+
+#---------------------#
+# 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_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="mathieu.morlighem@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=1
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=7
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS="'benchmark','all'"
Index: /issm/trunk-jpl-damage/cron/configs/linux64_schlegel_daily
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/linux64_schlegel_daily	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/linux64_schlegel_daily	(revision 11330)
@@ -0,0 +1,93 @@
+#
+########### Configuration file for Mathieu Morlighem's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full paths)
+ISSM_DIR="/u/astrid-r1b/schlegel/issmuci"
+ISSM_TIER="/u/astrid-r1b/schlegel/issmuci/trunk-jpl/cron/trunk-jpl"
+#ISSM_TIER="/u/astrid-r1b/seroussi/svn/issm/trunk/cron/issm2.2"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#Machine configuration
+MACHINE="astrid"
+
+#MATLAB path
+MATLAB_PATH="/usr/local/pkgs/matlab-7.6/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="update"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/astrid-r1b/schlegel/ExecutionNightlyRun"
+
+#-----------------------------------#
+# 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="none"
+EXTERNALPACKAGESDIR="/u/astrid-r1b/schlegel/issmuci/trunk-jpl/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco"
+
+#---------------------#
+# 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_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="schlegel@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=7
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS=""
Index: /issm/trunk-jpl-damage/cron/configs/linux64_schlegel_nightly
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/linux64_schlegel_nightly	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/linux64_schlegel_nightly	(revision 11330)
@@ -0,0 +1,93 @@
+#
+########### Configuration file for Mathieu Morlighem's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full path)
+ISSM_DIR="/u/astrid-r1b/schlegel/issmuci"
+ISSM_TIER="/u/astrid-r1b/schlegel/issmuci/trunk-jpl/cron/trunk-jpl"
+#ISSM_TIER="/u/astrid-r1b/seroussi/svn/issm/trunk/cron/issm2.2"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#Machine configuration
+MACHINE="astrid"
+
+#MATLAB path
+MATLAB_PATH="/usr/local/pkgs/matlab-7.6/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="checkout"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/astrid-r1b/schlegel/ExecutionNightlyRun"
+
+#-----------------------------------#
+# 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="/u/astrid-r1b/schlegel/issmuci/trunk-jpl/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco"
+
+#---------------------#
+# 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_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="schlegel@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=1
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=7
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS=""
Index: /issm/trunk-jpl-damage/cron/configs/linux64_schlegel_ucitrunk
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/linux64_schlegel_ucitrunk	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/linux64_schlegel_ucitrunk	(revision 11330)
@@ -0,0 +1,93 @@
+#
+########### Configuration file for Mathieu Morlighem's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full path)
+ISSM_DIR="/u/astrid-r1b/schlegel/issmuci"
+ISSM_TIER="/u/astrid-r1b/schlegel/issmuci/trunk-jpl/cron/trunk"
+#ISSM_TIER="/u/astrid-r1b/seroussi/svn/issm/trunk/cron/issm2.2"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#Machine configuration
+MACHINE="astrid"
+
+#MATLAB path
+MATLAB_PATH="/usr/local/pkgs/matlab-7.6/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="checkout"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/astrid-r1b/schlegel/ExecutionNightlyRun"
+
+#-----------------------------------#
+# 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="/u/astrid-r1b/schlegel/issmuci/trunk-jpl/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco"
+
+#---------------------#
+# 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_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="schlegel@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=1
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=7
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS=""
Index: /issm/trunk-jpl-damage/cron/configs/linux64_schlegel_validation
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/linux64_schlegel_validation	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/linux64_schlegel_validation	(revision 11330)
@@ -0,0 +1,92 @@
+########### Configuration file for Mathieu Morlighem's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full path)
+ISSM_DIR="/u/astrid-r1b/schlegel/issmuci"
+ISSM_TIER="/u/astrid-r1b/schlegel/issmuci/trunk-jpl/cron/trunk-jpl"
+#ISSM_TIER="/u/astrid-r1b/seroussi/svn/issm/trunk/cron/issm2.2"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#Machine configuration
+MACHINE="astrid"
+
+#MATLAB path
+MATLAB_PATH="/usr/local/pkgs/matlab-7.6/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="checkout"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/astrid-r1b/schlegel/ExecutionNightlyRun"
+
+#-----------------------------------#
+# 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="/u/astrid-r1b/schlegel/issmuci/trunk-jpl/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco yams"
+
+#---------------------#
+# 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_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="schlegel@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=1
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=7
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS="'benchmark','all'"
Index: /issm/trunk-jpl-damage/cron/configs/linux64_seroussi
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/linux64_seroussi	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/linux64_seroussi	(revision 11330)
@@ -0,0 +1,92 @@
+#
+########### Configuration file for Helene Seroussi's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full path)
+ISSM_DIR="/u/wilkes-r1b/seroussi/issm"
+ISSM_TIER="/u/wilkes-r1b/seroussi/issm/trunk-jpl/cron/trunk-jpl"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#Machine configuration
+MACHINE="astrid"
+
+#MATLAB path
+MATLAB_PATH="/usr/local/pkgs/matlab-7.6/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="update"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/wilkes-r1b/seroussi/ExecutionNightlyRun"
+
+#-----------------------------------#
+# 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="none"
+EXTERNALPACKAGESDIR="/u/wilkes-r1b/seroussi/issm/trunk-jpl/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco"
+
+#---------------------#
+# 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_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="helene.seroussi@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=7
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS=""
Index: /issm/trunk-jpl-damage/cron/configs/linux64_seroussi_daily
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/linux64_seroussi_daily	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/linux64_seroussi_daily	(revision 11330)
@@ -0,0 +1,93 @@
+#
+########### Configuration file for Mathieu Morlighem's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full paths)
+ISSM_DIR="/u/astrid-r1b/seroussi/issm"
+ISSM_TIER="/u/astrid-r1b/seroussi/issm/trunk-jpl/cron/trunk-jpl"
+#ISSM_TIER="/u/astrid-r1b/seroussi/svn/issm/trunk/cron/issm2.2"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#Machine configuration
+MACHINE="astrid"
+
+#MATLAB path
+MATLAB_PATH="/usr/local/pkgs/matlab-7.6/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="update"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/astrid-r1b/seroussi/ExecutionNightlyRun"
+
+#-----------------------------------#
+# 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="none"
+EXTERNALPACKAGESDIR="/u/astrid-r1b/seroussi/issm/trunk-jpl/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco"
+
+#---------------------#
+# 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_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="helene.seroussi@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=7
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS=""
Index: /issm/trunk-jpl-damage/cron/configs/linux64_seroussi_nightly
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/linux64_seroussi_nightly	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/linux64_seroussi_nightly	(revision 11330)
@@ -0,0 +1,93 @@
+#
+########### Configuration file for Mathieu Morlighem's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full path)
+ISSM_DIR="/u/astrid-r1b/seroussi/issm"
+ISSM_TIER="/u/astrid-r1b/seroussi/issm/trunk-jpl/cron/trunk-jpl"
+#ISSM_TIER="/u/astrid-r1b/seroussi/svn/issm/trunk/cron/issm2.2"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#Machine configuration
+MACHINE="astrid"
+
+#MATLAB path
+MATLAB_PATH="/usr/local/pkgs/matlab-7.6/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="checkout"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/astrid-r1b/seroussi/ExecutionNightlyRun"
+
+#-----------------------------------#
+# 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="/u/astrid-r1b/seroussi/issm/trunk-jpl/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco"
+
+#---------------------#
+# 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_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="helene.seroussi@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=1
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=7
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS=""
Index: /issm/trunk-jpl-damage/cron/configs/linux64_seroussi_ucitrunk
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/linux64_seroussi_ucitrunk	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/linux64_seroussi_ucitrunk	(revision 11330)
@@ -0,0 +1,93 @@
+#
+########### Configuration file for Mathieu Morlighem's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full path)
+ISSM_DIR="/u/astrid-r1b/seroussi/issm"
+ISSM_TIER="/u/astrid-r1b/seroussi/issm/trunk-jpl/cron/trunk"
+#ISSM_TIER="/u/astrid-r1b/seroussi/svn/issm/trunk/cron/issm2.2"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#Machine configuration
+MACHINE="astrid"
+
+#MATLAB path
+MATLAB_PATH="/usr/local/pkgs/matlab-7.6/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="checkout"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/astrid-r1b/seroussi/ExecutionNightlyRun"
+
+#-----------------------------------#
+# 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="/u/astrid-r1b/seroussi/issm/trunk-jpl/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco"
+
+#---------------------#
+# 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_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="helene.seroussi@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=1
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=7
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS=""
Index: /issm/trunk-jpl-damage/cron/configs/linux64_seroussi_validation
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/linux64_seroussi_validation	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/linux64_seroussi_validation	(revision 11330)
@@ -0,0 +1,92 @@
+########### Configuration file for Mathieu Morlighem's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full path)
+ISSM_DIR="/u/astrid-r1b/seroussi/issm"
+ISSM_TIER="/u/astrid-r1b/seroussi/issm/trunk-jpl/cron/trunk-jpl"
+#ISSM_TIER="/u/astrid-r1b/seroussi/svn/issm/trunk/cron/issm2.2"
+
+#ISSM Architecture
+ISSM_ARCH="linux-gnu-amd64"
+
+#Machine configuration
+MACHINE="astrid"
+
+#MATLAB path
+MATLAB_PATH="/usr/local/pkgs/matlab-7.6/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="checkout"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/astrid-r1b/seroussi/ExecutionNightlyRun"
+
+#-----------------------------------#
+# 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="/u/astrid-r1b/seroussi/issm/trunk-jpl/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco yams"
+
+#---------------------#
+# 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_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="helene.seroussi@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=1
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=7
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS="'benchmark','all'"
Index: /issm/trunk-jpl-damage/cron/configs/macosx32_seroussi
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/macosx32_seroussi	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/macosx32_seroussi	(revision 11330)
@@ -0,0 +1,92 @@
+#
+########### Configuration file for Helene Seroussi's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full path)
+ISSM_DIR="/Users/seroussi/Desktop/issmuci"
+ISSM_TIER="/Users/seroussi/Desktop/issmuci/trunk-jpl/cron/trunk-jpl"
+
+#ISSM Architecture
+ISSM_ARCH="macosx-gnu"
+
+#Machine configuration
+MACHINE="macmathieu"
+
+#MATLAB path
+MATLAB_PATH="/Applications/MATLAB_R2009a.app/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="update"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH=""
+
+#-----------------------------------#
+# 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="none"
+EXTERNALPACKAGESDIR=""
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco"
+
+#---------------------#
+# 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_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="helene.seroussi@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=1
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=1
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS=""
Index: /issm/trunk-jpl-damage/cron/configs/macosx64_larour
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/macosx64_larour	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/macosx64_larour	(revision 11330)
@@ -0,0 +1,91 @@
+#
+########### Configuration file for Eric Larour's nightly run on Mac ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full pathto ISSM trunk)
+ISSM_DIR="/Users/larour/issm/trunk"
+
+#ISSM Architecture
+ISSM_ARCH="macosx-gnu"
+
+#Operating System
+OS="macosx64"
+
+#MATLAB path
+MATLAB_PATH="/Applications/MATLAB_R2008a/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="update"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH=""
+
+#-----------------------------------#
+# 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="copy"
+EXTERNALPACKAGESDIR=""
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle"
+
+#---------------------#
+# 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"
+
+#------------------------#
+# 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=1
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=1
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS=""
Index: /issm/trunk-jpl-damage/cron/configs/winxp32_larour
===================================================================
--- /issm/trunk-jpl-damage/cron/configs/winxp32_larour	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/configs/winxp32_larour	(revision 11330)
@@ -0,0 +1,92 @@
+#
+########### Configuration file for Eric Larour's nightly run on Linux ############
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM main directory (full path)
+ISSM_DIR="C:/home/issm/trunk-jpl"
+ISSM_TIER="C:/home/issm/trunk-jpl/cron/trunk-jpl"
+
+#ISSM Architecture
+ISSM_ARCH="cygwin-intel"
+
+#Machine configuration
+MACHINE="wineric"
+
+#MATLAB path
+MATLAB_PATH="C:/MATLAB/R2009a/"
+
+#----------------------#
+# 2: ISSM Installation #
+#----------------------#
+
+#ISSM_INSTALLATION can have 3 values:
+# - "checkout" the existing version of the code will be erased and
+#              the latest version will be checked out
+# - "update"   the directory won't be erased but ISSM will be updated
+#              ->skip to section 3
+# - "none"     leave ISSM as is in its directory
+#              ->skip to section 3
+ISSM_INSTALLATION="update"
+
+#SVN repository
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+#REPOSITORY="http://s383-rhat/issm/svn/issm/branches/issm2.2"
+
+#execution path used for parallel runs
+EXECUTION_PATH="/u/astrid-r1b/larour/issm/execution"
+
+#-----------------------------------#
+# 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="none"
+EXTERNALPACKAGESDIR="/cygdrive/c/home/externalpackages"
+
+#List of external pakages to be installed
+EXTERNALPACKAGES="autoconf automake matlab mpich2 petsc metis triangle dakota chaco"
+
+#---------------------#
+# 4: ISSM Compilation #
+#---------------------#
+
+#ISSM_COMPILATION can have 2 values:
+# - "yes" compile ISSM
+# - "no"  do not compile ISSM
+ISSM_COMPILATION="no"
+
+#----------------------#
+# 5: Mail notification #
+#----------------------#
+
+#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
+#sent to the adresses present in $ISSM_TIER/cron/mailinglist.
+SKIPMAIL="no"
+
+#Sender email address
+EMAIL_ADRESS="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=1
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=1
+
+#Nightly run options. The matlab routine nightlyrun.m will be called
+#as follows: nightlyrun($NROPTIONS). The options must be understandable
+#by Matlab and nightlyrun.m
+#ex: "'id',[101 102 103]"
+
+NROPTIONS=""
Index: /issm/trunk-jpl-damage/cron/cronfiles/linux_cronfile
===================================================================
--- /issm/trunk-jpl-damage/cron/cronfiles/linux_cronfile	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/cronfiles/linux_cronfile	(revision 11330)
@@ -0,0 +1,14 @@
+#use /bin/bash to run commands, overriding the default set by cron
+SHELL=/bin/bash
+
+#mail output to Mathieu
+MAILTO=eric.larour@jpl.nasa.gov,mathieu.morlighem@jpl.nasa.gov,helene.seroussi@jpl.nasa.gov,Christopher.P.Borstad@jpl.nasa.gov,Nicole-Jeanne.Schlegel@jpl.nasa.gov,Feras.A.Habbal@jpl.nasa.gov
+
+#cronjob
+00 09 * * 1-5 cd /u/astrid-r1b/seroussi/issm/trunk-jpl/cron/ && ./nightlyrun.sh configs/linux64_seroussi_daily
+30 12 * * 1-5 cd /u/astrid-r1b/seroussi/issm/trunk-jpl/cron/ && ./nightlyrun.sh configs/linux64_seroussi_daily
+00 15 * * 1-5 cd /u/astrid-r1b/seroussi/issm/trunk-jpl/cron/ && ./nightlyrun.sh configs/linux64_seroussi_daily
+00 18 * * 1-5 cd /u/astrid-r1b/seroussi/issm/trunk-jpl/cron/ && ./nightlyrun.sh configs/linux64_seroussi_daily
+00 23 * * 1-5 cd /u/astrid-r1b/seroussi/issm/trunk-jpl/cron/ && ./nightlyrun.sh configs/linux64_seroussi_nightly
+00 23 * * 6   cd /u/astrid-r1b/seroussi/issm/trunk-jpl/cron/ && ./nightlyrun.sh configs/linux64_seroussi_validation
+00 23 * * 7   cd /u/astrid-r1b/seroussi/issm/trunk-jpl/cron/ && ./nightlyrun.sh configs/linux64_seroussi_ucitrunk
Index: /issm/trunk-jpl-damage/cron/cronfiles/mac_cronfile
===================================================================
--- /issm/trunk-jpl-damage/cron/cronfiles/mac_cronfile	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/cronfiles/mac_cronfile	(revision 11330)
@@ -0,0 +1,8 @@
+#use /bin/bash to run commands, overriding the default set by cron
+SHELL=/bin/bash
+
+#mail output to Helene
+MAILTO=eric.larour@jpl.nasa.gov,mathieu.morlighem@jpl.nasa.gov,helene.seroussi@jpl.nasa.gov
+
+#cronjob: issm 9:00pm
+50 9 * * * cd /Users/seroussi/Desktop/backup/svn/issm/trunk/cron/ && ./nightlyrun.sh configs/macosx32_seroussi
Index: /issm/trunk-jpl-damage/cron/cronfiles/winxp32_cronfile
===================================================================
--- /issm/trunk-jpl-damage/cron/cronfiles/winxp32_cronfile	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/cronfiles/winxp32_cronfile	(revision 11330)
@@ -0,0 +1,8 @@
+#use /bin/bash to run commands, overriding the default set by cron
+SHELL=/bin/bash
+
+#mail output to Eric
+MAILTO=eric.larour@jpl.nasa.gov,mathieu.morlighem@jpl.nasa.gov,helene.seroussi@jpl.nasa.gov
+
+#cronjob: issm sunday-friday 9:00pm
+0 21 * * 0-5 cd /cygdrive/c/home/issm/trunk/cron  && ./nightlyrun.sh configs/winxp32_larour
Index: /issm/trunk-jpl-damage/cron/mailinglist
===================================================================
--- /issm/trunk-jpl-damage/cron/mailinglist	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/mailinglist	(revision 11330)
@@ -0,0 +1,2 @@
+#Mailing list for nightly runs
+MAILINGLIST="mathieu.morlighem@jpl.nasa.gov helene.seroussi@jpl.nasa.gov eric.larour@jpl.nasa.gov John.E.Schiermeier@jpl.nasa.gov Nicole-Jeanne.Schlegel@jpl.nasa.gov christopher.p.borstad@jpl.nasa.gov Feras.A.Habbal@jpl.nasa.gov Daria.J.Halkides@jpl.nasa.gov"
Index: /issm/trunk-jpl-damage/cron/nightlyrun.sh
===================================================================
--- /issm/trunk-jpl-damage/cron/nightlyrun.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/cron/nightlyrun.sh	(revision 11330)
@@ -0,0 +1,317 @@
+#!/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() #{{{1
+{
+	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() #{{{1
+{
+	suffix=`date | awk '{printf("%s-%s-%s  %s",$2,$3,$6,$4);}'`			 
+	echo $suffix;			 
+} #}}}
+function host_name() #{{{1
+{
+	#return host name depending on the OS
+	if [ "$1" = "wineric" ] 
+	then
+		HOST_NAME=`hostname`;
+	else
+		HOST_NAME=`hostname -s`;
+	fi
+	echo $HOST_NAME;
+} #}}}
+
+#Get configuration
+#Source config file{{{1
+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;
+#}}}
+#Export ISSM_* variables{{{1
+export ISSM_DIR
+export ISSM_TIER
+export ISSM_ARCH
+#}}}
+#Initialize variables {{{1
+TODAY=$(todaydate);
+HOST_NAME=$(host_name $MACHINE);
+START_TIME=$(timer);
+ISSM_RELEASE=$(basename $(echo $REPOSITORY));
+USER=$(whoami);
+INIT_PATH=$(pwd);
+#}}}
+
+#Lauch installation
+#Checkout/update/none ISSM if requested (ISSM_INSTALLATION){{{1
+if [ "$ISSM_INSTALLATION" == "checkout" ]
+then
+
+	#Erase previous code and Fetch the new one
+	rm -rf $ISSM_RELEASE
+	svn checkout $REPOSITORY
+
+elif [ "$ISSM_INSTALLATION" == "update" ]
+then
+
+	#only update ISSM
+	cd $ISSM_TIER
+	svn update
+
+elif [ "$ISSM_INSTALLATION" == "none" ]
+then
+
+	#do nothing
+	echo "Skipping ISSM installation"
+
+else
+
+	#Error message
+	echo "ISSM_INSTALLATION supported values are: checkout, update and none. Exiting..." >&2 # Error message to stderr.
+	exit 1
+
+fi
+#}}}
+#Create cluster's settings{{{1
+#create simpler  cluster.rc file, with only the cluster we are interested in.
+cd $ISSM_TIER/test/NightlyRun/
+cat << END > $HOST_NAME"_settings.m"
+cluster.login='$USER';
+cluster.codepath='$ISSM_TIER/bin';
+cluster.executionpath='$EXECUTION_PATH';
+END
+#}}}
+#Source environment variables with new matlab path {{{1
+cd $ISSM_TIER/etc
+source environment.sh MATLAB_DIR=$MATLAB_PATH
+#}}}
+#install/copy/none external packages    (ISSM_EXTERNALPACKAGES){{{1
+if [ "$ISSM_EXTERNALPACKAGES" == "install" ]
+then
+	cd $ISSM_TIER/externalpackages
+	for ep in $EXTERNALPACKAGES
+	do 
+		cd $ep
+		case $ep in
+			"mpich2" )   ./install-1.0.2-linux64.sh ;;
+			"petsc" )    ./install-3.2-linux64.sh   ;;
+			"metis" )    ./install-4.0-linux64.sh ;;
+			"triangle" ) ./install-linux64.sh ;;
+			"dakota" )   ./install-linux64-astrid.sh ;;
+			*)           ./install.sh $NUMCPUS_INSTALL
+		esac
+		cd ..
+	done
+
+elif [ "$ISSM_EXTERNALPACKAGES" == "copy" ]
+then
+
+	#erase externapackages, and link with externalpackages_dir
+	cd $ISSM_TIER
+	rm -rf externalpackages
+	cp -Rf $EXTERNALPACKAGESDIR ./
+
+elif [ "$ISSM_EXTERNALPACKAGES" == "none" ]
+then
+
+	#Do nothing
+	echo "Skipping external packages installation"
+
+else
+
+	#Error message
+	echo "ISSM_EXTERNALPACKAGES supported values are: install, copy and none. Exiting..." >&2 # Error message to stderr.
+	exit 1
+
+fi
+#}}}
+#ISSM compilation yes/no                (ISSM_COMPILATION) {{{1
+if [ "$ISSM_COMPILATION" == "yes" ]
+then
+
+	cd $ISSM_TIER
+	make clean
+	make distclean
+	./scripts/automakererun.sh
+	./configs/config-linux64-astrid.sh
+
+	#4: compile and install ISSM
+	if [ "$MACHINE" = "wineric" ] 
+	then
+		cd $ISSM_TIER/src/c
+		./intel-compile.sh
+		cd $ISSM_TIER/src/mex
+		make install
+		cd $ISSM_TIER
+	else
+		make -j $NUMCPUS_INSTALL
+		make -j $NUMCPUS_INSTALL install
+	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
+#}}}
+
+#Prepare run
+#create softlink to startup {{{1
+cd $ISSM_TIER/test/NightlyRun/
+ln -s $ISSM_TIER/startup.m .
+#}}}
+#Create nightlylog directory and info.log {{{1
+#put installation elapsed time in info.log
+INSTALL_TIME=$(timer)
+ELAPSED_INSTALL=$(timer $START_TIME)
+rm -rf $ISSM_TIER/nightlylog
+mkdir  $ISSM_TIER/nightlylog
+cat << END > $ISSM_TIER/nightlylog/info.log
+today:     $(echo $TODAY)
+user:      $(echo $USER)
+host:      $(echo $HOST_NAME)
+OS:        $(echo $MACHINE)
+release:   $(echo $ISSM_RELEASE)
+init_path: $(echo $INIT_PATH)
+elapsed_install: $(echo $ELAPSED_INSTALL)
+END
+#}}}
+#check NUMCPUS_RUN options {{{1
+if [ "$NUMCPUS_RUN" = "" ]
+then
+	echo "NUMCPUS_RUN option not found, defaulting to NUMCPUS_RUN = 1"
+	NUMCPUS_RUN=1
+fi
+#}}}
+
+#Run tests
+#Launch all tests on different cpus {{{1
+for (( i=1;i<=$NUMCPUS_RUN;i++ ))
+do
+	#Launch matlab and the nightly run script
+	cat > $ISSM_TIER/nightlylog/matlab_run$i.m << EOF
+	warning off %necessary to avoid a info.log of several Go for parallel runs
+	try,
+	cd $ISSM_TIER/test/NightlyRun
+	startup;
+	$(if [ "$NROPTIONS" = ""  ]
+	then
+		echo "runme('output','nightly','rank',$i,'numprocs',$NUMCPUS_RUN);"
+	else
+		echo "runme($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([ISSM_TIER '/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
+
+	#Start run from nightlylog directory
+	cd $ISSM_TIER/nightlylog/
+
+	#Start test
+	MATLAB_VERSION="7.6" #7.2,7.4,7.6 and 7.8
+	/usr/local/pkgs/matlab-$MATLAB_VERSION/bin/matlab  -nojvm -nosplash  -r matlab_run$i -logfile matlab_log$i.log &
+done
+
+#wait until matlab closes
+wait
+#}}}
+#concatenate all reports {{{1
+cd $ISSM_TIER/nightlylog/
+mv matlab_log1.log  matlab_log.log
+for (( i=2;i<=$NUMCPUS_RUN;i++ ))
+do
+	cat matlab_log.log matlab_log$i.log > matlab_log.log.bak
+	mv matlab_log.log.bak matlab_log.log
+done
+#}}}
+#Complete info.log {{{1
+if [ $(cat matlab_log.log | grep "MATLABEXITEDCORRECTLY" | wc -l) -eq $NUMCPUS_RUN ]
+then
+	MATLABCRASH=0
+else
+	MATLABCRASH=1
+fi
+ELAPSED_RUN=$(timer $INSTALL_TIME)
+ELAPSED_TOTAL=$(timer $START_TIME)
+cat << END >>  $ISSM_TIER/nightlylog/info.log
+elapsed_run:   $(echo $ELAPSED_RUN)
+elapsed_total: $(echo $ELAPSED_TOTAL)
+matlab_crash:  $(echo $MATLABCRASH)
+END
+#}}}
+
+#Send Report
+#Build html report {{{1
+cd $ISSM_TIER/nightlylog/
+sh ../scripts/report.sh
+echo "html report located in $ISSM_TIER/nightlylog/report.html"
+#}}}
+#send mail if requested                  (SKIPMAIL) {{{1
+if [ "$SKIPMAIL" != "yes" ]
+then
+	echo "sending report..."
+	source $ISSM_TIER/cron/mailinglist
+	for i in `echo $MAILINGLIST`; do
+
+		if [ "$MACHINE" = "wineric" ]
+		then
+			email -html -f "ISSM Nightly run $EMAIL_ADRESS" -s "Nightly runs of $ISSM_RELEASE , configuration: $MACHINE, host: $HOST_NAME, user: $USER. " $i < $ISSM_TIER/test/Verification/NightlyRun/report.html
+		else 
+			if [ "$MACHINE" = "astrid" ]
+			then
+cat - $ISSM_TIER/nightlylog/report.html <<HERE | /usr/lib/sendmail  -oi -t
+From: "ISSM Nightly run" <$EMAIL_ADRESS>
+To: $i
+Subject: Nightly runs of $ISSM_RELEASE, configuration: $MACHINE, host: $HOST_NAME, user: $USER.
+Mime-Version: 1.0
+Content-Type: text/html
+HERE
+		else
+cat - $ISSM_TIER/nightlylog/report.html <<HERE | /usr/sbin/sendmail  -oi -t
+From: "ISSM Nightly run" <$EMAIL_ADRESS>
+To: $i
+Subject: Nightly runs of $ISSM_RELEASE, configuration: $MACHINE, host: $HOST_NAME, user: $USER.
+Mime-Version: 1.0
+Content-Type: text/html
+HERE
+			fi
+		fi
+	done
+fi
+#}}}
Index: /issm/trunk-jpl-damage/depcomp
===================================================================
--- /issm/trunk-jpl-damage/depcomp	(revision 11330)
+++ /issm/trunk-jpl-damage/depcomp	(revision 11330)
@@ -0,0 +1,589 @@
+#! /bin/sh
+# depcomp - compile a program generating dependencies as side-effects
+
+scriptversion=2007-03-29.01
+
+# Copyright (C) 1999, 2000, 2003, 2004, 2005, 2006, 2007 Free Software
+# Foundation, Inc.
+
+# 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, 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, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301, USA.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# Originally written by Alexandre Oliva <oliva@dcc.unicamp.br>.
+
+case $1 in
+  '')
+     echo "$0: No command.  Try \`$0 --help' for more information." 1>&2
+     exit 1;
+     ;;
+  -h | --h*)
+    cat <<\EOF
+Usage: depcomp [--help] [--version] PROGRAM [ARGS]
+
+Run PROGRAMS ARGS to compile a file, generating dependencies
+as side-effects.
+
+Environment variables:
+  depmode     Dependency tracking mode.
+  source      Source file read by `PROGRAMS ARGS'.
+  object      Object file output by `PROGRAMS ARGS'.
+  DEPDIR      directory where to store dependencies.
+  depfile     Dependency file to output.
+  tmpdepfile  Temporary file to use when outputing dependencies.
+  libtool     Whether libtool is used (yes/no).
+
+Report bugs to <bug-automake@gnu.org>.
+EOF
+    exit $?
+    ;;
+  -v | --v*)
+    echo "depcomp $scriptversion"
+    exit $?
+    ;;
+esac
+
+if test -z "$depmode" || test -z "$source" || test -z "$object"; then
+  echo "depcomp: Variables source, object and depmode must be set" 1>&2
+  exit 1
+fi
+
+# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po.
+depfile=${depfile-`echo "$object" |
+  sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`}
+tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
+
+rm -f "$tmpdepfile"
+
+# Some modes work just like other modes, but use different flags.  We
+# parameterize here, but still list the modes in the big case below,
+# to make depend.m4 easier to write.  Note that we *cannot* use a case
+# here, because this file can only contain one case statement.
+if test "$depmode" = hp; then
+  # HP compiler uses -M and no extra arg.
+  gccflag=-M
+  depmode=gcc
+fi
+
+if test "$depmode" = dashXmstdout; then
+   # This is just like dashmstdout with a different argument.
+   dashmflag=-xM
+   depmode=dashmstdout
+fi
+
+case "$depmode" in
+gcc3)
+## gcc 3 implements dependency tracking that does exactly what
+## we want.  Yay!  Note: for some reason libtool 1.4 doesn't like
+## it if -MD -MP comes after the -MF stuff.  Hmm.
+## Unfortunately, FreeBSD c89 acceptance of flags depends upon
+## the command line argument order; so add the flags where they
+## appear in depend2.am.  Note that the slowdown incurred here
+## affects only configure: in makefiles, %FASTDEP% shortcuts this.
+  for arg
+  do
+    case $arg in
+    -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;;
+    *)  set fnord "$@" "$arg" ;;
+    esac
+    shift # fnord
+    shift # $arg
+  done
+  "$@"
+  stat=$?
+  if test $stat -eq 0; then :
+  else
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  mv "$tmpdepfile" "$depfile"
+  ;;
+
+gcc)
+## There are various ways to get dependency output from gcc.  Here's
+## why we pick this rather obscure method:
+## - Don't want to use -MD because we'd like the dependencies to end
+##   up in a subdir.  Having to rename by hand is ugly.
+##   (We might end up doing this anyway to support other compilers.)
+## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like
+##   -MM, not -M (despite what the docs say).
+## - Using -M directly means running the compiler twice (even worse
+##   than renaming).
+  if test -z "$gccflag"; then
+    gccflag=-MD,
+  fi
+  "$@" -Wp,"$gccflag$tmpdepfile"
+  stat=$?
+  if test $stat -eq 0; then :
+  else
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  rm -f "$depfile"
+  echo "$object : \\" > "$depfile"
+  alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
+## The second -e expression handles DOS-style file names with drive letters.
+  sed -e 's/^[^:]*: / /' \
+      -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile"
+## This next piece of magic avoids the `deleted header file' problem.
+## The problem is that when a header file which appears in a .P file
+## is deleted, the dependency causes make to die (because there is
+## typically no way to rebuild the header).  We avoid this by adding
+## dummy dependencies for each header file.  Too bad gcc doesn't do
+## this for us directly.
+  tr ' ' '
+' < "$tmpdepfile" |
+## Some versions of gcc put a space before the `:'.  On the theory
+## that the space means something, we add a space to the output as
+## well.
+## Some versions of the HPUX 10.20 sed can't process this invocation
+## correctly.  Breaking it into two sed invocations is a workaround.
+    sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+hp)
+  # This case exists only to let depend.m4 do its work.  It works by
+  # looking at the text of this script.  This case will never be run,
+  # since it is checked for above.
+  exit 1
+  ;;
+
+sgi)
+  if test "$libtool" = yes; then
+    "$@" "-Wp,-MDupdate,$tmpdepfile"
+  else
+    "$@" -MDupdate "$tmpdepfile"
+  fi
+  stat=$?
+  if test $stat -eq 0; then :
+  else
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  rm -f "$depfile"
+
+  if test -f "$tmpdepfile"; then  # yes, the sourcefile depend on other files
+    echo "$object : \\" > "$depfile"
+
+    # Clip off the initial element (the dependent).  Don't try to be
+    # clever and replace this with sed code, as IRIX sed won't handle
+    # lines with more than a fixed number of characters (4096 in
+    # IRIX 6.2 sed, 8192 in IRIX 6.5).  We also remove comment lines;
+    # the IRIX cc adds comments like `#:fec' to the end of the
+    # dependency line.
+    tr ' ' '
+' < "$tmpdepfile" \
+    | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \
+    tr '
+' ' ' >> $depfile
+    echo >> $depfile
+
+    # The second pass generates a dummy entry for each header file.
+    tr ' ' '
+' < "$tmpdepfile" \
+   | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
+   >> $depfile
+  else
+    # The sourcefile does not contain any dependencies, so just
+    # store a dummy comment line, to avoid errors with the Makefile
+    # "include basename.Plo" scheme.
+    echo "#dummy" > "$depfile"
+  fi
+  rm -f "$tmpdepfile"
+  ;;
+
+aix)
+  # The C for AIX Compiler uses -M and outputs the dependencies
+  # in a .u file.  In older versions, this file always lives in the
+  # current directory.  Also, the AIX compiler puts `$object:' at the
+  # start of each line; $object doesn't have directory information.
+  # Version 6 uses the directory in both cases.
+  dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
+  test "x$dir" = "x$object" && dir=
+  base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
+  if test "$libtool" = yes; then
+    tmpdepfile1=$dir$base.u
+    tmpdepfile2=$base.u
+    tmpdepfile3=$dir.libs/$base.u
+    "$@" -Wc,-M
+  else
+    tmpdepfile1=$dir$base.u
+    tmpdepfile2=$dir$base.u
+    tmpdepfile3=$dir$base.u
+    "$@" -M
+  fi
+  stat=$?
+
+  if test $stat -eq 0; then :
+  else
+    rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
+    exit $stat
+  fi
+
+  for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
+  do
+    test -f "$tmpdepfile" && break
+  done
+  if test -f "$tmpdepfile"; then
+    # Each line is of the form `foo.o: dependent.h'.
+    # Do two passes, one to just change these to
+    # `$object: dependent.h' and one to simply `dependent.h:'.
+    sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile"
+    # That's a tab and a space in the [].
+    sed -e 's,^.*\.[a-z]*:[	 ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
+  else
+    # The sourcefile does not contain any dependencies, so just
+    # store a dummy comment line, to avoid errors with the Makefile
+    # "include basename.Plo" scheme.
+    echo "#dummy" > "$depfile"
+  fi
+  rm -f "$tmpdepfile"
+  ;;
+
+icc)
+  # Intel's C compiler understands `-MD -MF file'.  However on
+  #    icc -MD -MF foo.d -c -o sub/foo.o sub/foo.c
+  # ICC 7.0 will fill foo.d with something like
+  #    foo.o: sub/foo.c
+  #    foo.o: sub/foo.h
+  # which is wrong.  We want:
+  #    sub/foo.o: sub/foo.c
+  #    sub/foo.o: sub/foo.h
+  #    sub/foo.c:
+  #    sub/foo.h:
+  # ICC 7.1 will output
+  #    foo.o: sub/foo.c sub/foo.h
+  # and will wrap long lines using \ :
+  #    foo.o: sub/foo.c ... \
+  #     sub/foo.h ... \
+  #     ...
+
+  "$@" -MD -MF "$tmpdepfile"
+  stat=$?
+  if test $stat -eq 0; then :
+  else
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  rm -f "$depfile"
+  # Each line is of the form `foo.o: dependent.h',
+  # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'.
+  # Do two passes, one to just change these to
+  # `$object: dependent.h' and one to simply `dependent.h:'.
+  sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile"
+  # Some versions of the HPUX 10.20 sed can't process this invocation
+  # correctly.  Breaking it into two sed invocations is a workaround.
+  sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" |
+    sed -e 's/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+hp2)
+  # The "hp" stanza above does not work with aCC (C++) and HP's ia64
+  # compilers, which have integrated preprocessors.  The correct option
+  # to use with these is +Maked; it writes dependencies to a file named
+  # 'foo.d', which lands next to the object file, wherever that
+  # happens to be.
+  # Much of this is similar to the tru64 case; see comments there.
+  dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
+  test "x$dir" = "x$object" && dir=
+  base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
+  if test "$libtool" = yes; then
+    tmpdepfile1=$dir$base.d
+    tmpdepfile2=$dir.libs/$base.d
+    "$@" -Wc,+Maked
+  else
+    tmpdepfile1=$dir$base.d
+    tmpdepfile2=$dir$base.d
+    "$@" +Maked
+  fi
+  stat=$?
+  if test $stat -eq 0; then :
+  else
+     rm -f "$tmpdepfile1" "$tmpdepfile2"
+     exit $stat
+  fi
+
+  for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2"
+  do
+    test -f "$tmpdepfile" && break
+  done
+  if test -f "$tmpdepfile"; then
+    sed -e "s,^.*\.[a-z]*:,$object:," "$tmpdepfile" > "$depfile"
+    # Add `dependent.h:' lines.
+    sed -ne '2,${; s/^ *//; s/ \\*$//; s/$/:/; p;}' "$tmpdepfile" >> "$depfile"
+  else
+    echo "#dummy" > "$depfile"
+  fi
+  rm -f "$tmpdepfile" "$tmpdepfile2"
+  ;;
+
+tru64)
+   # The Tru64 compiler uses -MD to generate dependencies as a side
+   # effect.  `cc -MD -o foo.o ...' puts the dependencies into `foo.o.d'.
+   # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put
+   # dependencies in `foo.d' instead, so we check for that too.
+   # Subdirectories are respected.
+   dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
+   test "x$dir" = "x$object" && dir=
+   base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
+
+   if test "$libtool" = yes; then
+      # With Tru64 cc, shared objects can also be used to make a
+      # static library.  This mechanism is used in libtool 1.4 series to
+      # handle both shared and static libraries in a single compilation.
+      # With libtool 1.4, dependencies were output in $dir.libs/$base.lo.d.
+      #
+      # With libtool 1.5 this exception was removed, and libtool now
+      # generates 2 separate objects for the 2 libraries.  These two
+      # compilations output dependencies in $dir.libs/$base.o.d and
+      # in $dir$base.o.d.  We have to check for both files, because
+      # one of the two compilations can be disabled.  We should prefer
+      # $dir$base.o.d over $dir.libs/$base.o.d because the latter is
+      # automatically cleaned when .libs/ is deleted, while ignoring
+      # the former would cause a distcleancheck panic.
+      tmpdepfile1=$dir.libs/$base.lo.d   # libtool 1.4
+      tmpdepfile2=$dir$base.o.d          # libtool 1.5
+      tmpdepfile3=$dir.libs/$base.o.d    # libtool 1.5
+      tmpdepfile4=$dir.libs/$base.d      # Compaq CCC V6.2-504
+      "$@" -Wc,-MD
+   else
+      tmpdepfile1=$dir$base.o.d
+      tmpdepfile2=$dir$base.d
+      tmpdepfile3=$dir$base.d
+      tmpdepfile4=$dir$base.d
+      "$@" -MD
+   fi
+
+   stat=$?
+   if test $stat -eq 0; then :
+   else
+      rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4"
+      exit $stat
+   fi
+
+   for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4"
+   do
+     test -f "$tmpdepfile" && break
+   done
+   if test -f "$tmpdepfile"; then
+      sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile"
+      # That's a tab and a space in the [].
+      sed -e 's,^.*\.[a-z]*:[	 ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
+   else
+      echo "#dummy" > "$depfile"
+   fi
+   rm -f "$tmpdepfile"
+   ;;
+
+#nosideeffect)
+  # This comment above is used by automake to tell side-effect
+  # dependency tracking mechanisms from slower ones.
+
+dashmstdout)
+  # Important note: in order to support this mode, a compiler *must*
+  # always write the preprocessed file to stdout, regardless of -o.
+  "$@" || exit $?
+
+  # Remove the call to Libtool.
+  if test "$libtool" = yes; then
+    while test $1 != '--mode=compile'; do
+      shift
+    done
+    shift
+  fi
+
+  # Remove `-o $object'.
+  IFS=" "
+  for arg
+  do
+    case $arg in
+    -o)
+      shift
+      ;;
+    $object)
+      shift
+      ;;
+    *)
+      set fnord "$@" "$arg"
+      shift # fnord
+      shift # $arg
+      ;;
+    esac
+  done
+
+  test -z "$dashmflag" && dashmflag=-M
+  # Require at least two characters before searching for `:'
+  # in the target name.  This is to cope with DOS-style filenames:
+  # a dependency such as `c:/foo/bar' could be seen as target `c' otherwise.
+  "$@" $dashmflag |
+    sed 's:^[  ]*[^: ][^:][^:]*\:[    ]*:'"$object"'\: :' > "$tmpdepfile"
+  rm -f "$depfile"
+  cat < "$tmpdepfile" > "$depfile"
+  tr ' ' '
+' < "$tmpdepfile" | \
+## Some versions of the HPUX 10.20 sed can't process this invocation
+## correctly.  Breaking it into two sed invocations is a workaround.
+    sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+dashXmstdout)
+  # This case only exists to satisfy depend.m4.  It is never actually
+  # run, as this mode is specially recognized in the preamble.
+  exit 1
+  ;;
+
+makedepend)
+  "$@" || exit $?
+  # Remove any Libtool call
+  if test "$libtool" = yes; then
+    while test $1 != '--mode=compile'; do
+      shift
+    done
+    shift
+  fi
+  # X makedepend
+  shift
+  cleared=no
+  for arg in "$@"; do
+    case $cleared in
+    no)
+      set ""; shift
+      cleared=yes ;;
+    esac
+    case "$arg" in
+    -D*|-I*)
+      set fnord "$@" "$arg"; shift ;;
+    # Strip any option that makedepend may not understand.  Remove
+    # the object too, otherwise makedepend will parse it as a source file.
+    -*|$object)
+      ;;
+    *)
+      set fnord "$@" "$arg"; shift ;;
+    esac
+  done
+  obj_suffix="`echo $object | sed 's/^.*\././'`"
+  touch "$tmpdepfile"
+  ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@"
+  rm -f "$depfile"
+  cat < "$tmpdepfile" > "$depfile"
+  sed '1,2d' "$tmpdepfile" | tr ' ' '
+' | \
+## Some versions of the HPUX 10.20 sed can't process this invocation
+## correctly.  Breaking it into two sed invocations is a workaround.
+    sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile" "$tmpdepfile".bak
+  ;;
+
+cpp)
+  # Important note: in order to support this mode, a compiler *must*
+  # always write the preprocessed file to stdout.
+  "$@" || exit $?
+
+  # Remove the call to Libtool.
+  if test "$libtool" = yes; then
+    while test $1 != '--mode=compile'; do
+      shift
+    done
+    shift
+  fi
+
+  # Remove `-o $object'.
+  IFS=" "
+  for arg
+  do
+    case $arg in
+    -o)
+      shift
+      ;;
+    $object)
+      shift
+      ;;
+    *)
+      set fnord "$@" "$arg"
+      shift # fnord
+      shift # $arg
+      ;;
+    esac
+  done
+
+  "$@" -E |
+    sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
+       -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' |
+    sed '$ s: \\$::' > "$tmpdepfile"
+  rm -f "$depfile"
+  echo "$object : \\" > "$depfile"
+  cat < "$tmpdepfile" >> "$depfile"
+  sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+msvisualcpp)
+  # Important note: in order to support this mode, a compiler *must*
+  # always write the preprocessed file to stdout, regardless of -o,
+  # because we must use -o when running libtool.
+  "$@" || exit $?
+  IFS=" "
+  for arg
+  do
+    case "$arg" in
+    "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI")
+	set fnord "$@"
+	shift
+	shift
+	;;
+    *)
+	set fnord "$@" "$arg"
+	shift
+	shift
+	;;
+    esac
+  done
+  "$@" -E |
+  sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::echo "`cygpath -u \\"\1\\"`":p' | sort | uniq > "$tmpdepfile"
+  rm -f "$depfile"
+  echo "$object : \\" > "$depfile"
+  . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::	\1 \\:p' >> "$depfile"
+  echo "	" >> "$depfile"
+  . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::\1\::p' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+none)
+  exec "$@"
+  ;;
+
+*)
+  echo "Unknown depmode $depmode" 1>&2
+  exit 1
+  ;;
+esac
+
+exit 0
+
+# Local Variables:
+# mode: shell-script
+# sh-indentation: 2
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-end: "$"
+# End:
Index: /issm/trunk-jpl-damage/doc/issmdoc.m
===================================================================
--- /issm/trunk-jpl-damage/doc/issmdoc.m	(revision 11330)
+++ /issm/trunk-jpl-damage/doc/issmdoc.m	(revision 11330)
@@ -0,0 +1,15 @@
+%Quick documentation for ISSM
+
+%First get ISSM tier: 
+ISSM_TIER=issmtier;
+
+disp(sprintf('\n%s','  A comprehensive documentation is available on http://issm.jpl.nasa.gov'));
+disp(sprintf('\n%s','  Example: how to create a square ice shelf'));
+disp(sprintf('%s','	   go to ',ISSM_TIER,'/examples/SquareIceshelf'));
+disp(sprintf('%s','	   md=model;                                %creates a new empty model structure'));
+disp(sprintf('%s','	   md=triangle(md,''DomainOutline.exp'',50000);   %creates a mesh of the domain outline with a resolution of 50000m'));
+disp(sprintf('%s','	   md=geography(md,''all'','''');               %defines the glacier system as an ice shelf (no island)'));
+disp(sprintf('%s','	   md=parameterize(md,''Square.par'');        %fills all the other fields of the model'));
+disp(sprintf('%s','	   md=setelementstype(md,''macayeal'',''all''); %defines all elements as MacAyeal''s'));
+disp(sprintf('%s','	   md=solve(md,DiagnosticSolutionEnum);   %generate the velocity field'));
+disp(sprintf('%s','	   plotmodel(md,''data'',md.results.DiagnosticSolution.Vel);    %displays the velocity (type plotdoc for plotmodel help)'));
Index: /issm/trunk-jpl-damage/etc/environment.csh
===================================================================
--- /issm/trunk-jpl-damage/etc/environment.csh	(revision 11330)
+++ /issm/trunk-jpl-damage/etc/environment.csh	(revision 11330)
@@ -0,0 +1,128 @@
+#ISSM_TIER and ISSM_ARCH should have been defined already in your shell settings file (.bashrc, .cshrc, etc ...)
+source $ISSM_TIER/etc/environment_variables.csh
+
+#Do we have any command line arguments? (such as MATLAB_DIR=otherdirthandefault), source them before exporting the variables 
+#to environment.
+
+#foreach i ($@)
+#eval $i
+#end
+
+#CRON utilities
+setenv PATH {$PATH}:{$ISSM_TIER}/cron
+
+#SCRIPTS utilities
+setenv PATH {$PATH}:{$ISSM_TIER}/scripts
+
+#MATLAB
+setenv MATLAB_DIR {$MATLAB_DIR}
+setenv PATH {$MATLAB_DIR}/bin:{$PATH}
+setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$MATLAB_DIR/lib
+
+#MPI
+setenv MPI_DIR {$MPI_DIR}
+setenv PATH {$MPI_DIR}/bin:{$PATH}
+setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$MPI_DIR/lib
+setenv MANPATH {$MANPATH}:$MPI_DIR/man
+setenv MPIRUN_NPROCS 8
+
+#PETSC
+setenv PETSC_DIR {$PETSC_DIR}
+setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$PETSC_DIR/lib/{$ISSM_ARCH}
+
+#SLEPC
+setenv SLEPC_DIR {$SLEPC_DIR}
+setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$SLEPC_DIR/lib/{$ISSM_ARCH}
+
+
+#Dakota
+setenv DAKOTA_DIR {$DAKOTA_DIR}
+setenv PATH {$PATH}:{$DAKOTA_DIR}/bin
+setenv MANPATH {$MANPATH}:{$MPI_DIR}/man:{$DAKOTA_DIR}/docs/man:{$DAKOTA_DIR}/docs/man-ref
+
+#Qhull
+setenv QHULL_DIR {$QHULL_DIR}
+setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$QHULL_DIR}/lib
+
+
+#Doxygen
+setenv DOXYGEN_DIR {$DOXYGEN_DIR}
+setenv MANPATH {$MANPATH}:{$DOXYGEN_DIR}/man
+setenv PATH {$PATH}:{$DOXYGEN_DIR}/bin
+
+#MTOC
+setenv MTOC_DIR {$MTOC_DIR}
+setenv PATH {$PATH}:{$MTOC_DIR}
+
+#MATLAB
+setenv MATLAB_DIR {$MATLAB_DIR}
+setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$MATLAB_DIR}/bin/glnxa64
+setenv PATH {$PATH}:{$MATLAB_DIR}/bin
+
+#TRIANGLE
+setenv TRIANGLE_DIR {$TRIANGLE_DIR}
+
+#METIS
+setenv METIS_DIR {$METIS_DIR}
+	
+#BLAS
+setenv BLAS_DIR {$BLAS_DIR}
+
+#LAPACK
+setenv LAPACK_DIR {$LAPACK_DIR}
+
+#SCALAPACK
+setenv SCALAPACK_DIR {$SCALAPACK_DIR}
+
+#PLAPACK
+setenv PLAPACK_DIR {$PLAPACK_DIR}
+
+#BLACS
+setenv BLACS_DIR {$BLACS_DIR}
+
+#YAMS
+setenv YAMS_DIR {$YAMS_DIR}
+setenv PATH {$PATH}:{$YAMS_DIR}
+
+#TEX2IM
+setenv TEX2IM_DIR {$TEX2IM_DIR}
+setenv PATH {$PATH}:{$TEX2IM_DIR}
+
+#SOWING
+setenv SOWING_DIR {$SOWING_DIR}
+setenv PATH {$PATH}:{$SOWING_DIR}/bin
+setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$SOWING_DIR}/lib
+setenv MANPATH {$MANPATH}:{$SOWING_DIR}/man
+
+#Chaco
+setenv CHACO_DIR {$CHACO_DIR}
+setenv PATH {$PATH}:{$CHACO_DIR}
+
+#MeshPart
+setenv MESHPART_DIR {$MESHPART_DIR}
+setenv PATH {$PATH}:{$MESHPART_DIR}
+
+#SCOTCH
+setenv SCOTCH_DIR {$SCOTCH_DIR}
+setenv PATH {$PATH}:{$SCOTCH_DIR}
+setenv MANPATH {$MANPATH}:{$SCOTCH_DIR}/man
+
+#AUTOCONF
+setenv AUTOCONF_DIR {$AUTOCONF_DIR}
+setenv PATH {$PATH}:{$AUTOCONF_DIR}/bin
+
+#AUTOMAKE
+setenv AUTOMAKE_DIR {$AUTOMAKE_DIR}
+setenv PATH {$PATH}:{$AUTOMAKE_DIR}/bin
+
+#BORLAND
+setenv BORLAND_DIR {$BORLAND_DIR}
+setenv PATH {$PATH}:{$BORLAND_DIR}/Bin
+
+#SSH
+setenv SSH_DIR {$SSH_DIR}
+setenv PATH {$PATH}:{$SSH_DIR}
+
+#VALGRIND
+setenv VALGRIND_DIR {$VALGRIND_DIR}
+setenv PATH {$PATH}:{$VALGRIND_DIR}
Index: /issm/trunk-jpl-damage/etc/environment.sh
===================================================================
--- /issm/trunk-jpl-damage/etc/environment.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/etc/environment.sh	(revision 11330)
@@ -0,0 +1,225 @@
+#ISSM_TIER and ISSM_ARCH should have been defined already in your shell settings file (.bashrc, .cshrc, etc ...)
+source $ISSM_TIER/etc/environment_variables.sh
+
+#Do we have any command line arguments? (such as MATLAB_DIR=otherdirthandefault), source them before exporting the variables 
+#to environment.
+for i in $@
+do
+	eval $i
+done
+
+#CRON utilities
+PATH="$PATH:$ISSM_TIER/cron"
+
+#scripts
+PATH="$PATH:$ISSM_TIER/scripts"
+
+##MATLAB
+export MATLAB_DIR
+PATH="$MATLAB_DIR/bin:$PATH" #take precedence over /usr/local/bin/matlab
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$MATLAB_DIR/lib"
+export LD_RUN_PATH="$LD_RUN_PATH:$MATLAB_DIR/lib"
+#export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$MATLAB_DIR/bin/glnxa64"
+#export LD_RUN_PATH="$LD_RUN_PATH:$MATLAB_DIR/bin/glnxa64"
+
+#MPI
+export MPI_DIR
+PATH="$MPI_DIR/bin:$PATH"
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$MPI_DIR/lib"
+export LD_RUN_PATH="$LD_RUN_PATH:$MPI_DIR/lib"
+export MANPATH="$MANPATH:$MPI_DIR/man"
+export MPIRUN_NPROCS=24
+
+#PETSC
+export PETSC_DIR
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$PETSC_DIR/lib/$ISSM_ARCH"
+export LD_RUN_PATH="$LD_RUN_PATH:$PETSC_DIR/lib/$ISSM_ARCH"
+
+#SLEPC
+export SLEPC_DIR
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$SLEPC_DIR/lib/$ISSM_ARCH"
+export LD_RUN_PATH="$LD_RUN_PATH:$SLEPC_DIR/lib/$ISSM_ARCH"
+
+#Dakota
+export DAKOTA_DIR
+PATH="$PATH:$DAKOTA_DIR/bin"
+export MANPATH="$MANPATH:$MPI_DIR/man:$DAKOTA_DIR/docs/man:$DAKOTA_DIR/docs/man-ref"
+
+#Qhull
+export QHULL_DIR
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$QHULL_DIR/lib"
+export LD_RUN_PATH="$LD_RUN_PATH:$QHULL_DIR/lib"
+
+#Doxygen
+export DOXYGEN_DIR
+MANPATH="$MANPATH:$DOXYGEN_DIR/man"
+PATH="$PATH:$DOXYGEN_DIR/bin"
+
+#MTOC
+export MTOC_DIR
+PATH="$PATH:$MTOC_DIR"
+
+#TRIANGLE
+export TRIANGLE_DIR
+
+#METIS
+export METIS_DIR
+	
+#BLAS
+export BLAS_DIR
+
+#LAPACK
+export LAPACK_DIR
+
+#SCALAPACK
+export SCALAPACK_DIR
+
+#PLAPACK
+export PLAPACK_DIR
+
+#BLACS
+export BLACS_DIR
+
+#YAMS
+export YAMS_DIR
+PATH="$PATH:$YAMS_DIR"
+
+#BAMG
+export BAMG_DIR
+PATH="$PATH:$BAMG_DIR"
+
+#TEX2IM
+export TEX2IM_DIR
+PATH="$PATH:$TEX2IM_DIR"
+
+#SOWING
+export SOWING_DIR
+PATH="$PATH:$SOWING_DIR/bin"
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$SOWING_DIR/lib"
+export LD_RUN_PATH="$LD_RUN_PATH:$SOWING_DIR/lib"
+export MANPATH="$MANPATH:$SOWING_DIR/man"
+
+#Chaco
+export CHACO_DIR
+PATH="$PATH:$CHACO_DIR"
+
+#MeshPart
+export MESHPART_DIR
+PATH="$PATH:$MESHPART_DIR"
+
+#SCOTCH
+export SCOTCH_DIR
+PATH="$PATH:$SCOTCH_DIR"
+export MANPATH="$MANPATH:$SCOTCH_DIR/man"
+
+#AUTOCONF
+export AUTOCONF_DIR
+PATH="$AUTOCONF_DIR/bin:$PATH"
+
+#AUTOMAKE
+export AUTOMAKE_DIR
+PATH="$AUTOMAKE_DIR/bin:$PATH"
+
+export LIBTOOL_DIR
+PATH="$LIBTOOL_DIR/bin:$PATH"
+
+#BORLAND
+export BORLAND_DIR
+PATH="$PATH:$BORLAND_DIR/Bin"
+
+#INTEL
+#export INTEL_DIR
+#PATH="$PATH:$INTEL_DIR"
+#source $ISSM_TIER/externalpackages/intel/intel.sh
+
+#SDK
+export SDK_DIR
+PATH="$PATH:$SDK_DIR"
+
+#SSH
+export SSH_DIR
+PATH="$PATH:$SSH_DIR"
+
+#VALGRIND
+export VALGRIND_DIR
+PATH="$PATH:$VALGRIND_DIR"
+
+#GRAPHVIZ
+export GRAPHVIZ_DIR
+PATH="$PATH:$GRAPHVIZ_DIR"
+
+#CPPCHECK
+export CPPCHECK_DIR
+PATH="$PATH:$CPPCHECK_DIR"
+
+#GDAL
+export GDAL_DIR
+PATH="$GDAL_DIR/bin:$PATH"
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$GDAL_DIR/lib"
+
+#MERCURIAL
+export PYTHONPATH="$PYTHONPATH:$MERCURIAL_DIR/mercurial/pure/"
+export PATH="$PATH:$MERCURIAL_DIR/"
+
+#BOOST
+export BOOSTROOT
+export BOOST_DIR
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$BOOST_DIR/lib"
+export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$BOOST_DIR/lib"
+
+#XERCES
+export XERCESROOT 
+export XERCESCROOT
+
+#xaifBooster
+export XAIFBOOSTERROOT
+export XAIFBOOSTER_HOME
+export XAIF_DIR
+export PLATFORM
+
+#angel
+export ANGELROOT
+
+#openanalysis
+export OPENANALYSISROOT
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$OPENANALYSISROOT/lib"
+
+#JAVA
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$JVM_DIR"
+
+#BBFTP
+export PATH="$PATH:$BBFTP_DIR/bin"
+
+#ADIC
+export PATH="$PATH:$ADIC_DIR/bin"
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$ADIC_DIR/lib"
+export LD_RUN_PATH="$LD_RUN_PATH:$ADIC_DIR/lib"
+
+#COLPACK
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$COLPACK_DIR/lib"
+export LD_RUN_PATH="$LD_RUN_PATH:$COLPACK_DIR/lib"
+
+#ECLIPSE
+export PATH="$PATH:$ECLIPSE_DIR"
+
+#FLAIM
+export FLAIM_DIR
+
+#APPSCAN
+export PATH="$PATH:$APPSCAN_DIR/install/bin"
+export PATH="$PATH:$APPSCAN_DIR/bin"]
+
+#CPPCHECK
+export PATH="$PATH:$CPPCHECK_DIR/bin"
+
+#RATS
+export PATH="$PATH:$RATS_DIR/bin"
+
+#DYSON
+export PATH="$PATH:$DYSON_DIR"
+
+#CMAKE
+export PATH="$PATH:$CMAKE_DIR/bin"
+
+#SHAPELIB
+export PATH="$PATH:$SHAPELIB_DIR/exec"
Index: /issm/trunk-jpl-damage/etc/environment_variables.csh
===================================================================
--- /issm/trunk-jpl-damage/etc/environment_variables.csh	(revision 11330)
+++ /issm/trunk-jpl-damage/etc/environment_variables.csh	(revision 11330)
@@ -0,0 +1,84 @@
+#
+#
+#This routine can only be run if the ISSM_TIER variable has been correctly set!
+#
+#
+
+#MATLAB
+set MATLAB_DIR={$ISSM_TIER}/externalpackages/matlab/install
+
+#MPI
+set MPI_DIR={$ISSM_TIER}/externalpackages/mpich2/install
+
+#PETSC
+set PETSC_DIR={$ISSM_TIER}/externalpackages/petsc/install
+
+#SLEPC
+set SLEPC_DIR={$ISSM_TIER}/externalpackages/slepc/install
+
+#Dakota
+set DAKOTA_DIR={$ISSM_TIER}/externalpackages/dakota/install
+
+#Qhull
+set QHULL_DIR={$ISSM_TIER}/externalpackages/qhull/install
+
+#Doxygen
+set DOXYGEN_DIR={$ISSM_TIER}/externalpackages/doxygen/install
+
+#MTOC
+set MTOC_DIR={$ISSM_TIER}/externalpackages/mtoc/install
+
+#Triangle
+set TRIANGLE_DIR={$ISSM_TIER}/externalpackages/triangle/install
+
+#METIS
+set METIS_DIR={$ISSM_TIER}/externalpackages/metis/install
+
+#BLAS
+set BLAS_DIR={$ISSM_TIER}/externalpackages/petsc/install/externalexternalpackages/fblaslapack
+
+#LAPACK
+set LAPACK_DIR={$ISSM_TIER}/externalpackages/petsc/install/externalexternalpackages/fblaslapack/$ISSM_ARCH
+
+#SCALAPACK
+set SCALAPACK_DIR={$ISSM_TIER}/externalpackages/petsc/install/externalexternalpackages/SCALAPACK/$ISSM_ARCH
+
+#PLAPACK
+set PLAPACK_DIR={$ISSM_TIER}/externalpackages/petsc/install/externalexternalpackages/PLAPACKR32
+
+#BLACS
+set BLACS_DIR={$ISSM_TIER}/externalpackages/petsc/install/externalexternalpackages/blacs-dev/$ISSM_ARCH
+
+#sowing
+set SOWING_DIR={$ISSM_TIER}/externalpackages/sowing/install
+
+#YAMS
+set YAMS_DIR={$ISSM_TIER}/externalpackages/yams/install
+
+#TEX2IM
+set TEX2IM_DIR={$ISSM_TIER}/externalpackages/tex2im/install
+
+#Chaco
+set CHACO_DIR={$ISSM_TIER}/externalpackages/chaco/install
+
+#MeshPart
+set MESHPART_DIR={$ISSM_TIER}/externalpackages/meshpart/install
+
+#SCOTCH
+set SCOTCH_DIR={$ISSM_TIER}/externalpackages/scotch/install
+
+#Development packages
+#automake
+set AUTOMAKE_DIR={$ISSM_TIER}/externalpackages/automake/install
+
+#autoconf
+set AUTOCONF_DIR={$ISSM_TIER}/externalpackages/autoconf/install
+
+#borland
+set BORLAND_DIR=/cygdrive/c/Borland
+
+#ssh
+set SSH_DIR={$ISSM_TIER}/externalpackages/ssh
+
+#valgrind
+set VALGRIND_DIR={$ISSM_TIER}/externalpackages/valgrind/install/bin
Index: /issm/trunk-jpl-damage/etc/environment_variables.sh
===================================================================
--- /issm/trunk-jpl-damage/etc/environment_variables.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/etc/environment_variables.sh	(revision 11330)
@@ -0,0 +1,167 @@
+#
+#
+#This routine can only be run if the ISSM_TIER variable has been correctly set!
+#
+#
+
+#MATLAB
+MATLAB_DIR="$ISSM_TIER/externalpackages/matlab/install"
+
+#MPI
+MPI_DIR="$ISSM_TIER/externalpackages/mpich2/install"
+
+#PETSC
+PETSC_DIR="$ISSM_TIER/externalpackages/petsc/install"
+
+#SLEPC
+SLEPC_DIR="$ISSM_TIER/externalpackages/slepc/install"
+
+#Dakota
+DAKOTA_DIR="$ISSM_TIER/externalpackages/dakota/install"
+
+#Qhull
+QHULL_DIR="$ISSM_TIER/externalpackages/qhull/install"
+
+#Doxygen
+DOXYGEN_DIR="$ISSM_TIER/externalpackages/doxygen/install"
+
+#MTOC
+MTOC_DIR="$ISSM_TIER/externalpackages/mtoc/install"
+
+#Triangle
+TRIANGLE_DIR="$ISSM_TIER/externalpackages/triangle/install"
+
+#METIS
+METIS_DIR="$ISSM_TIER/externalpackages/metis/install"
+
+#BLAS
+BLAS_DIR="$ISSM_TIER/externalpackages/petsc/install/externalpackages/fblaslapack"
+
+#LAPACK
+LAPACK_DIR="$ISSM_TIER/externalpackages/petsc/install/externalpackages/fblaslapack/$ISSM_ARCH"
+
+#SCALAPACK
+SCALAPACK_DIR="$ISSM_TIER/externalpackages/petsc/install/externalpackages/SCALAPACK/$ISSM_ARCH"
+
+#PLAPACK
+PLAPACK_DIR="$ISSM_TIER/externalpackages/petsc/install/externalpackages/PLAPACKR32"
+
+#BLACS
+BLACS_DIR="$ISSM_TIER/externalpackages/petsc/install/externalpackages/blacs-dev/$ISSM_ARCH"
+
+#sowing
+SOWING_DIR="$ISSM_TIER/externalpackages/sowing/install"
+
+#BLACS
+BLACS_DIR="$ISSM_TIER/externalpackages/petsc/install/externalpackages/blacs-dev/$ISSM_ARCH"
+
+#YAMS
+YAMS_DIR="$ISSM_TIER/externalpackages/yams/install"
+
+#BAMG
+BAMG_DIR="$ISSM_TIER/externalpackages/bamg/install"
+
+#Chaco
+CHACO_DIR="$ISSM_TIER/externalpackages/chaco/install"
+
+#MeshPart
+MESHPART_DIR="$ISSM_TIER/externalpackages/meshpart/install"
+
+#SCOTCH
+SCOTCH_DIR="$ISSM_TIER/externalpackages/scotch/install"
+
+#Development packages
+#automake
+AUTOMAKE_DIR="$ISSM_TIER/externalpackages/automake/install"
+
+#libtool
+LIBTOOL_DIR="$ISSM_TIER/externalpackages/libtool/install"
+
+#autoconf
+AUTOCONF_DIR="$ISSM_TIER/externalpackages/autoconf/install"
+
+#borland
+#BORLAND_DIR="/cygdrive/c/Borland/"
+
+#intel
+#INTEL_DIR="C:/IntelInstall/Compiler/11.1/038/bin/ia32/"
+
+#TEX2IM			 
+TEX2IM_DIR="$ISSM_TIER/externalpackages/tex2im/install" 
+
+#sdk
+#SDK_DIR="C:/MicrosoftVisualStudio 9.0/Microsoft Visual C++ 2008 Express Edition with SP1 - ENU"
+
+#ssh 
+SSH_DIR="$ISSM_TIER/externalpackages/ssh"
+
+#valgrind
+VALGRIND_DIR="$ISSM_TIER/externalpackages/valgrind/install/bin"
+
+#graphviz
+GRAPHVIZ_DIR="$ISSM_TIER/externalpackages/graphviz/install/bin"
+
+#cppcheck
+CPPCHECK_DIR="$ISSM_TIER/externalpackages/cppcheck/install"
+
+#gdal
+GDAL_DIR="$ISSM_TIER/externalpackages/gdal/install"
+
+#mercurial
+MERCURIAL_DIR="$ISSM_TIER/externalpackages/mercurial/install"
+
+#boost
+BOOST_DIR="$ISSM_TIER/externalpackages/boost/install"
+BOOSTROOT="$ISSM_TIER/externalpackages/boost/install"
+
+#OpenAnalysis
+OPENANALYSISROOT="$ISSM_TIER/externalpackages/openanalysis/install"
+
+#xerces
+XERCESROOT="$ISSM_TIER/externalpackages/xerces/install"
+XERCESCROOT="$ISSM_TIER/externalpackages/xerces/src"
+
+#xaifBooster
+XAIFBOOSTERROOT="$ISSM_TIER/externalpackages/xaifbooster/"
+XAIF_DIR="$ISSM_TIER/externalpackages/xaifbooster/xaifBooster"
+XAIFBOOSTER_HOME="$ISSM_TIER/externalpackages/xaifbooster/xaifBooster"
+PLATFORM=x86-Linux
+
+#angel
+ANGELROOT="$ISSM_TIER/externalpackages/angel/angel"
+
+#java
+JVM_DIR=/usr/local/gcc/4.3.2/lib64/gcj-4.3.2-9/
+
+#bbftp
+BBFTP_DIR="$ISSM_TIER/externalpackages/bbftp/install"
+
+#adic2
+ADIC_DIR="$ISSM_TIER/externalpackages/adic/install"
+
+#colpack
+COLPACK_DIR="$ISSM_TIER/externalpackages/colpack/install"
+
+#eclipse
+ECLIPSE_DIR="$ISSM_TIER/externalpackages/eclipse/install"
+
+#flaim
+FLAIM_DIR="$ISSM_TIER/externalpackages/flaim/install"
+
+#appscan
+APPSCAN_DIR="$ISSM_TIER/externalpackages/appscan"
+
+#cppcheck
+CPPCHECK_DIR="$ISSM_TIER/externalpackages/cppcheck/install"
+
+#rats
+RATS_DIR="$ISSM_TIER/externalpackages/rats/install"
+
+#dyson
+DYSON_DIR="$ISSM_TIER/externalpackages/dyson/"
+
+#cmake
+CMAKE_DIR="$ISSM_TIER/externalpackages/cmake/install"
+
+#shapelib
+SHAPELIB_DIR="$ISSM_TIER/externalpackages/shapelib/install"
Index: /issm/trunk-jpl-damage/examples/SquareIceShelf/DomainOutline.exp
===================================================================
--- /issm/trunk-jpl-damage/examples/SquareIceShelf/DomainOutline.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/examples/SquareIceShelf/DomainOutline.exp	(revision 11330)
@@ -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/trunk-jpl-damage/examples/SquareIceShelf/Front.exp
===================================================================
--- /issm/trunk-jpl-damage/examples/SquareIceShelf/Front.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/examples/SquareIceShelf/Front.exp	(revision 11330)
@@ -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/trunk-jpl-damage/examples/SquareIceShelf/README
===================================================================
--- /issm/trunk-jpl-damage/examples/SquareIceShelf/README	(revision 11330)
+++ /issm/trunk-jpl-damage/examples/SquareIceShelf/README	(revision 11330)
@@ -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/trunk-jpl-damage/examples/SquareIceShelf/Square.par
===================================================================
--- /issm/trunk-jpl-damage/examples/SquareIceShelf/Square.par	(revision 11330)
+++ /issm/trunk-jpl-damage/examples/SquareIceShelf/Square.par	(revision 11330)
@@ -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.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+disp('      creating drag');
+pos=find(md.mask.vertexonfloatingice);
+md.friction.coefficient=200*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(pos)=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);
+
+disp('      creating boundary conditions');
+md=SetIceShelfBC(md,'Front.exp');
Index: /issm/trunk-jpl-damage/examples/SquareIceShelf/runme.m
===================================================================
--- /issm/trunk-jpl-damage/examples/SquareIceShelf/runme.m	(revision 11330)
+++ /issm/trunk-jpl-damage/examples/SquareIceShelf/runme.m	(revision 11330)
@@ -0,0 +1,6 @@
+md=model;
+md=triangle(md,'DomainOutline.exp',100000);
+md=setmask(md,'all','');
+md=parameterize(md,'Square.par');
+md=setflowequation(md,'macayeal','all');
+md=solve(md,DiagnosticSolutionEnum);
Index: /issm/trunk-jpl-damage/externalpackages/README
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/README	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/README	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/adic/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/adic/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/adic/install.sh	(revision 11330)
@@ -0,0 +1,33 @@
+#!/bin/bash
+
+#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_TIER/externalpackages/rose/install \
+	--with-openanalysis=$ISSM_TIER/externalpackages/openanalysis/openanalysis/x86_64-Linux \
+	--with-boost=$ISSM_TIER/externalpackages/boost/install \
+	--with-xerces=$ISSM_TIER/externalpackages/xerces/src \
+	--with-xaifbooster=$ISSM_TIER/externalpackages/xaifbooster/xaifBooster \
+	--with-colpack=$ISSM_TIER/externalpackages/colpack/install\
+	--prefix=$ISSM_TIER/externalpackages/adic/install 
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk-jpl-damage/externalpackages/adic/tests/notes
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/adic/tests/notes	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/adic/tests/notes	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/adolc/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/adolc/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/adolc/install.sh	(revision 11330)
@@ -0,0 +1,28 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install ADOL-C-2.2.0 src
+
+#Create install directories
+mkdir install src
+
+#Untar 
+tar -zxvf  ADOL-C-2.2.0.tar.gz
+
+#Move ADOL-C into install directory
+mv ADOL-C-2.2.0/* src
+rm -rf ADOL-C-2.2.0
+
+#Compile ADOL-C
+cd src 
+./configure \
+	--prefix=$ISSM_TIER/externalpackages/adolc/install \
+	--enable-sparse \
+	--enable-docexa \
+	--enable-addexa          
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk-jpl-damage/externalpackages/angel/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/angel/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/angel/install.sh	(revision 11330)
@@ -0,0 +1,11 @@
+#!/bin/bash
+
+#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/trunk-jpl-damage/externalpackages/appscan/bin/genouncemakePFile.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/appscan/bin/genouncemakePFile.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/appscan/bin/genouncemakePFile.sh	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/appscan/hostname
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/appscan/hostname	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/appscan/hostname	(revision 11330)
@@ -0,0 +1,1 @@
+jplsec-codescan.jpl.nasa.gov
Index: /issm/trunk-jpl-damage/externalpackages/appscan/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/appscan/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/appscan/install.sh	(revision 11330)
@@ -0,0 +1,9 @@
+#!/bin/bash
+
+#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/trunk-jpl-damage/externalpackages/autoconf/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/autoconf/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/autoconf/install.sh	(revision 11330)
@@ -0,0 +1,19 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install autoconf-2.63 src
+
+#Create install directories
+mkdir install
+
+#Untar 
+tar -zxvf  autoconf-2.63.tar.gz
+
+#Move autoconf into src directory
+mv autoconf-2.63 src
+
+#Compile autoconf
+cd src 
+./configure --prefix="$ISSM_TIER/externalpackages/autoconf/install" 
+make  
+make install
Index: /issm/trunk-jpl-damage/externalpackages/automake/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/automake/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/automake/install.sh	(revision 11330)
@@ -0,0 +1,17 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install automake-1.10.2 src
+
+#Create install directories
+mkdir install
+
+#Untar 
+tar -zxvf  automake-1.10.2.tar.gz
+mv automake-1.10.2 src
+
+#Compile automake
+cd src 
+./configure --prefix="$ISSM_TIER/externalpackages/automake/install" 
+make  
+make install
Index: /issm/trunk-jpl-damage/externalpackages/bbftp/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/bbftp/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/bbftp/install.sh	(revision 11330)
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install bbftp-client-3.2.0
+
+#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_TIER/externalpackages/bbftp/install
+make
+make install
Index: /issm/trunk-jpl-damage/externalpackages/boost/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/boost/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/boost/install.sh	(revision 11330)
@@ -0,0 +1,24 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install boost_1_45_0 src
+mkdir install src
+
+#Untar 
+tar -zxvf  boost_1_45_0.tar.gz
+
+#Move boost into install directory
+mv boost_1_45_0/* src
+rm -rf boost_1_45_0
+
+#Configure and compile
+cd src 
+./bootstrap.sh --prefix=$ISSM_TIER/externalpackages/boost/install
+
+#Compile boost
+if [ -z $1 ];
+then
+	./bjam install
+else
+	./bjam -j $1 install
+fi
Index: /issm/trunk-jpl-damage/externalpackages/canos/InterX.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/canos/InterX.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/canos/InterX.m	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/canos/license.txt
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/canos/license.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/canos/license.txt	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/canos/licenseNS.txt
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/canos/licenseNS.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/canos/licenseNS.txt	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/canos/selfintersect.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/canos/selfintersect.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/canos/selfintersect.m	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/chaco/chaco.h
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/chaco.h	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/chaco.h	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/chaco/chaco.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/chaco.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/chaco.patch	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/chaco/chaco_README.txt
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/chaco_README.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/chaco_README.txt	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/chaco/chaco_jes_notes.txt
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/chaco_jes_notes.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/chaco_jes_notes.txt	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/chaco/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/install.sh	(revision 11330)
@@ -0,0 +1,46 @@
+#!/bin/bash
+
+# Some cleanup
+rm -rf Chaco-2.2
+rm -rf src 
+rm -rf install 
+mkdir src install 
+
+# 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 [ -z $1 ]; 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/trunk-jpl-damage/externalpackages/chaco/mex/Chaco.c
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/mex/Chaco.c	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/mex/Chaco.c	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/chaco/mex/Chaco_m.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/mex/Chaco_m.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/mex/Chaco_m.m	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/chaco/mex/Chacox.c
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/mex/Chacox.c	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/mex/Chacox.c	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/chaco/mex/Makefile
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/mex/Makefile	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/mex/Makefile	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/chaco/mex/User_Params.debug
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/mex/User_Params.debug	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/mex/User_Params.debug	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/chaco/mex/User_Params.verbose
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/mex/User_Params.verbose	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/mex/User_Params.verbose	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/chaco/mex/user_params.c
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/mex/user_params.c	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/mex/user_params.c	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/chaco/mlchaco_README.txt
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/mlchaco_README.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/mlchaco_README.txt	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/chaco/mlchaco_jes_notes.txt
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/chaco/mlchaco_jes_notes.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/chaco/mlchaco_jes_notes.txt	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/cmake/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/cmake/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/cmake/install.sh	(revision 11330)
@@ -0,0 +1,22 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install cmake-2.8.5
+mkdir install
+
+#Untar 
+tar -zxvf  cmake-2.8.5.tar.gz
+
+#Move cmake into install directory
+mv cmake-2.8.5/* install
+rm -rf cmake-2.8.5
+
+#Compile cmake
+cd install 
+./bootstrap --prefix=$ISSM_TIER/externalpackages/cmake/install
+if [ -z $1 ]; then
+	make
+else 
+	make -j $1; 
+fi
+make install
Index: /issm/trunk-jpl-damage/externalpackages/colpack/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/colpack/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/colpack/install.sh	(revision 11330)
@@ -0,0 +1,22 @@
+#!/bin/bash
+
+#Erase install
+rm -rf install  src ColPack
+
+#install directory
+mkdir src
+tar -zxvf ColPack-1.0.3.tar.gz 
+mv ColPack/* src
+rm -rf ColPack
+
+#compile
+cd src
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+cd ..
+
+#install
+ln -s src/build ./install
Index: /issm/trunk-jpl-damage/externalpackages/cppcheck/README
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/cppcheck/README	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/cppcheck/README	(revision 11330)
@@ -0,0 +1,2 @@
+Cppcheck: static analysis of source code.
+Obtained code from http://sourceforge.net/projects/cppcheck/
Index: /issm/trunk-jpl-damage/externalpackages/cppcheck/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/cppcheck/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/cppcheck/install.sh	(revision 11330)
@@ -0,0 +1,20 @@
+#!/bin/bash
+
+#Erase install
+rm -rf install  src cppcheck-1.48
+mkdir src
+
+tar -xvf cppcheck-1.48.tar
+
+mv cppcheck-1.48/* src
+rm -rf cppcheck-1.48
+
+#compile
+cd src
+if [ -z $1 ]; then
+	make 
+else 
+	make -j $1
+fi  
+make install PREFIX=$ISSM_TIER/externalpackages/cppcheck/install
+cd ..
Index: /issm/trunk-jpl-damage/externalpackages/dace/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dace/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dace/install.sh	(revision 11330)
@@ -0,0 +1,12 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install dace
+mkdir install
+
+#uncompress
+unzip dace.zip
+
+#move to install directory
+mv dace/* install
+rm -rf dace
Index: /issm/trunk-jpl-damage/externalpackages/dakota/LHSDriver.cpp.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dakota/LHSDriver.cpp.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dakota/LHSDriver.cpp.patch	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/dakota/NIDRProblemDescDB.C.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dakota/NIDRProblemDescDB.C.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dakota/NIDRProblemDescDB.C.patch	(revision 11330)
@@ -0,0 +1,4 @@
+95a96,98
+>   
+>   //close the input file
+>   fclose(nidrin);
Index: /issm/trunk-jpl-damage/externalpackages/dakota/NonDLocalReliability.C.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dakota/NonDLocalReliability.C.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dakota/NonDLocalReliability.C.patch	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/dakota/NonDSampling.C.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dakota/NonDSampling.C.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dakota/NonDSampling.C.patch	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/dakota/NonDUnilevelRBDO.C.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dakota/NonDUnilevelRBDO.C.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dakota/NonDUnilevelRBDO.C.patch	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/dakota/ParallelLibrary.C.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dakota/ParallelLibrary.C.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dakota/ParallelLibrary.C.patch	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/dakota/ParallelLibrary.H.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dakota/ParallelLibrary.H.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dakota/ParallelLibrary.H.patch	(revision 11330)
@@ -0,0 +1,3 @@
+346a347,348
+>   /// library mode constructor, serial mode
+>   ParallelLibrary(char*  serial_mode);
Index: /issm/trunk-jpl-damage/externalpackages/dakota/README
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dakota/README	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dakota/README	(revision 11330)
@@ -0,0 +1,9 @@
+version 4.3 of dakota is not yet released. The 4.3 version 
+here refers to the VOTD release on May 12th 2009. While waiting 
+for 4.3, we consider the develpment version to be 4.3.
+4.2 is replaced by 4.3, to handle fnEvalId extra arguemnt to the Dakota 
+structure.
+
+Be sure to set FC and F77 variable names to point to your fortran compiler, otherwise, 
+	the LHS packages will pick up gfortran as its fortran compiler, which can create serious 
+	troubles.
Index: /issm/trunk-jpl-damage/externalpackages/dakota/install-altix64-cosmos.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dakota/install-altix64-cosmos.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dakota/install-altix64-cosmos.sh	(revision 11330)
@@ -0,0 +1,96 @@
+#!/bin/bash
+
+#Get number of cpus
+NUMCPUS=$1;
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf install 
+mkdir src install 
+
+#Untar 
+tar -zxvf  Dakota_4_3.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C ./ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H ./ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C ./NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C ./NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C ./NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C ./NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp ./LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \ 
+	--prefix="$ISSM_TIER/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 [ -z $NUMCPUS ];
+then
+	make
+	make install
+else
+	make -j $NUMCPUS
+	make -j $NUMCPUS install
+fi
+cd ..
+
+#Weird behaviour of Dakota: libamplsolver.a and amplsolver.a are not the same thing!
+cd install/lib
+mv libamplsolver.a libamplsolver.a.bak
+ln -s ../../src/packages/ampl/amplsolver.a ./libamplsolver.a
Index: /issm/trunk-jpl-damage/externalpackages/dakota/install-linux64-astrid.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dakota/install-linux64-astrid.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dakota/install-linux64-astrid.sh	(revision 11330)
@@ -0,0 +1,96 @@
+#!/bin/bash
+
+#Get number of cpus
+NUMCPUS=$1;
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf install 
+mkdir src install 
+
+#Untar 
+tar -zxvf  Dakota_4_3.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C ./ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H ./ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C ./NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C ./NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C ./NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C ./NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp ./LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \
+	--prefix="$ISSM_TIER/externalpackages/dakota/install" \
+	--without-graphics  \
+	--with-pic \
+	--disable-mpi \
+	--with-blas=/usr/lib64/libblas.so.3.0.3 \
+	--with-lapack=/usr/lib64/liblapack.so.3.0.3
+cd ..
+
+#Before compiling, if running on 64 bits, we need to active fPIC compilation. Some packages 
+#do not register -fPIC in Dakota, which is a problem. Edit the faulty Makefiles and add the -fPIC 
+#flag to the compilation.
+cat ./src/methods/NCSUOpt/Makefile | sed 's/FFLAGS = -g -O2/FFLAGS = -g -O2 -fPIC/g' >  temp
+mv temp ./src/methods/NCSUOpt/Makefile
+
+cat ./src/methods/acro/packages/pebbl/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/pebbl/src/Makefile
+
+cat ./src/methods/hopspack/src-nappspack/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp ./src/methods/hopspack/src-nappspack/Makefile
+
+cat ./src/methods/hopspack/src-cddlib/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-cddlib/Makefile 
+
+cat ./src/methods/hopspack/src-shared/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-shared/Makefile 
+
+cat ./src/methods/hopspack/src-shared/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-shared/Makefile 
+
+cat ./src/methods/hopspack/src-conveyor/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-conveyor/Makefile 
+
+cat ./src/methods/hopspack/src-appspack/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp ./src/methods/hopspack/src-appspack/Makefile 
+
+cat ./src/methods/acro/packages/colin/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/colin/src/Makefile
+
+cat ./src/methods/acro/packages/coliny/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/coliny/src/Makefile
+
+cat ./src/methods/acro/packages/tpl/3po/Makefile | sed 's/CFLAGS = -O2/CFLAGS = -O2 -fPIC/g' > temp
+mv temp  ./src/methods/acro/packages/tpl/3po/Makefile 
+
+cat ./src/methods/acro/packages/tpl/3po/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp  ./src/methods/acro/packages/tpl/3po/Makefile 
+
+cat ./src/packages/ampl/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/packages/ampl/Makefile 
+
+#Compile and install dakota
+cd src 
+if [ -z $NUMCPUS ];
+then
+	make
+	make install
+else
+	make -j $NUMCPUS
+	make -j $NUMCPUS install
+fi
+cd ..
+
+#Weird behaviour of Dakota: libamplsolver.a and amplsolver.a are not the same thing!
+cd install/lib
+mv libamplsolver.a libamplsolver.a.bak
+ln -s ../../src/packages/ampl/amplsolver.a ./libamplsolver.a
Index: /issm/trunk-jpl-damage/externalpackages/dakota/install-macosx64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dakota/install-macosx64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dakota/install-macosx64.sh	(revision 11330)
@@ -0,0 +1,94 @@
+#!/bin/bash
+
+#Get number of cpus
+NUMCPUS=$1;
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf install 
+mkdir src install 
+
+#Untar 
+tar -zxvf  Dakota_4_3.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C ./ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H ./ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C ./NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C ./NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C ./NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C ./NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp ./LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \ 
+	--prefix="$ISSM_TIER/externalpackages/dakota/install" \
+	--without-graphics  \
+	--with-pic \
+	--disable-mpi
+cd ..
+
+#Before compiling, if running on 64 bits, we need to active fPIC compilation. Some packages 
+#do not register -fPIC in Dakota, which is a problem. Edit the faulty Makefiles and add the -fPIC 
+#flag to the compilation.
+cat ./src/methods/NCSUOpt/Makefile | sed 's/FFLAGS = -g -O2/FFLAGS = -g -O2 -fPIC/g' >  temp
+mv temp ./src/methods/NCSUOpt/Makefile
+
+cat ./src/methods/acro/packages/pebbl/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/pebbl/src/Makefile
+
+cat ./src/methods/hopspack/src-nappspack/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp ./src/methods/hopspack/src-nappspack/Makefile
+
+cat ./src/methods/hopspack/src-cddlib/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-cddlib/Makefile 
+
+cat ./src/methods/hopspack/src-shared/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-shared/Makefile 
+
+cat ./src/methods/hopspack/src-shared/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-shared/Makefile 
+
+cat ./src/methods/hopspack/src-conveyor/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-conveyor/Makefile 
+
+cat ./src/methods/hopspack/src-appspack/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp ./src/methods/hopspack/src-appspack/Makefile 
+
+cat ./src/methods/acro/packages/colin/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/colin/src/Makefile
+
+cat ./src/methods/acro/packages/coliny/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/coliny/src/Makefile
+
+cat ./src/methods/acro/packages/tpl/3po/Makefile | sed 's/CFLAGS = -O2/CFLAGS = -O2 -fPIC/g' > temp
+mv temp  ./src/methods/acro/packages/tpl/3po/Makefile 
+
+cat ./src/methods/acro/packages/tpl/3po/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp  ./src/methods/acro/packages/tpl/3po/Makefile 
+
+cat ./src/packages/ampl/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/packages/ampl/Makefile 
+
+#Compile and install dakota
+cd src 
+if [ -z $NUMCPUS ];
+then
+	make
+	make install
+else
+	make -j $NUMCPUS
+	make -j $NUMCPUS install
+fi
+cd ..
+
+#Weird behaviour of Dakota: libamplsolver.a and amplsolver.a are not the same thing!
+cd install/lib
+mv libamplsolver.a libamplsolver.a.bak
+ln -s ../../src/packages/ampl/amplsolver.a ./libamplsolver.a
Index: /issm/trunk-jpl-damage/externalpackages/dakota/install-pleiades.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dakota/install-pleiades.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dakota/install-pleiades.sh	(revision 11330)
@@ -0,0 +1,96 @@
+#!/bin/bash
+
+#Get number of cpus
+NUMCPUS=$1;
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf install 
+mkdir src install 
+
+#Untar 
+tar -zxvf  Dakota_4_3.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C ./ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H ./ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C ./NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C ./NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C ./NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C ./NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp ./LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \ 
+	--prefix="$ISSM_TIER/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 [ -z $NUMCPUS ];
+then
+	make
+	make install
+else
+	make -j $NUMCPUS
+	make -j $NUMCPUS install
+fi
+cd ..
+
+#Weird behaviour of Dakota: libamplsolver.a and amplsolver.a are not the same thing!
+cd install/lib
+mv libamplsolver.a libamplsolver.a.bak
+ln -s ../../src/packages/ampl/amplsolver.a ./libamplsolver.a
Index: /issm/trunk-jpl-damage/externalpackages/doxygen/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/doxygen/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/doxygen/install.sh	(revision 11330)
@@ -0,0 +1,19 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install
+
+#Download latest version
+svn co https://doxygen.svn.sourceforge.net/svnroot/doxygen/trunk install
+
+#Configure doxygen
+cd install && ./configure --prefix "$ISSM_TIER/externalpackages/doxygen/install"
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+
+#Install doxygen
+make install
+make install_docs
Index: /issm/trunk-jpl-damage/externalpackages/dyson/ldap.pl
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dyson/ldap.pl	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dyson/ldap.pl	(revision 11330)
@@ -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=* filter $bn > $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/trunk-jpl-damage/externalpackages/dyson/readme.txt
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dyson/readme.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dyson/readme.txt	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/dyson/source_seek.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/dyson/source_seek.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/dyson/source_seek.sh	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/export_fig/eps2pdf.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/export_fig/eps2pdf.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/export_fig/eps2pdf.m	(revision 11330)
@@ -0,0 +1,104 @@
+%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-2010
+
+% 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.
+
+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 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
+
Index: /issm/trunk-jpl-damage/externalpackages/export_fig/export_fig.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/export_fig/export_fig.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/export_fig/export_fig.m	(revision 11330)
@@ -0,0 +1,720 @@
+%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(..., 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).
+%   handle - The handle of the figure or axes (can be an array of handles
+%            of several axes, but these must be in the same figure) to be
+%            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-2011
+
+% 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.
+
+function [im alpha] = export_fig(varargin)
+% Parse the input arguments
+[fig options] = parse_args(nargout, varargin{:});
+% Isolate the subplot, if it is one
+cls = strcmp(get(fig(1), 'Type'), 'axes');
+if cls
+    % Given handles of one or more axes, so isolate them from the rest
+    fig = isolate_axes(fig);
+else
+    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
+% 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', 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
+        % 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);
+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, ...
+                 '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 '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(fig, '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
Index: /issm/trunk-jpl-damage/externalpackages/export_fig/fix_lines.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/export_fig/fix_lines.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/export_fig/fix_lines.m	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/export_fig/ghostscript.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/export_fig/ghostscript.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/export_fig/ghostscript.m	(revision 11330)
@@ -0,0 +1,140 @@
+function varargout = ghostscript(cmd)
+%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.
+
+% 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'};
+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/trunk-jpl-damage/externalpackages/export_fig/isolate_axes.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/export_fig/isolate_axes.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/export_fig/isolate_axes.m	(revision 11330)
@@ -0,0 +1,122 @@
+%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 specified, and
+% also their associated legends and colorbars. The axes specified must all
+% be in the same figure, but they will generally only be a subset of the
+% axes in the figure.
+%
+% IN:
+%    ah - An array of axes 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
+
+% Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
+
+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, and are all in the same figure
+fh = ancestor(ah(1), 'figure');
+nAx = numel(ah);
+for a = 1:nAx
+    if ~strcmp(get(ah(a), 'Type'), 'axes')
+        error('All handles must be axes handles.');
+    end
+    if ~isequal(ancestor(ah(a), 'figure'), fh)
+        error('Axes must all come from the same figure.');
+    end
+end
+% Tag the axes 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 axes 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 axes 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 axes 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
+
+function fh = copyfig(fh)
+% 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/trunk-jpl-damage/externalpackages/export_fig/license.txt
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/export_fig/license.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/export_fig/license.txt	(revision 11330)
@@ -0,0 +1,24 @@
+Copyright (c) 2011, 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/trunk-jpl-damage/externalpackages/export_fig/pdf2eps.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/export_fig/pdf2eps.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/export_fig/pdf2eps.m	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/export_fig/pdftops.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/export_fig/pdftops.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/export_fig/pdftops.m	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/export_fig/print2array.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/export_fig/print2array.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/export_fig/print2array.m	(revision 11330)
@@ -0,0 +1,157 @@
+%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-2011
+
+% 5/9/2011 Set EraseModes to normal when using opengl or zbuffer renderers.
+% Thanks to Pawel Kocieniewski for reporting the issue.
+
+% 21/9/2011 Bug fix: unit8 -> uint8!
+% Thanks to Tobias Lamour for reporting the issue.
+
+% 14/11/2011 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.
+
+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
+        % Export to tiff using ghostscript
+        ghostscript(['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc -sOutputFile="' tmp_nam '" "' tmp_eps '"']);
+    catch
+        % Delete the intermediate file
+        delete(tmp_eps);
+        rethrow(lasterror);
+    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 = median([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_mode = get(fig, 'PaperPositionMode');
+    set(fig, 'PaperPositionMode', 'auto');
+    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_mode);
+    % 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
Index: /issm/trunk-jpl-damage/externalpackages/export_fig/print2eps.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/export_fig/print2eps.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/export_fig/print2eps.m	(revision 11330)
@@ -0,0 +1,71 @@
+%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, and improves the line style,
+% making dashed lines more like those on screen and giving grid lines their
+% own dotted style.
+%
+%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-2011
+
+% 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.
+
+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
+% Set paper size
+old_mode = get(fig, 'PaperPositionMode');
+set(fig, 'PaperPositionMode', 'auto');
+% 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_mode);
+% 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
Index: /issm/trunk-jpl-damage/externalpackages/export_fig/user_string.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/export_fig/user_string.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/export_fig/user_string.m	(revision 11330)
@@ -0,0 +1,84 @@
+%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
+
+% 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.
+
+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, 'w');
+    if fid == -1
+        string = false;
+        return
+    end
+    try
+        fwrite(fid, string, '*char');
+    catch
+        fclose(fid);
+        string = false;
+        return
+    end
+    fclose(fid);
+    string = true;
+else
+    % Get string
+    fid = fopen(string_name, 'r');
+    if fid == -1
+        string = '';
+        return
+    end
+    string = fread(fid, '*char')';
+    fclose(fid);
+end
+return
Index: /issm/trunk-jpl-damage/externalpackages/findbugs/README
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/findbugs/README	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/findbugs/README	(revision 11330)
@@ -0,0 +1,2 @@
+Fingbugs for Java programs. 
+Downloaded from http://findbugs.sourceforge.net/downloads.html
Index: /issm/trunk-jpl-damage/externalpackages/findbugs/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/findbugs/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/findbugs/install.sh	(revision 11330)
@@ -0,0 +1,10 @@
+#!/bin/bash
+
+#Erase install
+rm -rf install  findbugs-1.3.9
+mkdir install
+
+tar -zxvf findbugs-1.3.9.tar.gz 
+
+mv findbugs-1.3.9/* install
+rm -rf findbugs-1.3.9
Index: /issm/trunk-jpl-damage/externalpackages/flaim/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/flaim/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/flaim/install.sh	(revision 11330)
@@ -0,0 +1,7 @@
+#!/bin/bash
+
+#Erase symlink
+rm -rf install
+
+#symlink to flaim directory
+ln -s /home/jschierm/flaim/svn/trunk ./install
Index: /issm/trunk-jpl-damage/externalpackages/gdal/GDALmake.opt.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/gdal/GDALmake.opt.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/gdal/GDALmake.opt.patch	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/gdal/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/gdal/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/gdal/install.sh	(revision 11330)
@@ -0,0 +1,36 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf gdal-1.6.0
+mkdir src install
+
+#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_TIER/externalpackages/gdal/install" \
+	--without-python \
+	--with-netcdf=no \
+	--with-jasper=no \
+	--without-ld-shared \
+	--with-unix-stdio-64=no \
+	--with-expat-lib=/usr/lib64/libexpat.so
+
+#Patch GDALmake.opt
+patch GDALmake.opt ../GDALmake.opt.patch
+
+#Compile and install gdal
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk-jpl-damage/externalpackages/gfortran/README
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/gfortran/README	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/gfortran/README	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/googleearthtoolbox/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/googleearthtoolbox/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/googleearthtoolbox/install.sh	(revision 11330)
@@ -0,0 +1,7 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install  
+
+#Download code: 
+svn checkout http://googleearthtoolbox.googlecode.com/svn/trunk/ install
Index: /issm/trunk-jpl-damage/externalpackages/graphviz/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/graphviz/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/graphviz/install.sh	(revision 11330)
@@ -0,0 +1,27 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install src
+mkdir install src
+
+#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_TIER/externalpackages/graphviz/install"
+cd ..
+
+#Compile and install
+cd src
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+cd ..
Index: /issm/trunk-jpl-damage/externalpackages/intel/intel.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/intel/intel.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/intel/intel.sh	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/intel/readme
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/intel/readme	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/intel/readme	(revision 11330)
@@ -0,0 +1,42 @@
+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. 
Index: /issm/trunk-jpl-damage/externalpackages/latex2rtf/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/latex2rtf/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/latex2rtf/install.sh	(revision 11330)
@@ -0,0 +1,13 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf latex2rtf-2.0.0 cfg install
+
+#untar 
+tar -zxvf  latex2rtf-2.0.0.tar.gz
+mv latex2rtf-2.0.0 install
+
+#Compile
+cd install
+export PREFIX="$ISSM_TIER/externalpackages/latex2rtf/install/"
+make
Index: /issm/trunk-jpl-damage/externalpackages/libtool/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/libtool/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/libtool/install.sh	(revision 11330)
@@ -0,0 +1,17 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install libtool-2.2.6b src
+mkdir install
+
+#Untar 
+tar -zxvf  libtool-2.2.6b.tar.gz
+
+#Move libtool into src directory
+mv libtool-2.2.6b src
+
+#Compile libtool
+cd src 
+./configure --prefix="$ISSM_TIER/externalpackages/libtool/install" 
+make  
+make install
Index: /issm/trunk-jpl-damage/externalpackages/m2html/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/m2html/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/m2html/install.sh	(revision 11330)
@@ -0,0 +1,17 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install m2html
+mkdir install
+
+#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/trunk-jpl-damage/externalpackages/m2html/m2html.m.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/m2html/m2html.m.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/m2html/m2html.m.patch	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/matlab/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/matlab/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/matlab/install.sh	(revision 11330)
@@ -0,0 +1,15 @@
+#!/bin/bash
+
+#Erase symlink
+rm -rf install
+
+#Select or create a new simlink
+ln -s /usr/local/pkgs/matlab-7.6/ install
+#ln -s /usr/local/matlab704/ install
+#ln -s /usr/local/matlab711/ install
+ln -s /usr/local/matlab712/ install
+#ln -s /usr/local/pkgs/matlab-7.6/ install
+#ln -s /Applications/MATLAB_R2008a/ install
+#ln -s /Applications/MATLAB_R2009a.app/ install
+#ln -s /Applications/MATLAB_R2010a.app/ install
+#ln -s /Applications/MATLAB_R2011b.app/ install
Index: /issm/trunk-jpl-damage/externalpackages/mercurial/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mercurial/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mercurial/install.sh	(revision 11330)
@@ -0,0 +1,20 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install mercurial-1.7.3
+mkdir install
+
+#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/trunk-jpl-damage/externalpackages/merge/mergesort.c
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/merge/mergesort.c	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/merge/mergesort.c	(revision 11330)
@@ -0,0 +1,196 @@
+/******************************************************************************
+* FILE: mergesort.c
+* DESCRIPTION:  
+*   The master task distributes an array to the workers in chunks, zero pads for equal load balancing
+*   The workers sort and return to the master, which does a final merge
+******************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include <mpi.h>
+
+
+
+#define N 100000
+#define MASTER 0		/* taskid of first task */
+
+void showVector(int *v, int n, int id);
+int * merge(int *A, int asize, int *B, int bsize);
+void swap(int *v, int i, int j);
+void m_sort(int *A, int min, int max);
+
+double startT, stopT;
+
+double startTime;
+
+/*function to print a vector*/
+void showVector(int *v, int n, int id)
+{
+	int i;
+	printf("%d: ",id);
+	for(i=0;i<n;i++)
+		printf("%d ",v[i]);
+	putchar('\n');
+}
+
+/*function to merge vectors*/
+int * merge(int *A, int asize, int *B, int bsize) {
+	int ai, bi, ci, i;
+	int *C;
+	int csize = asize+bsize;
+
+	ai = 0;
+	bi = 0;
+	ci = 0;
+
+	/* printf("asize=%d bsize=%d\n", asize, bsize); */
+
+	C = (int *)malloc(csize*sizeof(int));	/*the array can be statically allocated too*/
+	while ((ai < asize) && (bi < bsize)) {
+		if (A[ai] <= B[bi]) {
+			C[ci] = A[ai];
+			ci++; ai++;
+		} else {
+			C[ci] = B[bi];
+			ci++; bi++;
+		}
+	}
+
+	if (ai >= asize)						/*if A is shorter*/
+		for (i = ci; i < csize; i++, bi++)
+			C[i] = B[bi];
+	else if (bi >= bsize)					/*if B is shorter*/
+		for (i = ci; i < csize; i++, ai++)
+			C[i] = A[ai];
+
+	for (i = 0; i < asize; i++)				
+		A[i] = C[i];
+	for (i = 0; i < bsize; i++)
+		B[i] = C[asize+i];
+
+	/* showVector(C, csize, 0); */
+	return C;
+}
+
+void swap(int *v, int i, int j)
+{
+	int t;
+	t = v[i];
+	v[i] = v[j];
+	v[j] = t;
+}
+
+void m_sort(int *A, int min, int max)
+{
+	int *C;		/* dummy, just to fit the function */
+	int mid = (min+max)/2;
+	int lowerCount = mid - min + 1;
+	int upperCount = max - mid;
+
+	/* If the range consists of a single element, it's already sorted */
+	if (max == min) {
+		return;
+	} else {
+		/* Otherwise, sort the first half */
+		m_sort(A, min, mid);
+		/* Now sort the second half */
+		m_sort(A, mid+1, max);
+		/* Now merge the two halves */
+		C = merge(A + min, lowerCount, A + mid + 1, upperCount);
+	}
+}
+
+main(int argc, char **argv)
+{
+	int * data;
+	int * chunk;
+	int * other;
+	int m,n=N;
+	int id,p;
+	int s = 0;
+	int i;
+	int step;
+	MPI_Status status;
+
+	MPI_Init(&argc,&argv);
+	MPI_Comm_rank(MPI_COMM_WORLD,&id);
+	MPI_Comm_size(MPI_COMM_WORLD,&p);
+
+	startT = MPI_Wtime();
+	
+/**************************** master task ************************************/
+	if(id == MASTER)
+	{
+		int r;
+		srandom(MPI_Wtime());
+		s = n/p;
+		r = n%p;
+		data = (int *)malloc((n+s-r)*sizeof(int));
+		for(i=0;i<n;i++)
+			data[i] = random();
+		if(r!=0)
+		{
+			for(i=n;i<n+s-r;i++)
+				data[i]=0;
+			s=s+1;
+		}
+
+		MPI_Bcast(&s,1,MPI_INT,0,MPI_COMM_WORLD);
+		chunk = (int *)malloc(s*sizeof(int));
+		MPI_Scatter(data,s,MPI_INT,chunk,s,MPI_INT,0,MPI_COMM_WORLD);
+		m_sort(chunk, 0, s-1);
+		/* showVector(chunk, s, id); */
+	}
+
+/**************************** worker task ************************************/
+	else
+	{
+		MPI_Bcast(&s,1,MPI_INT,0,MPI_COMM_WORLD);
+		chunk = (int *)malloc(s*sizeof(int));
+		MPI_Scatter(data,s,MPI_INT,chunk,s,MPI_INT,0,MPI_COMM_WORLD);
+		m_sort(chunk, 0, s-1);
+		/* showVector(chunk, s, id);*/
+	}
+
+
+
+      /*data propagation in a tree fashion*/
+	step = 1;
+	while(step<p)
+	{
+		if(id%(2*step)==0)
+		{
+			if(id+step<p)
+			{
+				MPI_Recv(&m,1,MPI_INT,id+step,0,MPI_COMM_WORLD,&status);
+				other = (int *)malloc(m*sizeof(int));
+				MPI_Recv(other,m,MPI_INT,id+step,0,MPI_COMM_WORLD,&status);
+				chunk = merge(chunk,s,other,m);
+				s = s+m;
+			} 
+		}
+		else
+		{
+			int near = id-step;
+			MPI_Send(&s,1,MPI_INT,near,0,MPI_COMM_WORLD);
+			MPI_Send(chunk,s,MPI_INT,near,0,MPI_COMM_WORLD);
+			break;
+		}
+		step = step*2;
+	}
+
+	stopT = MPI_Wtime();
+	if(id==0)
+	{
+		FILE * fout;
+
+		printf("%d; %d processors; %f secs\n", s, p, (stopT-startT));
+
+		fout = fopen("result","w");
+		for(i=0;i<s;i++)
+			fprintf(fout,"%d\n",chunk[i]);
+		fclose(fout);
+	}
+	MPI_Finalize();
+}
Index: /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/altix64/Makefile.in.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/altix64/Makefile.in.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/altix64/Makefile.in.patch	(revision 11330)
@@ -0,0 +1,10 @@
+3,5c3
+< CC = gcc
+< OBJ_EXT=o
+< LIB_EXT=a
+---
+> CC = cc
+8c6
+< OPTFLAGS = -DLINUX -fPIC
+---
+> OPTFLAGS = -O2 
Index: /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/cosmos/Makefile.in.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/cosmos/Makefile.in.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/cosmos/Makefile.in.patch	(revision 11330)
@@ -0,0 +1,10 @@
+3,5c3
+< CC = icc
+< OBJ_EXT=o
+< LIB_EXT=a
+---
+> CC = cc
+8c6
+< OPTFLAGS = -DLINUX -fPIC
+---
+> OPTFLAGS = -O2 
Index: /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/linux64/Makefile.in.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/linux64/Makefile.in.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/linux64/Makefile.in.patch	(revision 11330)
@@ -0,0 +1,10 @@
+3,5c3
+< CC = gcc
+< OBJ_EXT=o
+< LIB_EXT=a
+---
+> CC = cc
+8c6
+< OPTFLAGS = -DLINUX -fPIC
+---
+> OPTFLAGS = -O2 
Index: /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/macosx32/Makefile.in.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/macosx32/Makefile.in.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/macosx32/Makefile.in.patch	(revision 11330)
@@ -0,0 +1,10 @@
+3,5c3
+< CC = gcc
+< OBJ_EXT=o
+< LIB_EXT=a
+---
+> CC = cc
+8c6
+< OPTFLAGS = -DLINUX -fPIC
+---
+> OPTFLAGS = -O2  -m32
Index: /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/macosx64/Makefile.in.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/macosx64/Makefile.in.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/macosx64/Makefile.in.patch	(revision 11330)
@@ -0,0 +1,10 @@
+3,5c3
+< CC = gcc
+< OBJ_EXT=o
+< LIB_EXT=a
+---
+> CC = cc
+8c6
+< OPTFLAGS = -DLINUX -fPIC
+---
+> OPTFLAGS = -O2  -m64
Index: /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/pleiades/Makefile.in.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/pleiades/Makefile.in.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/pleiades/Makefile.in.patch	(revision 11330)
@@ -0,0 +1,10 @@
+3,5c3
+< CC = gcc
+< OBJ_EXT=o
+< LIB_EXT=a
+---
+> CC = icc
+8c6
+< OPTFLAGS = -DLINUX -fPIC
+---
+> OPTFLAGS = -O2 
Index: /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/win32/Makefile.in.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/win32/Makefile.in.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/configs/4.0/win32/Makefile.in.patch	(revision 11330)
@@ -0,0 +1,14 @@
+3,5c3,5
+< CC = gcc
+< OBJ_EXT=o
+< LIB_EXT=a
+---
+> CC = icl
+> OBJ_EXT=obj
+> LIB_EXT=lib
+8c8
+< OPTFLAGS = -DLINUX -fPIC
+---
+> OPTFLAGS = -DWIN32 -D__VC__
+22d21
+< #RANLIB = 
Index: /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-altix64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-altix64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-altix64.sh	(revision 11330)
@@ -0,0 +1,20 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#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/trunk-jpl-damage/externalpackages/metis/install-4.0-cosmos.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-cosmos.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-cosmos.sh	(revision 11330)
@@ -0,0 +1,20 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#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/trunk-jpl-damage/externalpackages/metis/install-4.0-linux64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-linux64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-linux64.sh	(revision 11330)
@@ -0,0 +1,20 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#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/trunk-jpl-damage/externalpackages/metis/install-4.0-macosx32.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-macosx32.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-macosx32.sh	(revision 11330)
@@ -0,0 +1,20 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#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/trunk-jpl-damage/externalpackages/metis/install-4.0-macosx64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-macosx64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-macosx64.sh	(revision 11330)
@@ -0,0 +1,20 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#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/trunk-jpl-damage/externalpackages/metis/install-4.0-pleiades.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-pleiades.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-pleiades.sh	(revision 11330)
@@ -0,0 +1,20 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#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/trunk-jpl-damage/externalpackages/metis/install-4.0-win32.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-win32.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/install-4.0-win32.sh	(revision 11330)
@@ -0,0 +1,20 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#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/trunk-jpl-damage/externalpackages/metis/install-5.0.1-linux64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/install-5.0.1-linux64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/install-5.0.1-linux64.sh	(revision 11330)
@@ -0,0 +1,20 @@
+#!/bin/bash
+#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
+
+#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_TIER/externalpackages/metis/install"
+make install
Index: /issm/trunk-jpl-damage/externalpackages/metis/metis-4.0.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/metis/metis-4.0.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/metis/metis-4.0.patch	(revision 11330)
@@ -0,0 +1,263 @@
+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 )
+diff -crB install/Makefile.in install2/Makefile.in
+*** install/Makefile.in	1998-10-02 14:28:35.000000000 -0700
+--- install2/Makefile.in	2011-06-08 15:19:00.536540378 -0700
+***************
+*** 1,9 ****
+  
+  # Which compiler to use
+! CC = cc
+  
+  # What optimization level to use
+! OPTFLAGS = -O2 
+  
+  # What options to be used by the compiler
+  COPTIONS = 
+--- 1,11 ----
+  
+  # Which compiler to use
+! CC = gcc
+! OBJ_EXT=o
+! LIB_EXT=a
+  
+  # What optimization level to use
+! OPTFLAGS = -DLINUX -fPIC
+  
+  # What options to be used by the compiler
+  COPTIONS = 
Index: /issm/trunk-jpl-damage/externalpackages/mitgcm/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mitgcm/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mitgcm/install.sh	(revision 11330)
@@ -0,0 +1,25 @@
+#!/bin/bash
+
+#Do these commands once:
+# cvs -d:pserver:cvsanon@mitgcm.org:/u/gcmpack login
+# ( enter the CVS password: "cvsanon" )
+
+#Some cleanup
+rm -rf install  
+
+#add cvs repository
+export CVSROOT=':pserver:cvsanon@mitgcm.org:/u/gcmpack'
+
+#Download code from server
+cvs co -P MITgcm_code
+
+#move
+mv MITgcm install
+
+#compile code
+cd install
+mkdir bin exe
+cd bin
+../tools/genmake2 -mods=../../code
+make depend
+make -j 8
Index: /issm/trunk-jpl-damage/externalpackages/mitgcm/readme_mitgcm.txt
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mitgcm/readme_mitgcm.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mitgcm/readme_mitgcm.txt	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/altix64/Examples.Makefile.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/altix64/Examples.Makefile.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/altix64/Examples.Makefile.patch	(revision 11330)
@@ -0,0 +1,6 @@
+72,73c72,73
+< cpi: cpi.o   ../lib/lib${MPILIBNAME}.a
+< 	$(C_LINK) $(LDFLAGS) -o cpi cpi.o  -lm ${LIBS}
+---
+> cpi: cpi.o   ../lib/lib${MPILIBNAME}.a 
+> 	$(C_LINK) $(LDFLAGS) -o cpi cpi.o  -lm ${LIBS} ../lib/libmpich.a
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/altix64/mpicxx.h.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/altix64/mpicxx.h.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/altix64/mpicxx.h.patch	(revision 11330)
@@ -0,0 +1,12 @@
+26c26
+< //#error "SEEK_SET is #defined but must not be for the C++ binding of MPI"
+---
+> #error "SEEK_SET is #defined but must not be for the C++ binding of MPI"
+30c30
+< //#error "SEEK_CUR is #defined but must not be for the C++ binding of MPI"
+---
+> #error "SEEK_CUR is #defined but must not be for the C++ binding of MPI"
+35c35
+< //#error "SEEK_END is #defined but must not be for the C++ binding of MPI"
+---
+> #error "SEEK_END is #defined but must not be for the C++ binding of MPI"
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/linux64/Examples.Makefile.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/linux64/Examples.Makefile.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/linux64/Examples.Makefile.patch	(revision 11330)
@@ -0,0 +1,6 @@
+72,73c72,73
+< cpi: cpi.o   ../lib/lib${MPILIBNAME}.a
+< 	$(C_LINK) $(LDFLAGS) -o cpi cpi.o  -lm ${LIBS}
+---
+> cpi: cpi.o   ../lib/lib${MPILIBNAME}.a 
+> 	$(C_LINK) $(LDFLAGS) -o cpi cpi.o  -lm ${LIBS} ../lib/libmpich.a
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/linux64/mpicxx.h.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/linux64/mpicxx.h.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/linux64/mpicxx.h.patch	(revision 11330)
@@ -0,0 +1,12 @@
+26c26
+< //#error "SEEK_SET is #defined but must not be for the C++ binding of MPI"
+---
+> #error "SEEK_SET is #defined but must not be for the C++ binding of MPI"
+30c30
+< //#error "SEEK_CUR is #defined but must not be for the C++ binding of MPI"
+---
+> #error "SEEK_CUR is #defined but must not be for the C++ binding of MPI"
+35c35
+< //#error "SEEK_END is #defined but must not be for the C++ binding of MPI"
+---
+> #error "SEEK_END is #defined but must not be for the C++ binding of MPI"
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/macosx32/Examples.Makefile.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/macosx32/Examples.Makefile.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/macosx32/Examples.Makefile.patch	(revision 11330)
@@ -0,0 +1,6 @@
+72,73c72,73
+< cpi: cpi.o   ../lib/lib${MPILIBNAME}.a
+< 	$(C_LINK) $(LDFLAGS) -o cpi cpi.o  -lm ${LIBS}
+---
+> cpi: cpi.o   ../lib/lib${MPILIBNAME}.a 
+> 	$(C_LINK) $(LDFLAGS) -o cpi cpi.o  -lm ${LIBS} ../lib/libmpich.a
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/macosx32/mpicxx.h.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/macosx32/mpicxx.h.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/macosx32/mpicxx.h.patch	(revision 11330)
@@ -0,0 +1,12 @@
+26c26
+< //#error "SEEK_SET is #defined but must not be for the C++ binding of MPI"
+---
+> #error "SEEK_SET is #defined but must not be for the C++ binding of MPI"
+30c30
+< //#error "SEEK_CUR is #defined but must not be for the C++ binding of MPI"
+---
+> #error "SEEK_CUR is #defined but must not be for the C++ binding of MPI"
+35c35
+< //#error "SEEK_END is #defined but must not be for the C++ binding of MPI"
+---
+> #error "SEEK_END is #defined but must not be for the C++ binding of MPI"
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/win32/Examples.Makefile.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/win32/Examples.Makefile.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/win32/Examples.Makefile.patch	(revision 11330)
@@ -0,0 +1,6 @@
+72,73c72,73
+< cpi: cpi.o   ../lib/lib${MPILIBNAME}.a
+< 	$(C_LINK) $(LDFLAGS) -o cpi cpi.o  -lm ${LIBS}
+---
+> cpi: cpi.o   ../lib/lib${MPILIBNAME}.a 
+> 	$(C_LINK) $(LDFLAGS) -o cpi cpi.o  -lm ${LIBS} ../lib/libmpich.a
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/win32/mpicxx.h.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/win32/mpicxx.h.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/configs/1.0.2/win32/mpicxx.h.patch	(revision 11330)
@@ -0,0 +1,12 @@
+26c26
+< //#error "SEEK_SET is #defined but must not be for the C++ binding of MPI"
+---
+> #error "SEEK_SET is #defined but must not be for the C++ binding of MPI"
+30c30
+< //#error "SEEK_CUR is #defined but must not be for the C++ binding of MPI"
+---
+> #error "SEEK_CUR is #defined but must not be for the C++ binding of MPI"
+35c35
+< //#error "SEEK_END is #defined but must not be for the C++ binding of MPI"
+---
+> #error "SEEK_END is #defined but must not be for the C++ binding of MPI"
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.0.2-altix64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.0.2-altix64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.0.2-altix64.sh	(revision 11330)
@@ -0,0 +1,39 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install mpich2-1.0.2p1
+mkdir src install
+
+#Untar 
+tar -zxvf  mpich2-1.0.2p1.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.0.2p1/* src
+rm -rf mpich2-1.0.2p1
+
+#Configure mpich2
+cd src
+make distclean
+export CFLAGS="$CFLAGS -fPIC"
+export FFLAGS="$FFLAGS -fPIC"
+./configure \
+	--prefix="$ISSM_TIER/externalpackages/mpich2/install" \
+	--enable-sharedlibs=gcc \
+	--enable-f91=gfortran 
+
+#Apply Patch to examples
+patch ./examples/Makefile ../configs/1.0.2/altix64/Examples.Makefile.patch
+patch -R ./src/binding/cxx/mpicxx.h ../configs/1.0.2/altix64/mpicxx.h.patch
+patch -R ./src/include/mpicxx.h ../configs/1.0.2/altix64/mpicxx.h.patch
+
+#Compile mpich2
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
+
+#remove so files
+cd ../install/lib
+rm -rf *.so
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.0.2-linux64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.0.2-linux64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.0.2-linux64.sh	(revision 11330)
@@ -0,0 +1,35 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install mpich2-1.0.2p1
+mkdir src install
+
+#Untar 
+tar -zxvf  mpich2-1.0.2p1.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.0.2p1/* src
+rm -rf mpich2-1.0.2p1
+
+#Configure mpich2
+cd src
+make distclean
+export CFLAGS="$CFLAGS -fPIC"
+export FFLAGS="$FFLAGS -fPIC"
+./configure \
+	--prefix="$ISSM_TIER/externalpackages/mpich2/install" \
+	--enable-sharedlibs=gcc \
+	--enable-f91=gfortran 
+
+#Apply Patch to examples
+patch ./examples/Makefile ../configs/1.0.2/linux64/Examples.Makefile.patch
+patch -R ./src/binding/cxx/mpicxx.h ../configs/1.0.2/linux64/mpicxx.h.patch
+patch -R ./src/include/mpicxx.h ../configs/1.0.2/linux64/mpicxx.h.patch
+
+#Compile mpich2
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.0.2-macosx32.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.0.2-macosx32.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.0.2-macosx32.sh	(revision 11330)
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install mpich2-1.0.2p1
+mkdir src install
+
+#Untar 
+tar -zxvf  mpich2-1.0.2p1.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.0.2p1/* src
+rm -rf mpich2-1.0.2p1
+
+#Configure mpich2
+cd src
+make distclean
+export CFLAGS=" -m32"
+./configure \
+	--prefix="$ISSM_TIER/externalpackages/mpich2/install" \
+	--enable-f91=gfortran \
+	--enable-sharedlibs=osx-gcc
+
+#Apply Patch to examples
+patch ./examples/Makefile ../configs/1.0.2/macosx32/Examples.Makefile.patch
+patch -R ./src/binding/cxx/mpicxx.h ../configs/1.0.2/macosx32/mpicxx.h.patch
+patch -R ./src/include/mpicxx.h ../configs/1.0.2/macosx32/mpicxx.h.patch
+
+#Compile mpich2
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
+
+#remove so files
+cd ../install/lib
+rm -rf *.so
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.0.2-win32.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.0.2-win32.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.0.2-win32.sh	(revision 11330)
@@ -0,0 +1,36 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install mpich2-1.0.2p1
+mkdir src install
+
+#Untar 
+tar -zxvf  mpich2-1.0.2p1.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.0.2p1/* src
+rm -rf mpich2-1.0.2p1
+
+#Configure mpich2
+cd src
+make distclean
+export CFLAGS="$CFLAGS -fPIC"
+export FFLAGS="$FFLAGS -fPIC"
+./configure --prefix="$ISSM_TIER/externalpackages/mpich2/install" 
+
+#Apply Patch to examples
+patch ./examples/Makefile ../configs/1.0.2/win32/Examples.Makefile.patch
+patch -R ./src/binding/cxx/mpicxx.h ../configs/1.0.2/win32/mpicxx.h.patch
+patch -R ./src/include/mpicxx.h ../configs/1.0.2/win32/mpicxx.h.patch
+
+#Compile mpich2
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
+
+#remove so files
+cd ../install/lib
+rm -rf *.so
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.4-linux64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.4-linux64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.4-linux64.sh	(revision 11330)
@@ -0,0 +1,34 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install mpich2-1.4
+mkdir src install
+
+#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 CFLAGS="$CFLAGS -fPIC"
+export FFLAGS="$FFLAGS -fPIC"
+./configure \
+	--prefix="$ISSM_TIER/externalpackages/mpich2/install" \
+	--enable-shared \
+	--enable-sharedlibs=gcc \
+	--enable-f91=gfortran 
+
+#Compile mpich2
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
+
+#remove so files
+cd ../install/lib
+rm -rf *.so
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.4-macosx32.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.4-macosx32.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.4-macosx32.sh	(revision 11330)
@@ -0,0 +1,37 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install mpich2-1.4
+mkdir src install
+
+#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 CFLAGS=" -arch i386"
+export CXXFLAGS=" -arch i386"
+export CPPFLAGS=" -arch i386"
+export FFLAGS=" -arch i386"
+./configure \
+	--prefix="$ISSM_TIER/externalpackages/mpich2/install" \
+	--enable-f91=gfortran \
+	--enable-sharedlibs=osx-gcc \
+	--enable-shared \
+	--enable-fc="/usr/local/bin/gfortran"
+
+#Compile mpich2
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
+
+#remove so files
+cd ../install/lib
+rm -rf *.so
Index: /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.4-macosx64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.4-macosx64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/mpich2/install-1.4-macosx64.sh	(revision 11330)
@@ -0,0 +1,37 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install mpich2-1.4
+mkdir src install
+
+#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_TIER/externalpackages/mpich2/install" \
+	--enable-f91 \
+	--enable-sharedlibs=osx-gcc \
+	--enable-shared \
+	--enable-fc
+
+#Compile mpich2
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
+
+#remove so files
+cd ../install/lib
+rm -rf *.so
Index: /issm/trunk-jpl-damage/externalpackages/ncview/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/ncview/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/ncview/install.sh	(revision 11330)
@@ -0,0 +1,24 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install
+mkdir install
+
+#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_TIER/externalpackages/ncview/install" \
+	--x-libraries=/usr/X11/lib/ \
+	--x-includes=/usr/X11/include/ \
+	--with-netcdf_incdir="$ISSM_TIER/externalpackages/netcdf/install/include/" \
+	--with-netcdf_libdir="$ISSM_TIER/externalpackages/netcdf/install/lib/"
+
+make
+make install
Index: /issm/trunk-jpl-damage/externalpackages/netcdf/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/netcdf/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/netcdf/install.sh	(revision 11330)
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install netcdf-4.0.1
+mkdir install
+
+#Untar 
+tar -zxvf  netcdf-4.0.1.tar.gz
+
+#Move netcdf to install directory
+rm -rf install/*
+mv netcdf-4.0.1/* install/
+rm -rf netcdf-4.0.1
+
+#Configure and compile
+cd install
+./configure  --prefix="$ISSM_TIER/externalpackages/netcdf/install" 
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk-jpl-damage/externalpackages/oofem/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/oofem/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/oofem/install.sh	(revision 11330)
@@ -0,0 +1,32 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src
+rm -rf oofem-2.0
+mkdir src
+
+#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 [ -z $1 ]; 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/trunk-jpl-damage/externalpackages/openanalysis/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/openanalysis/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/openanalysis/install.sh	(revision 11330)
@@ -0,0 +1,13 @@
+#!/bin/bash
+
+#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/trunk-jpl-damage/externalpackages/pcre/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/pcre/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/pcre/install.sh	(revision 11330)
@@ -0,0 +1,17 @@
+#!/bin/bash
+
+#Cleaning
+rm -rf install
+rm -rf pcre-8.21
+mkdir install
+
+#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_TIER/externalpackages/python/install"
+make
+make install
Index: /issm/trunk-jpl-damage/externalpackages/petsc/README
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/README	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/README	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-altix64-castor.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-altix64-castor.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-altix64-castor.sh	(revision 11330)
@@ -0,0 +1,61 @@
+#!/bin/bash
+#Step 1: unzip and install
+#Step 2: After Plapack implodes
+STEP=0
+
+if [ $STEP -eq 1 ]; then
+	#Some cleanup
+	rm -rf install petsc-2.3.2-p3 src
+	mkdir install src
+
+	#Untar and move petsc to install directory
+	tar -zxvf  petsc-2.3.2-p3.tar.gz
+	mv petsc-2.3.2-p3/* install/
+	rm -rf petsc-2.3.2-p3
+
+	#configure
+	cd install
+	./config/configure.py \
+		--prefix="$ISSM_TIER/externalpackages/petsc/install" \
+		--with-batch=1  \
+		--ISSM_ARCH=$ISSM_ARCH \
+		--PETSC_DIR=$PETSC_DIR   \
+		--with-debugging=no \
+		--with-shared=0 COPTFLAGS=-O3 FOPTFLAGS=-O3 \
+		--with-blas-lapack-dir=/opt/intel/mkl/9.1.023 \
+		--with-mpi-lib=/usr/lib/libmpi.so \
+		--with-mpi-include=/usr/include  \
+		--with-mpi-shared=0 \
+		--download-mumps=yes \
+		--download-scalapack=yes \
+		--download-blacs=yes  \
+		--download-plapack=yes \
+		--FFLAGS=-I/usr/include \
+		--with-cc=icc \
+		--with-fc=ifort
+
+	echo "== Fix Plapack compilation manually (http://issm.jpl.nasa.gov/installation/compilationtroubleshooting/petsc232/) =="
+	echo "== Then run STEP=2 =="
+fi
+if [ $STEP -eq 2 ]; then
+	cd install
+	./config/configure.py  \
+		--prefix="$ISSM_TIER/externalpackages/petsc/install" \
+		--with-batch=1  \
+		--ISSM_ARCH=$ISSM_ARCH \
+		--PETSC_DIR=$PETSC_DIR   \
+		--with-debugging=no \
+		--with-shared=0 COPTFLAGS=-O3 FOPTFLAGS=-O3 \
+		--with-blas-lapack-dir=/opt/intel/mkl/9.1.023 \
+		--with-mpi-lib=/usr/lib/libmpi.so \
+		--with-mpi-include=/usr/include  \
+		--with-mpi-shared=0 \
+		--download-mumps=yes \
+		--download-scalapack=yes \
+		--download-blacs=yes  \
+		--with-plapack-dir=$PETSC_DIR/externalpackages/PLAPACKR32-hg/$ISSM_ARCH \
+		--FFLAGS=-I/usr/include \
+		--with-cc=icc \
+		--with-fc=ifort
+	echo "== Follow PETSc's instructions"
+fi
Index: /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-cosmos.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-cosmos.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-cosmos.sh	(revision 11330)
@@ -0,0 +1,32 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-2.3.2-p3 src
+mkdir install src
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-2.3.2-p3.tar.gz
+mv petsc-2.3.2-p3/* install/
+rm -rf petsc-2.3.2-p3
+
+#configure
+cd install
+PETSC_DIR=$ISSM_TIER/externalpackages/petsc/install
+./config/configure.py  \
+	--prefix=$PETSC_DIR \
+	--with-batch=1  \
+	--ISSM_ARCH=$ISSM_ARCH \
+	--PETSC_DIR=$PETSC_DIR   \
+	--with-debugging=no COPTFLAGS=-O3 FOPTFLAGS=-O3 \
+	--with-blas-lapack-dir=/opt/intel/mkl/10.0.5.025/ \
+	--with-mpi-dir=/opt/mpich/gm/intel10.1/  \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes  \
+	--download-plapack=yes \
+	--FFLAGS=-I/usr/include  \
+	--with-mpi-shared=0
+
+#Compile petsc and install it
+make
+make install
Index: /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-linux64-astrid.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-linux64-astrid.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-linux64-astrid.sh	(revision 11330)
@@ -0,0 +1,35 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-2.3.2-p3 src
+mkdir install src
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-2.3.2-p3.tar.gz
+mv petsc-2.3.2-p3/* install/
+rm -rf petsc-2.3.2-p3
+
+#configure
+cd install
+./config/configure.py  \
+	--prefix="$ISSM_TIER/externalpackages/petsc/install" \
+	--with-mpi-dir=$ISSM_TIER/externalpackages/mpich2/install \
+	--PETSC_ARCH=linux-gnu-amd64 \
+	--PETSC_DIR="$ISSM_TIER/externalpackages/petsc/install" \
+	--with-fc=gfortran \
+	--with-debugging=1 \
+	--with-shared=0 \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--FFLAGS=-I$ISSM_TIER/externalpackages/mpich2/install/include \
+	--download-plapack=yes \
+	--COPTFLAGS="-march=opteron -O2" \
+	--FOPTFLAGS="-march=opteron -O2" \
+	--CXXOPTFLAGS="-march=opteron -O2" 
+
+#Compile petsc and install it
+make
+make install
Index: /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-macosx32-eric.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-macosx32-eric.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-macosx32-eric.sh	(revision 11330)
@@ -0,0 +1,68 @@
+#!/bin/bash
+#Step 1: unzip and install
+#Step 2: After MUMPS Crashes
+STEP=0
+
+if [ $STEP -eq 1 ]; then
+	#Some cleanup
+	rm -rf install petsc-2.3.2-p3 src
+	mkdir install src
+
+	#Untar and move petsc to install directory
+	tar -zxvf  petsc-2.3.2-p3.tar.gz
+	mv petsc-2.3.2-p3/* install/
+	rm -rf petsc-2.3.2-p3
+
+	#configure
+	cd install
+	./config/configure.py  \
+		--prefix="$ISSM_TIER/externalpackages/petsc/install" \
+		--with-mpi-dir=$ISSM_TIER/externalpackages/mpich2/install \
+		--PETSC_ARCH=macosx-gnu \
+		--PETSC_DIR="$ISSM_TIER/externalpackages/petsc/install" \
+		--with-fc=/usr/local/bin/gfortran \
+		--with-debugging=0 \
+		--with-shared=0 \
+		--download-mumps=yes \
+		--download-scalapack=yes \
+		--download-blacs=yes \
+		--download-blas=yes \
+		--download-f-blas-lapack=yes \
+		--FFLAGS="-I$ISSM_TIER/externalpackages/mpich2/install/include -L$ISSM_TIER/externalpackages/mpich2/install/lib -L/usr/local/bin -lmpich -lpmpich -lgfortran  -fPIC -arch i386" \
+		--download-plapack=yes \
+		--CXXFLAGS=" -fPIC -arch i386" \
+		--CFLAGS=" -fPIC -arch i386" \
+		--with-pic \
+		--with-fc="gfortran -arch i386 " \
+		--LDFLAGS="-arch i386"
+	echo "== Fix MUMPS compilation manually (http://issm.jpl.nasa.gov/installation/compilationtroubleshooting/petsc232/) =="
+	echo "== Then run STEP=2 =="
+fi
+
+if [ $STEP -eq 2 ]; then
+	cd install
+	./config/configure.py  \
+		--prefix="$ISSM_TIER/externalpackages/petsc/install" \
+		--with-mpi-dir=$ISSM_TIER/externalpackages/mpich2/install \
+		--PETSC_ARCH=macosx-gnu \
+		--PETSC_DIR="$ISSM_TIER/externalpackages/petsc/install" \
+		--with-fc=/usr/local/bin/gfortran \
+		--with-debugging=0 \
+		--with-shared=0 \
+		--with-mumps-dir=$ISSM_TIER/externalpackages/petsc/install/externalpackages/MUMPS_4.6.3  \
+		--download-scalapack=yes \
+		--download-blacs=yes \
+		--download-blas=yes \
+		--download-f-blas-lapack=yes \
+		--FFLAGS="-I$ISSM_TIER/externalpackages/mpich2/install/include -L$ISSM_TIER/externalpackages/mpich2/install/lib -L/usr/local/bin -lmpich -lpmpich -lgfortran  -fPIC -arch i386" \
+		--download-plapack=yes \
+		--CXXFLAGS=" -fPIC -arch i386" \
+		--CFLAGS=" -fPIC -arch i386" \
+		--with-pic \
+		--with-fc="gfortran -arch i386 " \
+		--LDFLAGS="-arch i386"
+
+	#Compile petsc and install it
+	make
+	make install
+fi
Index: /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-macosx32-ogive.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-macosx32-ogive.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-macosx32-ogive.sh	(revision 11330)
@@ -0,0 +1,31 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-2.3.2-p3 src
+mkdir install src
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-2.3.2-p3.tar.gz
+mv petsc-2.3.2-p3/* install/
+rm -rf petsc-2.3.2-p3
+
+#configure
+cd install
+./config/configure.py  --prefix="$ISSM_TIER/externalpackages/petsc/install" \
+	--with-mpi-dir=$ISSM_TIER/externalpackages/mpich2/install \
+	--PETSC_ARCH=macosx-gnu \
+	--PETSC_DIR="$ISSM_TIER/externalpackages/petsc/install" \
+	--with-fc=/usr/local/bin/gfortran \
+	--with-debugging=0 \
+	--with-shared=0 \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--FFLAGS="-I$ISSM_TIER/externalpackages/mpich2/install/include -L$ISSM_TIER/externalpackages/mpich2/install/lib -L/usr/local/bin -lmpich -lpmpich -lgfortran" \
+	--download-plapack=yes
+
+#Compile petsc and install it
+make
+make install
Index: /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-pleiades.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-pleiades.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-pleiades.sh	(revision 11330)
@@ -0,0 +1,67 @@
+#!/bin/bash
+#Step 1: unzip and install
+#Step 2: After Plapack implodes
+STEP=0
+
+if [ $STEP -eq 1 ]; then
+	#Some cleanup
+	rm -rf install petsc-2.3.2-p3 src
+	mkdir install src
+
+	#Untar and move petsc to install directory
+	tar -zxvf  petsc-2.3.2-p3.tar.gz
+	mv petsc-2.3.2-p3/* install/
+	rm -rf petsc-2.3.2-p3
+
+	#configure
+	cd install
+	./config/configure.py  \
+		--prefix="$ISSM_TIER/externalpackages/petsc/install" \
+		--with-batch=1  \
+		--PETSC_ARCH=$ISSM_ARCH \
+		--PETSC_DIR=$PETSC_DIR   \
+		--with-debugging=no \
+		--with-shared=0 \
+		--with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
+		--with-mpi-lib=/nasa/sgi/mpt/1.23.nas/lib64/libmpi.so \
+		--with-mpi-include=/nasa/sgi/mpt/1.23.nas/include  \
+		--with-mpi-shared=0 \
+		--download-mumps=yes \
+		--download-scalapack=yes \
+		--download-blacs=yes  \
+		--download-plapack=yes \
+		--FFLAGS=-I/usr/include \
+		--with-cc=icc \
+		--with-fc=ifort \
+		--COPTFLAGS=" -O3 -xS" \
+		--FOPTFLAGS=" -O3 -xS" \
+		--CXXOPTFLAGS=" -O3 -xS"
+
+	echo "== Fix Plapack compilation manually (http://issm.jpl.nasa.gov/installation/compilationtroubleshooting/petsc232/) =="
+	echo "== Then run STEP=2 =="
+fi
+if [ $STEP -eq 2 ]; then
+	cd install
+	./config/configure.py  \
+		--prefix="$ISSM_TIER/externalpackages/petsc/install" \
+		--with-batch=1  \
+		--PETSC_ARCH=$ISSM_ARCH \
+		--PETSC_DIR=$PETSC_DIR   \
+		--with-debugging=no \
+		--with-shared=0 \
+		--with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
+		--with-mpi-lib=/nasa/sgi/mpt/1.23.nas/lib64/libmpi.so \
+		--with-mpi-include=/nasa/sgi/mpt/1.23.nas/include  \
+		--with-mpi-shared=0 \
+		--download-mumps=yes \
+		--download-scalapack=yes \
+		--download-blacs=yes  \
+		--with-plapack-dir=$PETSC_DIR/externalpackages/PLAPACKR32-hg/$ISSM_ARCH \
+		--FFLAGS=-I/usr/include \
+		--with-cc=icc \
+		--with-fc=ifort \
+		--COPTFLAGS=" -O3 -xS" \
+		--FOPTFLAGS=" -O3 -xS" \
+		--CXXOPTFLAGS=" -O3 -xS"
+	echo "== Follow PETSc's instructions"
+fi
Index: /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-win32-eric.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-win32-eric.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-2.3.2-win32-eric.sh	(revision 11330)
@@ -0,0 +1,25 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-2.3.2-p3 src
+mkdir install src
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-2.3.2-p3.tar.gz
+mv petsc-2.3.2-p3/* install/
+rm -rf petsc-2.3.2-p3
+
+#configure
+cd install
+./config/configure.py  \
+	--with-parallel-no \
+	--prefix="$ISSM_TIER/externalpackages/petsc/install" \
+	--PETSC_ARCH=cygwin-intel \
+	--PETSC_DIR="$ISSM_TIER/externalpackages/petsc/install" \
+	--with-debugging=0 \
+	--with-mpi=0 \
+	--download-c-blas-lapack=1
+
+#Compile petsc and install it
+make
+make install
Index: /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-altix64-castor.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-altix64-castor.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-altix64-castor.sh	(revision 11330)
@@ -0,0 +1,62 @@
+#!/bin/bash
+#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
+
+	#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_TIER/externalpackages/petsc/install" \
+	  --PETSC_DIR="$ISSM_TIER/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_TIER/externalpackages/petsc/install" \
+		--PETSC_DIR="$ISSM_TIER/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/trunk-jpl-damage/externalpackages/petsc/install-3.1-cosmos.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-cosmos.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-cosmos.sh	(revision 11330)
@@ -0,0 +1,32 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.1-p7 src
+mkdir install src
+
+#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_TIER/externalpackages/petsc/install" \
+	--PETSC_DIR="$ISSM_TIER/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/trunk-jpl-damage/externalpackages/petsc/install-3.1-linux64-astrid.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-linux64-astrid.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-linux64-astrid.sh	(revision 11330)
@@ -0,0 +1,36 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.1-p7 src
+mkdir install src
+
+#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_TIER/externalpackages/petsc/install" \
+ --with-mpi-dir=$ISSM_TIER/externalpackages/mpich2/install \
+ --PETSC_ARCH=linux-gnu-amd64 \
+ --PETSC_DIR="$ISSM_TIER/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_TIER/externalpackages/mpich2/install/include \
+ --download-plapack=yes \
+ --COPTFLAGS="-march=opteron -O2" \
+ --FOPTFLAGS="-march=opteron -O2" \
+ --CXXOPTFLAGS="-march=opteron -O2" \
+ --with-pic=1
+
+#Compile petsc and install it
+make
+make install
Index: /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-macosx32-mathieu.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-macosx32-mathieu.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-macosx32-mathieu.sh	(revision 11330)
@@ -0,0 +1,35 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.1-p7 src
+mkdir install src
+
+#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_TIER/externalpackages/petsc/install" \
+ --PETSC_DIR="$ISSM_TIER/externalpackages/petsc/src" \
+ --PETSC_ARCH=macosx-gnu \
+ --with-mpi-dir=$ISSM_TIER/externalpackages/mpich2/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_TIER/externalpackages/mpich2/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/trunk-jpl-damage/externalpackages/petsc/install-3.1-macosx32-ogive.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-macosx32-ogive.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-macosx32-ogive.sh	(revision 11330)
@@ -0,0 +1,36 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.1-p7 src
+mkdir install src
+
+#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_TIER/externalpackages/petsc/install" \
+	--PETSC_DIR="$ISSM_TIER/externalpackages/petsc/src" \
+	--with-mpi-dir=$ISSM_TIER/externalpackages/mpich2/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_TIER/externalpackages/mpich2/install/include -L$ISSM_TIER/externalpackages/mpich2/install/lib -L/usr/local/bin -lmpich -lpmpich -lgfortran " 
+
+#Compile petsc and install it
+make
+make install
Index: /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-pleiades.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-pleiades.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-3.1-pleiades.sh	(revision 11330)
@@ -0,0 +1,69 @@
+#!/bin/bash
+#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
+
+	#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_TIER/externalpackages/petsc/install" \
+		--with-batch=1  \
+		--PETSC_ARCH="$ISSM_ARCH" \
+		--PETSC_DIR="$ISSM_TIER/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_TIER/externalpackages/petsc/install" \
+	 --with-batch=1  \
+	 --PETSC_ARCH="$ISSM_ARCH" \
+	 --PETSC_DIR="$ISSM_TIER/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_TIER/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/trunk-jpl-damage/externalpackages/petsc/install-3.2-linux64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-3.2-linux64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-3.2-linux64.sh	(revision 11330)
@@ -0,0 +1,33 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.2-p3 src
+mkdir install src
+
+#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_TIER/externalpackages/petsc/install" \
+	--with-mpi-dir=$ISSM_TIER/externalpackages/mpich2/install \
+	--with-clanguage=C++ \
+	--PETSC_ARCH=linux-gnu-amd64 \
+	--PETSC_DIR="$ISSM_TIER/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--with-shared-libraries=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/trunk-jpl-damage/externalpackages/petsc/install-3.2-macosx64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-3.2-macosx64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-3.2-macosx64.sh	(revision 11330)
@@ -0,0 +1,31 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.2-p3 src
+mkdir install src
+
+#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_TIER/externalpackages/petsc/install" \
+  --PETSC_DIR="$ISSM_TIER/externalpackages/petsc/src" \
+  --PETSC_ARCH=macosx-gnu \
+  --with-mpi-dir="$ISSM_TIER/externalpackages/mpich2/install" \
+  --with-debugging=0 \
+  --with-shared-libraries=0 \
+  --download-mumps=yes \
+  --download-scalapack=yes \
+  --download-blacs=yes \
+  --download-blas=yes \
+  --download-plapack=yes  \
+  --download-parmetis=yes \
+  --download-f-blas-lapack=yes 
+
+#Compile petsc and install it
+make
+make install
Index: /issm/trunk-jpl-damage/externalpackages/petsc/install-3.2-pleiades.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/petsc/install-3.2-pleiades.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/petsc/install-3.2-pleiades.sh	(revision 11330)
@@ -0,0 +1,69 @@
+#!/bin/bash
+#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
+
+	#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_TIER/externalpackages/petsc/install" \
+		--with-batch=1  \
+		--PETSC_ARCH="$ISSM_ARCH" \
+		--PETSC_DIR="$ISSM_TIER/externalpackages/petsc/src" \
+		--with-debugging=0 \
+		--with-shared-libraries=0 \
+		--with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
+		--known-mpi-shared-libraries=1 \
+		--with-mpi-lib=/nasa/sgi/mpt/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/installation/compilationtroubleshooting/petsc31/) =="
+	echo "== Then run STEP=2 =="
+fi
+if [ $STEP -eq 2 ]; then
+	cd src
+	./config/configure.py \
+	 --prefix="$ISSM_TIER/externalpackages/petsc/install" \
+	 --with-batch=1  \
+	 --PETSC_ARCH="$ISSM_ARCH" \
+	 --PETSC_DIR="$ISSM_TIER/externalpackages/petsc/src" \
+	 --with-debugging=0 \
+	 --with-shared-libraries=0 \
+	 --with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
+	 --with-mpi-lib=/nasa/sgi/mpt/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_TIER/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/trunk-jpl-damage/externalpackages/polygonclipper/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/polygonclipper/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/polygonclipper/install.sh	(revision 11330)
@@ -0,0 +1,15 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install
+
+#install
+mkdir install
+cd install
+cp ../PolygonClipper.zip .
+
+#uncompress
+unzip PolygonClipper.zip
+
+#Make
+mex gpc.c gpc_mexfile.c -O -output PolygonClip
Index: /issm/trunk-jpl-damage/externalpackages/python/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/python/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/python/install.sh	(revision 11330)
@@ -0,0 +1,22 @@
+#!/bin/bash
+#wget http://python.org/ftp/python/3.2.2/Python-3.2.2.tgz
+
+#Some cleanup
+rm -rf install
+rm -rf Python-3.2.2
+mkdir install
+
+#Untar and move python into install directory
+tar -zxvf  Python-3.2.2.tgz
+mv Python-3.2.2/* install
+rm -rf Python-3.2.2
+
+#Configure doxygen
+cd install 
+./configure --prefix "$ISSM_TIER/externalpackages/python/install"
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk-jpl-damage/externalpackages/qhull/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/qhull/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/qhull/install.sh	(revision 11330)
@@ -0,0 +1,19 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install qhull-2003.1
+mkdir src install
+
+#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_TIER/externalpackages/qhull/install"
+make
+make install
Index: /issm/trunk-jpl-damage/externalpackages/rats/README
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/rats/README	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/rats/README	(revision 11330)
@@ -0,0 +1,3 @@
+Rought Auditing Tools for Software
+Obtained code from https://www.fortify.com/ssa-elements/threat-intelligence/rats.html
+
Index: /issm/trunk-jpl-damage/externalpackages/rats/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/rats/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/rats/install.sh	(revision 11330)
@@ -0,0 +1,17 @@
+#!/bin/bash
+
+#Erase install
+rm -rf install  src rats-2.3
+
+#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_TIER/externalpackages/rats/install
+make
+make install
+cd ..
Index: /issm/trunk-jpl-damage/externalpackages/rose/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/rose/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/rose/install.sh	(revision 11330)
@@ -0,0 +1,26 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf source build install
+mkdir install source build
+
+#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_TIER/externalpackages/rose/install \
+	--with-boost=$ISSM_TIER/externalpackages/boost/install\
+	--srcdir=$ISSM_TIER/externalpackages/rose/source
+
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk-jpl-damage/externalpackages/satstress/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/satstress/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/satstress/install.sh	(revision 11330)
@@ -0,0 +1,16 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install SatStress-0.1.2
+mkdir install
+
+#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/trunk-jpl-damage/externalpackages/scotch/Makefile.inc
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/scotch/Makefile.inc	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/scotch/Makefile.inc	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/scotch/gmap.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/scotch/gmap.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/scotch/gmap.m	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/scotch/gmap_mex.c
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/scotch/gmap_mex.c	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/scotch/gmap_mex.c	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/scotch/gmapx.c
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/scotch/gmapx.c	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/scotch/gmapx.c	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/scotch/gpart.m
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/scotch/gpart.m	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/scotch/gpart.m	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/scotch/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/scotch/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/scotch/install.sh	(revision 11330)
@@ -0,0 +1,51 @@
+#!/bin/bash
+
+# Some cleanup
+rm -rf scotch_5.1
+rm -rf src 
+rm -rf install 
+
+# Create src and install directories
+mkdir src install 
+
+# Untar 
+tar -xvzf scotch_5.1.6.tar.gz
+
+# Move scotch to src directory
+mv scotch_5.1/* src
+rm -rf scotch_5.1
+
+# Apply patches (all at once, since many)
+# (written by diff -rc old_src new_src > scotch.patch)
+patch -p0 < scotch.patch
+
+# Build scotch
+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/trunk-jpl-damage/externalpackages/scotch/mex/Gmap.c
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/scotch/mex/Gmap.c	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/scotch/mex/Gmap.c	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/scotch/mex/Gmapx.c
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/scotch/mex/Gmapx.c	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/scotch/mex/Gmapx.c	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/scotch/mex/Makefile
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/scotch/mex/Makefile	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/scotch/mex/Makefile	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/scotch/mex/VectorToSparse.c
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/scotch/mex/VectorToSparse.c	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/scotch/mex/VectorToSparse.c	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/scotch/scotch.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/scotch/scotch.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/scotch/scotch.patch	(revision 11330)
@@ -0,0 +1,2397 @@
+Only in new5: bin
+Only in new5: include
+Only in new5: lib
+diff -rc src/src/libscotch/arch.c new5/src/libscotch/arch.c
+*** src/src/libscotch/arch.c	2008-09-27 07:48:01.000000000 -0700
+--- new5/src/libscotch/arch.c	2010-07-21 17:13:15.583257119 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_cmplt.c new5/src/libscotch/arch_cmplt.c
+*** src/src/libscotch/arch_cmplt.c	2008-05-22 06:44:41.000000000 -0700
+--- new5/src/libscotch/arch_cmplt.c	2010-07-21 17:13:15.585257133 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_cmplt.h new5/src/libscotch/arch_cmplt.h
+*** src/src/libscotch/arch_cmplt.h	2008-05-22 06:44:41.000000000 -0700
+--- new5/src/libscotch/arch_cmplt.h	2010-07-21 17:13:15.588257154 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_cmpltw.c new5/src/libscotch/arch_cmpltw.c
+*** src/src/libscotch/arch_cmpltw.c	2008-08-27 14:22:22.000000000 -0700
+--- new5/src/libscotch/arch_cmpltw.c	2010-07-21 17:13:15.590257168 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_cmpltw.h new5/src/libscotch/arch_cmpltw.h
+*** src/src/libscotch/arch_cmpltw.h	2008-05-22 06:44:41.000000000 -0700
+--- new5/src/libscotch/arch_cmpltw.h	2010-07-21 17:13:15.592257181 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_deco.c new5/src/libscotch/arch_deco.c
+*** src/src/libscotch/arch_deco.c	2008-09-28 06:35:27.000000000 -0700
+--- new5/src/libscotch/arch_deco.c	2010-07-21 17:13:15.595257202 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_deco.h new5/src/libscotch/arch_deco.h
+*** src/src/libscotch/arch_deco.h	2008-09-27 07:49:46.000000000 -0700
+--- new5/src/libscotch/arch_deco.h	2010-07-21 17:13:15.597257216 -0700
+***************
+*** 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 -rc src/src/libscotch/arch.h new5/src/libscotch/arch.h
+*** src/src/libscotch/arch.h	2009-04-28 08:11:27.000000000 -0700
+--- new5/src/libscotch/arch.h	2010-07-21 17:13:15.600257237 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_hcub.c new5/src/libscotch/arch_hcub.c
+*** src/src/libscotch/arch_hcub.c	2008-05-22 06:44:41.000000000 -0700
+--- new5/src/libscotch/arch_hcub.c	2010-07-21 17:13:15.602257251 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_hcub.h new5/src/libscotch/arch_hcub.h
+*** src/src/libscotch/arch_hcub.h	2008-05-22 06:44:41.000000000 -0700
+--- new5/src/libscotch/arch_hcub.h	2010-07-21 17:13:15.604257265 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_mesh.c new5/src/libscotch/arch_mesh.c
+*** src/src/libscotch/arch_mesh.c	2008-05-22 06:44:41.000000000 -0700
+--- new5/src/libscotch/arch_mesh.c	2010-07-21 17:13:15.607257286 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_mesh.h new5/src/libscotch/arch_mesh.h
+*** src/src/libscotch/arch_mesh.h	2008-05-22 06:44:41.000000000 -0700
+--- new5/src/libscotch/arch_mesh.h	2010-07-21 17:13:15.610257307 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_tleaf.c new5/src/libscotch/arch_tleaf.c
+*** src/src/libscotch/arch_tleaf.c	2008-05-22 06:44:41.000000000 -0700
+--- new5/src/libscotch/arch_tleaf.c	2010-07-21 17:13:15.612257320 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_tleaf.h new5/src/libscotch/arch_tleaf.h
+*** src/src/libscotch/arch_tleaf.h	2008-05-22 06:44:41.000000000 -0700
+--- new5/src/libscotch/arch_tleaf.h	2010-07-21 17:13:15.615257341 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_torus.c new5/src/libscotch/arch_torus.c
+*** src/src/libscotch/arch_torus.c	2008-05-22 06:44:41.000000000 -0700
+--- new5/src/libscotch/arch_torus.c	2010-07-21 17:13:15.618257362 -0700
+***************
+*** 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 -rc src/src/libscotch/arch_torus.h new5/src/libscotch/arch_torus.h
+*** src/src/libscotch/arch_torus.h	2008-05-22 06:44:41.000000000 -0700
+--- new5/src/libscotch/arch_torus.h	2010-07-21 17:13:15.620257376 -0700
+***************
+*** 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 -rc src/src/libscotch/common.c new5/src/libscotch/common.c
+*** src/src/libscotch/common.c	2008-05-22 06:44:41.000000000 -0700
+--- new5/src/libscotch/common.c	2010-07-21 17:13:15.622257390 -0700
+***************
+*** 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 -rc src/src/libscotch/common.h new5/src/libscotch/common.h
+*** src/src/libscotch/common.h	2009-02-06 14:20:55.000000000 -0800
+--- new5/src/libscotch/common.h	2010-07-21 17:15:06.061025001 -0700
+***************
+*** 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 ----
+***************
+*** 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 -rc src/src/libscotch/common_integer.c new5/src/libscotch/common_integer.c
+*** src/src/libscotch/common_integer.c	2009-01-21 01:32:32.000000000 -0800
+--- new5/src/libscotch/common_integer.c	2010-07-21 17:13:15.628257432 -0700
+***************
+*** 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 -rc src/src/libscotch/common_memory.c new5/src/libscotch/common_memory.c
+*** src/src/libscotch/common_memory.c	2009-01-03 02:16:11.000000000 -0800
+--- new5/src/libscotch/common_memory.c	2010-07-21 17:13:15.630257445 -0700
+***************
+*** 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 -rc src/src/libscotch/dummysizes.c new5/src/libscotch/dummysizes.c
+*** src/src/libscotch/dummysizes.c	2009-05-09 16:08:02.000000000 -0700
+--- new5/src/libscotch/dummysizes.c	2010-07-21 17:13:15.633257466 -0700
+***************
+*** 267,271 ****
+--- 267,273 ----
+    }
+  #endif /* SCOTCH_DEBUG_MAIN1 */
+  
++ #ifndef MATLAB
+    exit (0);
++ #endif /* MATLAB */
+  }
+diff -rc src/src/libscotch/graph.c new5/src/libscotch/graph.c
+*** src/src/libscotch/graph.c	2008-05-22 06:44:42.000000000 -0700
+--- new5/src/libscotch/graph.c	2010-07-21 17:13:15.635257480 -0700
+***************
+*** 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 -rc src/src/libscotch/graph.h new5/src/libscotch/graph.h
+*** src/src/libscotch/graph.h	2008-06-01 02:49:11.000000000 -0700
+--- new5/src/libscotch/graph.h	2010-07-21 17:13:15.637257494 -0700
+***************
+*** 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 -rc src/src/libscotch/graph_io.c new5/src/libscotch/graph_io.c
+*** src/src/libscotch/graph_io.c	2008-05-22 06:44:42.000000000 -0700
+--- new5/src/libscotch/graph_io.c	2010-07-21 17:13:15.639257508 -0700
+***************
+*** 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 -rc src/src/libscotch/graph_io_scot.c new5/src/libscotch/graph_io_scot.c
+*** src/src/libscotch/graph_io_scot.c	2008-05-22 06:44:42.000000000 -0700
+--- new5/src/libscotch/graph_io_scot.c	2010-07-21 17:13:15.641257522 -0700
+***************
+*** 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 -rc src/src/libscotch/library_arch.c new5/src/libscotch/library_arch.c
+*** src/src/libscotch/library_arch.c	2008-05-22 06:44:42.000000000 -0700
+--- new5/src/libscotch/library_arch.c	2010-07-21 17:13:15.643257536 -0700
+***************
+*** 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 -rc src/src/libscotch/library_arch_f.c new5/src/libscotch/library_arch_f.c
+*** src/src/libscotch/library_arch_f.c	2008-05-22 06:44:42.000000000 -0700
+--- new5/src/libscotch/library_arch_f.c	2010-07-21 17:13:15.645257550 -0700
+***************
+*** 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 -rc src/src/libscotch/library_error_exit.c new5/src/libscotch/library_error_exit.c
+*** src/src/libscotch/library_error_exit.c	2009-01-20 00:36:33.000000000 -0800
+--- new5/src/libscotch/library_error_exit.c	2010-07-21 17:13:15.648257570 -0700
+***************
+*** 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 -rc src/src/libscotch/library_graph.c new5/src/libscotch/library_graph.c
+*** src/src/libscotch/library_graph.c	2008-05-22 07:28:12.000000000 -0700
+--- new5/src/libscotch/library_graph.c	2010-07-21 17:13:15.650257584 -0700
+***************
+*** 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 -rc src/src/libscotch/library_graph_f.c new5/src/libscotch/library_graph_f.c
+*** src/src/libscotch/library_graph_f.c	2008-05-22 06:44:43.000000000 -0700
+--- new5/src/libscotch/library_graph_f.c	2010-07-21 17:13:15.652257598 -0700
+***************
+*** 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 -rc src/src/libscotch/library_graph_map.c new5/src/libscotch/library_graph_map.c
+*** src/src/libscotch/library_graph_map.c	2008-09-28 04:04:05.000000000 -0700
+--- new5/src/libscotch/library_graph_map.c	2010-07-21 17:13:15.654257612 -0700
+***************
+*** 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 -rc src/src/libscotch/library_graph_map_f.c new5/src/libscotch/library_graph_map_f.c
+*** src/src/libscotch/library_graph_map_f.c	2008-06-28 03:44:26.000000000 -0700
+--- new5/src/libscotch/library_graph_map_f.c	2010-07-21 17:13:15.656257626 -0700
+***************
+*** 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 -rc src/src/libscotch/library.h new5/src/libscotch/library.h
+*** src/src/libscotch/library.h	2009-05-09 16:08:03.000000000 -0700
+--- new5/src/libscotch/library.h	2010-07-21 17:13:15.660257654 -0700
+***************
+*** 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 -rc src/src/libscotch/Makefile new5/src/libscotch/Makefile
+*** src/src/libscotch/Makefile	2009-05-09 16:08:04.000000000 -0700
+--- new5/src/libscotch/Makefile	2010-07-21 17:13:15.665257689 -0700
+***************
+*** 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 -rc src/src/libscotch/mapping.h new5/src/libscotch/mapping.h
+*** src/src/libscotch/mapping.h	2008-10-27 08:27:47.000000000 -0700
+--- new5/src/libscotch/mapping.h	2010-07-21 17:13:15.667257702 -0700
+***************
+*** 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 -rc src/src/libscotch/mapping_io.c new5/src/libscotch/mapping_io.c
+*** src/src/libscotch/mapping_io.c	2008-05-22 06:44:43.000000000 -0700
+--- new5/src/libscotch/mapping_io.c	2010-07-21 17:13:15.670257723 -0700
+***************
+*** 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 -rc src/src/libscotch/mesh_io_scot.c new5/src/libscotch/mesh_io_scot.c
+*** src/src/libscotch/mesh_io_scot.c	2008-05-22 06:44:43.000000000 -0700
+--- new5/src/libscotch/mesh_io_scot.c	2010-07-21 17:13:15.672257737 -0700
+***************
+*** 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 -rc src/src/libscotch/module.h new5/src/libscotch/module.h
+*** src/src/libscotch/module.h	2009-04-26 23:07:14.000000000 -0700
+--- new5/src/libscotch/module.h	2010-07-21 17:13:15.675257758 -0700
+***************
+*** 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 -rc src/src/libscotch/parser_ll.l new5/src/libscotch/parser_ll.l
+*** src/src/libscotch/parser_ll.l	2008-05-22 06:44:43.000000000 -0700
+--- new5/src/libscotch/parser_ll.l	2010-07-21 17:13:15.677257772 -0700
+***************
+*** 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 -rc src/src/libscotch/parser_yy.y new5/src/libscotch/parser_yy.y
+*** src/src/libscotch/parser_yy.y	2008-10-22 15:12:48.000000000 -0700
+--- new5/src/libscotch/parser_yy.y	2010-07-21 17:13:15.679257786 -0700
+***************
+*** 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 -rc src/src/libscotch/vgraph_separate_vw.c new5/src/libscotch/vgraph_separate_vw.c
+*** src/src/libscotch/vgraph_separate_vw.c	2008-05-22 06:44:43.000000000 -0700
+--- new5/src/libscotch/vgraph_separate_vw.c	2010-07-21 17:13:15.682257807 -0700
+***************
+*** 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 -rc src/src/Makefile new5/src/Makefile
+*** src/src/Makefile	2008-09-15 05:50:51.000000000 -0700
+--- new5/src/Makefile	2010-07-21 17:13:15.684257821 -0700
+***************
+*** 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 new5/src: Makefile.inc
+diff -rc src/src/scotch/gmap.h new5/src/scotch/gmap.h
+*** src/src/scotch/gmap.h	2008-06-18 11:05:17.000000000 -0700
+--- new5/src/scotch/gmap.h	2010-07-21 17:13:15.686257834 -0700
+***************
+*** 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 new5/src/scotch: gmap_mex.c
+Only in new5/src/scotch: gmapx.c
+diff -rc src/src/scotch/Makefile new5/src/scotch/Makefile
+*** src/src/scotch/Makefile	2009-04-27 02:19:43.000000000 -0700
+--- new5/src/scotch/Makefile	2010-07-21 17:13:15.689257855 -0700
+***************
+*** 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/trunk-jpl-damage/externalpackages/scotch/scotch_README.txt
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/scotch/scotch_README.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/scotch/scotch_README.txt	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/scotch/scotch_jes_notes.txt
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/scotch/scotch_jes_notes.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/scotch/scotch_jes_notes.txt	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/shapelib/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/shapelib/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/shapelib/install.sh	(revision 11330)
@@ -0,0 +1,50 @@
+#!/bin/bash
+
+# Some cleanup
+rm -rf shapelib-1.2.10
+rm -rf src 
+rm -rf install 
+mkdir src install 
+
+# 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 [ -z $1 ]; 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/trunk-jpl-damage/externalpackages/shapelib/shapelib.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/shapelib/shapelib.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/shapelib/shapelib.patch	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/slepc/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/slepc/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/slepc/install.sh	(revision 11330)
@@ -0,0 +1,21 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install slepc-2.3.2
+mkdir install
+
+#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 [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
Index: /issm/trunk-jpl-damage/externalpackages/ssh/README
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/ssh/README	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/ssh/README	(revision 11330)
@@ -0,0 +1,6 @@
+These two command line tools are taken from the Putty web page: 
+http://www.chiark.greenend.org.uk/~sgtatham/putty
+
+These two tools are used instead of ssh and scp (the ones that ship with cygwin),
+because ssh and scp do not work when called directly from matlab using the 'system' 
+command.
Index: /issm/trunk-jpl-damage/externalpackages/swig/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/swig/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/swig/install.sh	(revision 11330)
@@ -0,0 +1,26 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install
+rm -rf swig-2.0.4
+mkdir install
+
+#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_TIER/externalpackages/pcre/install/pcre.h  ./Source/Include/
+#cp $ISSM_TIER/externalpackages/pcre/install/.libs/*  ./Source/Include/
+export CFLAGS="$CFLAGS -I$ISSM_TIER/externalpackages/pcre/install"
+export LDFLAGS="-L$ISSM_TIER/externalpackages/pcre/install/.libs/"
+export LIBS="-lpcre"
+#Configure doxygen
+./configure \
+ --prefix="$ISSM_TIER/externalpackages/python/install" \
+ --with-pcre-prefix="$ISSM_TIER/externalpackages/pcre/install" \
+ --with-pcre-exec-prefix="$ISSM_TIER/externalpackages/pcre/install"
+make 
+make install
Index: /issm/trunk-jpl-damage/externalpackages/tao/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/tao/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/tao/install.sh	(revision 11330)
@@ -0,0 +1,18 @@
+#!/bin/bash
+#wget http://www.mcs.anl.gov/research/projects/tao/download/tao-2.0.tar.gz
+
+#Some cleanup
+rm -rf install tao-2.0
+mkdir install
+
+#Untar 
+tar -zxvf  tao-2.0.tar.gz
+
+#move into place
+mv tao-2.0/* install/
+rm -rf tao-2.0
+cd install
+export TAO_DIR="$ISSM_TIER/externalpackages/tao/install/"
+
+#petsc needs to be compiled with --with-clanguage=C++
+make
Index: /issm/trunk-jpl-damage/externalpackages/tex2im/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/tex2im/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/tex2im/install.sh	(revision 11330)
@@ -0,0 +1,12 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install
+mkdir install
+
+#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/trunk-jpl-damage/externalpackages/triangle/README
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/README	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/README	(revision 11330)
@@ -0,0 +1,2 @@
+Go pick up the correct configure.make  file in the config directory (according to your platform), 
+copy it to the top triangle directory, and run install.sh
Index: /issm/trunk-jpl-damage/externalpackages/triangle/configs/altix64/configure.make
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/configs/altix64/configure.make	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/configs/altix64/configure.make	(revision 11330)
@@ -0,0 +1,4 @@
+CC=gcc
+CSWITCHES = $(CFLAGS) -I$(MATLAB_DIR)/extern/include  -I$(MATLAB_DIR)/include -DLIN64 -fPIC
+OBJ_EXT=o
+LIB_EXT=a
Index: /issm/trunk-jpl-damage/externalpackages/triangle/configs/linux64/configure.make
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/configs/linux64/configure.make	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/configs/linux64/configure.make	(revision 11330)
@@ -0,0 +1,4 @@
+CC=gcc
+CSWITCHES = $(CFLAGS) -I$(MATLAB_DIR)/extern/include  -I$(MATLAB_DIR)/include -DLIN64 -fPIC
+OBJ_EXT=o
+LIB_EXT=a
Index: /issm/trunk-jpl-damage/externalpackages/triangle/configs/macosx32/configure.make
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/configs/macosx32/configure.make	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/configs/macosx32/configure.make	(revision 11330)
@@ -0,0 +1,5 @@
+CC=gcc -arch i386
+CSWITCHES = $(CFLAGS)  -I/usr/X11R6/include -L/usr/X11R6/lib -I$(MATLAB_DIR)/extern/include -fPIC -I$(MATLAB_DIR)/include
+TRILIBDEFS = -DTRILIBRARY
+OBJ_EXT=o
+LIB_EXT=a
Index: /issm/trunk-jpl-damage/externalpackages/triangle/configs/macosx64/configure.make
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/configs/macosx64/configure.make	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/configs/macosx64/configure.make	(revision 11330)
@@ -0,0 +1,5 @@
+CC=gcc -arch x86_64
+CSWITCHES = $(CFLAGS)  -I/usr/X11R6/include -L/usr/X11R6/lib -I$(MATLAB_DIR)/extern/include -fPIC -I$(MATLAB_DIR)/include
+TRILIBDEFS = -DTRILIBRARY
+OBJ_EXT=o
+LIB_EXT=a
Index: /issm/trunk-jpl-damage/externalpackages/triangle/configs/pleiades/configure.make
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/configs/pleiades/configure.make	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/configs/pleiades/configure.make	(revision 11330)
@@ -0,0 +1,4 @@
+CC=gcc
+CSWITCHES = $(CFLAGS) -I$(MATLAB_DIR)/extern/include  -I$(MATLAB_DIR)/include -DLIN64 -fPIC
+OBJ_EXT=o
+LIB_EXT=a
Index: /issm/trunk-jpl-damage/externalpackages/triangle/configs/win32/configure.make
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/configs/win32/configure.make	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/configs/win32/configure.make	(revision 11330)
@@ -0,0 +1,4 @@
+CC=icl
+CSWITCHES = $(CFLAGS) -I$(MATLAB_DIR)/extern/include  -I$(MATLAB_DIR)/include -DWIN32
+OBJ_EXT=obj
+LIB_EXT=a
Index: /issm/trunk-jpl-damage/externalpackages/triangle/install-altix64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/install-altix64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/install-altix64.sh	(revision 11330)
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/altix64/configure.make ./
+cp ../makefile ./
+
+#Patch triangle.c 
+patch triangle.c ../triangle.c.patch
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/trunk-jpl-damage/externalpackages/triangle/install-linux64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/install-linux64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/install-linux64.sh	(revision 11330)
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/linux64/configure.make ./
+cp ../makefile ./
+
+#Patch triangle.c 
+patch triangle.c ../triangle.c.patch
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/trunk-jpl-damage/externalpackages/triangle/install-macosx32.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/install-macosx32.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/install-macosx32.sh	(revision 11330)
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/macosx32/configure.make ./
+cp ../makefile ./
+
+#Patch triangle.c 
+patch triangle.c ../triangle.c.patch
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/trunk-jpl-damage/externalpackages/triangle/install-macosx64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/install-macosx64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/install-macosx64.sh	(revision 11330)
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/macosx64/configure.make ./
+cp ../makefile ./
+
+#Patch triangle.c 
+patch triangle.c ../triangle.c.patch
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/trunk-jpl-damage/externalpackages/triangle/install-pleiades.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/install-pleiades.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/install-pleiades.sh	(revision 11330)
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/pleiades/configure.make ./
+cp ../makefile ./
+
+#Patch triangle.c 
+patch triangle.c ../triangle.c.patch
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/trunk-jpl-damage/externalpackages/triangle/install-win32.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/install-win32.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/install-win32.sh	(revision 11330)
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/win32/configure.make ./
+cp ../makefile ./
+
+#Patch triangle.c 
+patch triangle.c ../triangle.c.patch
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/trunk-jpl-damage/externalpackages/triangle/makefile
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/makefile	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/makefile	(revision 11330)
@@ -0,0 +1,22 @@
+#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)
+	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/trunk-jpl-damage/externalpackages/triangle/triangle.c.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/triangle.c.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/triangle.c.patch	(revision 11330)
@@ -0,0 +1,164 @@
+0a1,10
+> /*Notes for the Ice code: 
+>  * to be able to compile Triangle within a mex function that can run within 
+>  * matlab, we had to change the allocation routine trimalloc, as well as the 
+>  * double precision activation in exactinit(); The rest is not changed. 
+>  * We also created the ice_makefile to compile Triangle into a library. */
+> #include <mat.h>
+> #include <matrix.h>
+> #define ANSI_DECLARATORS
+> #define NO_TIMER
+> 
+347a358
+> #ifndef _WIN_
+348a360
+> #endif
+641d652
+< 
+817a829,922
+> /*Some missing prototypes: */
+> int scale_expansion_zeroelim(int elen, REAL *e, REAL b, REAL *h);
+> int fast_expansion_sum_zeroelim(int elen, REAL *e, int flen, REAL *f, REAL *h);
+> void poolzero(struct memorypool *pool);
+> int triunsuitable(vertex triorg, vertex tridest, vertex triapex, REAL area);
+> triangle *triangletraverse(struct mesh *m);
+> void pooldeinit(struct memorypool *pool);
+> void printtriangle(struct mesh *m, struct behavior *b, struct otri *t);
+> VOID *poolalloc(struct memorypool *pool);
+> void enqueuebadtriang(struct mesh *m, struct behavior *b,
+>                       struct badtriang *badtri);
+> void triangulatepolygon(struct mesh *m, struct behavior *b,
+>                         struct otri *firstedge, struct otri *lastedge,
+>                         int edgecount, int doflip, int triflaws);
+> void triangledealloc(struct mesh *m, triangle *dyingtriangle);
+> void unflip(struct mesh *m, struct behavior *b, struct otri *flipedge);
+> void vertexmedian(vertex *sortarray, int arraysize, int median, int axis);
+> REAL counterclockwiseadapt(vertex pa, vertex pb, vertex pc, REAL detsum);
+> REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent);
+> void enqueuebadtri(struct mesh *m, struct behavior *b, struct otri *enqtri,
+>                    REAL minedge, vertex enqapex, vertex enqorg, vertex enqdest);
+> void alternateaxes(vertex *sortarray, int arraysize, int axis);
+> REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent);
+> void maketriangle(struct mesh *m, struct behavior *b, struct otri *newotri);
+> REAL counterclockwise(struct mesh *m, struct behavior *b,
+>                       vertex pa, vertex pb, vertex pc);
+> vertex vertextraverse(struct mesh *m);
+> void mergehulls(struct mesh *m, struct behavior *b, struct otri *farleft,
+>                 struct otri *innerleft, struct otri *innerright,
+>                 struct otri *farright, int axis);
+> REAL incircle(struct mesh *m, struct behavior *b,
+>               vertex pa, vertex pb, vertex pc, vertex pd);
+> void poolrestart(struct memorypool *pool);
+> void trifree(VOID *memptr);
+> struct splaynode *splay(struct mesh *m, struct splaynode *splaytree,
+>                         vertex searchpoint, struct otri *searchtri);
+> void eventheapdelete(struct event **heap, int heapsize, int eventnum);
+> void eventheapdelete(struct event **heap, int heapsize, int eventnum);
+> void flip(struct mesh *m, struct behavior *b, struct otri *flipedge);
+> void check4deadevent(struct otri *checktri, struct event **freeevents,
+>                      struct event **eventheap, int *heapsize);
+> REAL orient3d(struct mesh *m, struct behavior *b,
+>               vertex pa, vertex pb, vertex pc, vertex pd,
+>               REAL aheight, REAL bheight, REAL cheight, REAL dheight);
+> REAL circletop(struct mesh *m, vertex pa, vertex pb, vertex pc, REAL ccwabc);
+> void poolinit(struct memorypool *pool, int bytecount, int itemcount,
+>               int firstitemcount, int alignment);
+> void eventheapinsert(struct event **heap, int heapsize, struct event *newevent);
+> int rightofhyperbola(struct mesh *m, struct otri *fronttri, vertex newsite);
+> void insertsubseg(struct mesh *m, struct behavior *b, struct otri *tri,
+>                   int subsegmark);
+> int scoutsegment(struct mesh *m, struct behavior *b, struct otri *searchtri,
+>                  vertex endpoint2, int newmark);
+> vertex getvertex(struct mesh *m, struct behavior *b, int number);
+> void internalerror();
+> unsigned long randomnation(unsigned int choices);
+> struct splaynode *splayinsert(struct mesh *m, struct splaynode *splayroot,
+>                               struct otri *newkey, vertex searchpoint);
+> void delaunayfixup(struct mesh *m, struct behavior *b,
+>                    struct otri *fixuptri, int leftside);
+> void traversalinit(struct memorypool *pool);
+> enum insertvertexresult insertvertex(struct mesh *m, struct behavior *b,
+>                                      vertex newvertex, struct otri *searchtri,
+>                                      struct osub *splitseg,
+>                                      int segmentflaws, int triflaws);
+> void conformingedge(struct mesh *m, struct behavior *b,
+>                     vertex endpoint1, vertex endpoint2, int newmark);
+> enum finddirectionresult finddirection(struct mesh *m, struct behavior *b,
+>                                        struct otri *searchtri,
+>                                        vertex searchpoint);
+> VOID *traverse(struct memorypool *pool);
+> void deletevertex(struct mesh *m, struct behavior *b, struct otri *deltri);
+> void pooldealloc(struct memorypool *pool, VOID *dyingitem);
+> int checkseg4encroach(struct mesh *m, struct behavior *b,
+>                       struct osub *testsubseg);
+> void badsubsegdealloc(struct mesh *m, struct badsubseg *dyingseg);
+> void vertexdealloc(struct mesh *m, vertex dyingvertex);
+> void vertexsort(vertex *sortarray, int arraysize);
+> void tallyencs(struct mesh *m, struct behavior *b);
+> void splittriangle(struct mesh *m, struct behavior *b,
+>                    struct badtriang *badtri);
+> subseg *subsegtraverse(struct mesh *m);
+> enum locateresult locate(struct mesh *m, struct behavior *b,
+>                          vertex searchpoint, struct otri *searchtri);
+> void writenodes(struct mesh *m, struct behavior *b, REAL **pointlist,
+>                 REAL **pointattriblist, int **pointmarkerlist);
+> void writevoronoi(struct mesh *m, struct behavior *b, REAL **vpointlist,
+>                   REAL **vpointattriblist, int **vpointmarkerlist,
+>                   int **vedgelist, int **vedgemarkerlist, REAL **vnormlist);
+> void writeneighbors(struct mesh *m, struct behavior *b, int **neighborlist);
+> void testtriangle(struct mesh *m, struct behavior *b, struct otri *testtri);
+> void triangleinit(struct mesh *m);
+> 
+> 
+1408a1514
+> void triexit(int status);
+1410d1515
+< #ifdef ANSI_DECLARATORS
+1412,1416d1516
+< #else /* not ANSI_DECLARATORS */
+< void triexit(status)
+< int status;
+< #endif /* not ANSI_DECLARATORS */
+< 
+1421c1521
+< #ifdef ANSI_DECLARATORS
+---
+> VOID *trimalloc(int size);
+1423,1427d1522
+< #else /* not ANSI_DECLARATORS */
+< VOID *trimalloc(size)
+< int size;
+< #endif /* not ANSI_DECLARATORS */
+< 
+1431c1526,1527
+<   memptr = (VOID *) malloc((unsigned int) size);
+---
+>   memptr = (VOID *) mxMalloc((unsigned int) size);
+>   //memptr = (VOID *) malloc((unsigned int) size);
+1447c1543,1544
+<   free(memptr);
+---
+>   //free(memptr);
+>   mxFree(memptr);
+3665,3670c3762,3767
+< void printtriangle(struct mesh *m, struct behavior *b, struct otri *t)
+< #else /* not ANSI_DECLARATORS */
+< void printtriangle(m, b, t)
+< struct mesh *m;
+< struct behavior *b;
+< struct otri *t;
+---
+> void printtriangle(struct mesh *m, struct behavior *b, struct otri *t){
+> //#else /* not ANSI_DECLARATORS */
+> //void printtriangle(m, b, t)
+> //struct mesh *m;
+> //struct behavior *b;
+> //struct otri *t;
+3673c3770
+< {
+---
+> //{
+4910c5007
+<   _FPU_SETCW(cword);
+---
+>   //_FPU_SETCW(cword); //taken care of by Matlab
Index: /issm/trunk-jpl-damage/externalpackages/triangle/triangle.h
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/triangle.h	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/triangle.h	(revision 11330)
@@ -0,0 +1,291 @@
+/*****************************************************************************/
+/*                                                                           */
+/*  (triangle.h)                                                             */
+/*                                                                           */
+/*  Include file for programs that call Triangle.                            */
+/*                                                                           */
+/*  Accompanies Triangle Version 1.6                                         */
+/*  July 28, 2005                                                            */
+/*                                                                           */
+/*  Copyright 1996, 2005                                                     */
+/*  Jonathan Richard Shewchuk                                                */
+/*  2360 Woolsey #H                                                          */
+/*  Berkeley, California  94705-1927                                         */
+/*  jrs@cs.berkeley.edu                                                      */
+/*                                                                           */
+/*****************************************************************************/
+
+/*****************************************************************************/
+/*                                                                           */
+/*  How to call Triangle from another program                                */
+/*                                                                           */
+/*                                                                           */
+/*  If you haven't read Triangle's instructions (run "triangle -h" to read   */
+/*  them), you won't understand what follows.                                */
+/*                                                                           */
+/*  Triangle must be compiled into an object file (triangle.o) with the      */
+/*  TRILIBRARY symbol defined (generally by using the -DTRILIBRARY compiler  */
+/*  switch).  The makefile included with Triangle will do this for you if    */
+/*  you run "make trilibrary".  The resulting object file can be called via  */
+/*  the procedure triangulate().                                             */
+/*                                                                           */
+/*  If the size of the object file is important to you, you may wish to      */
+/*  generate a reduced version of triangle.o.  The REDUCED symbol gets rid   */
+/*  of all features that are primarily of research interest.  Specifically,  */
+/*  the -DREDUCED switch eliminates Triangle's -i, -F, -s, and -C switches.  */
+/*  The CDT_ONLY symbol gets rid of all meshing algorithms above and beyond  */
+/*  constrained Delaunay triangulation.  Specifically, the -DCDT_ONLY switch */
+/*  eliminates Triangle's -r, -q, -a, -u, -D, -Y, -S, and -s switches.       */
+/*                                                                           */
+/*  IMPORTANT:  These definitions (TRILIBRARY, REDUCED, CDT_ONLY) must be    */
+/*  made in the makefile or in triangle.c itself.  Putting these definitions */
+/*  in this file (triangle.h) will not create the desired effect.            */
+/*                                                                           */
+/*                                                                           */
+/*  The calling convention for triangulate() follows.                        */
+/*                                                                           */
+/*      void triangulate(triswitches, in, out, vorout)                       */
+/*      char *triswitches;                                                   */
+/*      struct triangulateio *in;                                            */
+/*      struct triangulateio *out;                                           */
+/*      struct triangulateio *vorout;                                        */
+/*                                                                           */
+/*  `triswitches' is a string containing the command line switches you wish  */
+/*  to invoke.  No initial dash is required.  Some suggestions:              */
+/*                                                                           */
+/*  - You'll probably find it convenient to use the `z' switch so that       */
+/*    points (and other items) are numbered from zero.  This simplifies      */
+/*    indexing, because the first item of any type always starts at index    */
+/*    [0] of the corresponding array, whether that item's number is zero or  */
+/*    one.                                                                   */
+/*  - You'll probably want to use the `Q' (quiet) switch in your final code, */
+/*    but you can take advantage of Triangle's printed output (including the */
+/*    `V' switch) while debugging.                                           */
+/*  - If you are not using the `q', `a', `u', `D', `j', or `s' switches,     */
+/*    then the output points will be identical to the input points, except   */
+/*    possibly for the boundary markers.  If you don't need the boundary     */
+/*    markers, you should use the `N' (no nodes output) switch to save       */
+/*    memory.  (If you do need boundary markers, but need to save memory, a  */
+/*    good nasty trick is to set out->pointlist equal to in->pointlist       */
+/*    before calling triangulate(), so that Triangle overwrites the input    */
+/*    points with identical copies.)                                         */
+/*  - The `I' (no iteration numbers) and `g' (.off file output) switches     */
+/*    have no effect when Triangle is compiled with TRILIBRARY defined.      */
+/*                                                                           */
+/*  `in', `out', and `vorout' are descriptions of the input, the output,     */
+/*  and the Voronoi output.  If the `v' (Voronoi output) switch is not used, */
+/*  `vorout' may be NULL.  `in' and `out' may never be NULL.                 */
+/*                                                                           */
+/*  Certain fields of the input and output structures must be initialized,   */
+/*  as described below.                                                      */
+/*                                                                           */
+/*****************************************************************************/
+
+/*****************************************************************************/
+/*                                                                           */
+/*  The `triangulateio' structure.                                           */
+/*                                                                           */
+/*  Used to pass data into and out of the triangulate() procedure.           */
+/*                                                                           */
+/*                                                                           */
+/*  Arrays are used to store points, triangles, markers, and so forth.  In   */
+/*  all cases, the first item in any array is stored starting at index [0].  */
+/*  However, that item is item number `1' unless the `z' switch is used, in  */
+/*  which case it is item number `0'.  Hence, you may find it easier to      */
+/*  index points (and triangles in the neighbor list) if you use the `z'     */
+/*  switch.  Unless, of course, you're calling Triangle from a Fortran       */
+/*  program.                                                                 */
+/*                                                                           */
+/*  Description of fields (except the `numberof' fields, which are obvious): */
+/*                                                                           */
+/*  `pointlist':  An array of point coordinates.  The first point's x        */
+/*    coordinate is at index [0] and its y coordinate at index [1], followed */
+/*    by the coordinates of the remaining points.  Each point occupies two   */
+/*    REALs.                                                                 */
+/*  `pointattributelist':  An array of point attributes.  Each point's       */
+/*    attributes occupy `numberofpointattributes' REALs.                     */
+/*  `pointmarkerlist':  An array of point markers; one int per point.        */
+/*                                                                           */
+/*  `trianglelist':  An array of triangle corners.  The first triangle's     */
+/*    first corner is at index [0], followed by its other two corners in     */
+/*    counterclockwise order, followed by any other nodes if the triangle    */
+/*    represents a nonlinear element.  Each triangle occupies                */
+/*    `numberofcorners' ints.                                                */
+/*  `triangleattributelist':  An array of triangle attributes.  Each         */
+/*    triangle's attributes occupy `numberoftriangleattributes' REALs.       */
+/*  `trianglearealist':  An array of triangle area constraints; one REAL per */
+/*    triangle.  Input only.                                                 */
+/*  `neighborlist':  An array of triangle neighbors; three ints per          */
+/*    triangle.  Output only.                                                */
+/*                                                                           */
+/*  `segmentlist':  An array of segment endpoints.  The first segment's      */
+/*    endpoints are at indices [0] and [1], followed by the remaining        */
+/*    segments.  Two ints per segment.                                       */
+/*  `segmentmarkerlist':  An array of segment markers; one int per segment.  */
+/*                                                                           */
+/*  `holelist':  An array of holes.  The first hole's x and y coordinates    */
+/*    are at indices [0] and [1], followed by the remaining holes.  Two      */
+/*    REALs per hole.  Input only, although the pointer is copied to the     */
+/*    output structure for your convenience.                                 */
+/*                                                                           */
+/*  `regionlist':  An array of regional attributes and area constraints.     */
+/*    The first constraint's x and y coordinates are at indices [0] and [1], */
+/*    followed by the regional attribute at index [2], followed by the       */
+/*    maximum area at index [3], followed by the remaining area constraints. */
+/*    Four REALs per area constraint.  Note that each regional attribute is  */
+/*    used only if you select the `A' switch, and each area constraint is    */
+/*    used only if you select the `a' switch (with no number following), but */
+/*    omitting one of these switches does not change the memory layout.      */
+/*    Input only, although the pointer is copied to the output structure for */
+/*    your convenience.                                                      */
+/*                                                                           */
+/*  `edgelist':  An array of edge endpoints.  The first edge's endpoints are */
+/*    at indices [0] and [1], followed by the remaining edges.  Two ints per */
+/*    edge.  Output only.                                                    */
+/*  `edgemarkerlist':  An array of edge markers; one int per edge.  Output   */
+/*    only.                                                                  */
+/*  `normlist':  An array of normal vectors, used for infinite rays in       */
+/*    Voronoi diagrams.  The first normal vector's x and y magnitudes are    */
+/*    at indices [0] and [1], followed by the remaining vectors.  For each   */
+/*    finite edge in a Voronoi diagram, the normal vector written is the     */
+/*    zero vector.  Two REALs per edge.  Output only.                        */
+/*                                                                           */
+/*                                                                           */
+/*  Any input fields that Triangle will examine must be initialized.         */
+/*  Furthermore, for each output array that Triangle will write to, you      */
+/*  must either provide space by setting the appropriate pointer to point    */
+/*  to the space you want the data written to, or you must initialize the    */
+/*  pointer to NULL, which tells Triangle to allocate space for the results. */
+/*  The latter option is preferable, because Triangle always knows exactly   */
+/*  how much space to allocate.  The former option is provided mainly for    */
+/*  people who need to call Triangle from Fortran code, though it also makes */
+/*  possible some nasty space-saving tricks, like writing the output to the  */
+/*  same arrays as the input.                                                */
+/*                                                                           */
+/*  Triangle will not free() any input or output arrays, including those it  */
+/*  allocates itself; that's up to you.  You should free arrays allocated by */
+/*  Triangle by calling the trifree() procedure defined below.  (By default, */
+/*  trifree() just calls the standard free() library procedure, but          */
+/*  applications that call triangulate() may replace trimalloc() and         */
+/*  trifree() in triangle.c to use specialized memory allocators.)           */
+/*                                                                           */
+/*  Here's a guide to help you decide which fields you must initialize       */
+/*  before you call triangulate().                                           */
+/*                                                                           */
+/*  `in':                                                                    */
+/*                                                                           */
+/*    - `pointlist' must always point to a list of points; `numberofpoints'  */
+/*      and `numberofpointattributes' must be properly set.                  */
+/*      `pointmarkerlist' must either be set to NULL (in which case all      */
+/*      markers default to zero), or must point to a list of markers.  If    */
+/*      `numberofpointattributes' is not zero, `pointattributelist' must     */
+/*      point to a list of point attributes.                                 */
+/*    - If the `r' switch is used, `trianglelist' must point to a list of    */
+/*      triangles, and `numberoftriangles', `numberofcorners', and           */
+/*      `numberoftriangleattributes' must be properly set.  If               */
+/*      `numberoftriangleattributes' is not zero, `triangleattributelist'    */
+/*      must point to a list of triangle attributes.  If the `a' switch is   */
+/*      used (with no number following), `trianglearealist' must point to a  */
+/*      list of triangle area constraints.  `neighborlist' may be ignored.   */
+/*    - If the `p' switch is used, `segmentlist' must point to a list of     */
+/*      segments, `numberofsegments' must be properly set, and               */
+/*      `segmentmarkerlist' must either be set to NULL (in which case all    */
+/*      markers default to zero), or must point to a list of markers.        */
+/*    - If the `p' switch is used without the `r' switch, then               */
+/*      `numberofholes' and `numberofregions' must be properly set.  If      */
+/*      `numberofholes' is not zero, `holelist' must point to a list of      */
+/*      holes.  If `numberofregions' is not zero, `regionlist' must point to */
+/*      a list of region constraints.                                        */
+/*    - If the `p' switch is used, `holelist', `numberofholes',              */
+/*      `regionlist', and `numberofregions' is copied to `out'.  (You can    */
+/*      nonetheless get away with not initializing them if the `r' switch is */
+/*      used.)                                                               */
+/*    - `edgelist', `edgemarkerlist', `normlist', and `numberofedges' may be */
+/*      ignored.                                                             */
+/*                                                                           */
+/*  `out':                                                                   */
+/*                                                                           */
+/*    - `pointlist' must be initialized (NULL or pointing to memory) unless  */
+/*      the `N' switch is used.  `pointmarkerlist' must be initialized       */
+/*      unless the `N' or `B' switch is used.  If `N' is not used and        */
+/*      `in->numberofpointattributes' is not zero, `pointattributelist' must */
+/*      be initialized.                                                      */
+/*    - `trianglelist' must be initialized unless the `E' switch is used.    */
+/*      `neighborlist' must be initialized if the `n' switch is used.  If    */
+/*      the `E' switch is not used and (`in->numberofelementattributes' is   */
+/*      not zero or the `A' switch is used), `elementattributelist' must be  */
+/*      initialized.  `trianglearealist' may be ignored.                     */
+/*    - `segmentlist' must be initialized if the `p' or `c' switch is used,  */
+/*      and the `P' switch is not used.  `segmentmarkerlist' must also be    */
+/*      initialized under these circumstances unless the `B' switch is used. */
+/*    - `edgelist' must be initialized if the `e' switch is used.            */
+/*      `edgemarkerlist' must be initialized if the `e' switch is used and   */
+/*      the `B' switch is not.                                               */
+/*    - `holelist', `regionlist', `normlist', and all scalars may be ignored.*/
+/*                                                                           */
+/*  `vorout' (only needed if `v' switch is used):                            */
+/*                                                                           */
+/*    - `pointlist' must be initialized.  If `in->numberofpointattributes'   */
+/*      is not zero, `pointattributelist' must be initialized.               */
+/*      `pointmarkerlist' may be ignored.                                    */
+/*    - `edgelist' and `normlist' must both be initialized.                  */
+/*      `edgemarkerlist' may be ignored.                                     */
+/*    - Everything else may be ignored.                                      */
+/*                                                                           */
+/*  After a call to triangulate(), the valid fields of `out' and `vorout'    */
+/*  will depend, in an obvious way, on the choice of switches used.  Note    */
+/*  that when the `p' switch is used, the pointers `holelist' and            */
+/*  `regionlist' are copied from `in' to `out', but no new space is          */
+/*  allocated; be careful that you don't free() the same array twice.  On    */
+/*  the other hand, Triangle will never copy the `pointlist' pointer (or any */
+/*  others); new space is allocated for `out->pointlist', or if the `N'      */
+/*  switch is used, `out->pointlist' remains uninitialized.                  */
+/*                                                                           */
+/*  All of the meaningful `numberof' fields will be properly set; for        */
+/*  instance, `numberofedges' will represent the number of edges in the      */
+/*  triangulation whether or not the edges were written.  If segments are    */
+/*  not used, `numberofsegments' will indicate the number of boundary edges. */
+/*                                                                           */
+/*****************************************************************************/
+typedef double REAL;
+typedef void VOID;
+
+extern "C" struct triangulateio {
+  REAL *pointlist;                                               /* In / out */
+  REAL *pointattributelist;                                      /* In / out */
+  int *pointmarkerlist;                                          /* In / out */
+  int numberofpoints;                                            /* In / out */
+  int numberofpointattributes;                                   /* In / out */
+
+  int *trianglelist;                                             /* In / out */
+  REAL *triangleattributelist;                                   /* In / out */
+  REAL *trianglearealist;                                         /* In only */
+  int *neighborlist;                                             /* Out only */
+  int numberoftriangles;                                         /* In / out */
+  int numberofcorners;                                           /* In / out */
+  int numberoftriangleattributes;                                /* In / out */
+
+  int *segmentlist;                                              /* In / out */
+  int *segmentmarkerlist;                                        /* In / out */
+  int numberofsegments;                                          /* In / out */
+
+  REAL *holelist;                        /* In / pointer to array copied out */
+  int numberofholes;                                      /* In / copied out */
+
+  REAL *regionlist;                      /* In / pointer to array copied out */
+  int numberofregions;                                    /* In / copied out */
+
+  int *edgelist;                                                 /* Out only */
+  int *edgemarkerlist;            /* Not used with Voronoi diagram; out only */
+  REAL *normlist;                /* Used only with Voronoi diagram; out only */
+  int numberofedges;                                             /* Out only */
+};
+
+#ifdef ANSI_DECLARATORS
+extern "C" void triangulate(char *, struct triangulateio *, struct triangulateio *,
+                 struct triangulateio *);
+extern "C" void trifree(VOID *memptr);
+#else /* not ANSI_DECLARATORS */
+void triangulate();
+void trifree();
+#endif /* not ANSI_DECLARATORS */
Index: /issm/trunk-jpl-damage/externalpackages/triangle/triangle.h.patch
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/triangle/triangle.h.patch	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/triangle/triangle.h.patch	(revision 11330)
@@ -0,0 +1,17 @@
+249a250,253
+> #ifndef REAL
+> typedef double REAL;
+> typedef void VOID;
+> #endif
+251c255
+< struct triangulateio {
+---
+> extern "C" struct triangulateio {
+283c287
+< void triangulate(char *, struct triangulateio *, struct triangulateio *,
+---
+> extern "C" void triangulate(char *, struct triangulateio *, struct triangulateio *,
+285c289
+< void trifree(VOID *memptr);
+---
+> extern "C" void trifree(VOID *memptr);
Index: /issm/trunk-jpl-damage/externalpackages/valgrind/README
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/valgrind/README	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/valgrind/README	(revision 11330)
@@ -0,0 +1,5 @@
+How to use valgrind to debug memory leaks. 
+Install valgrind (jut type valgrind.sh). 
+Compile the parallel code using -g -O0 as optoins (edit src/c/Makefile if necessary).
+Then set md.mem_debug=1, and run in parallel. Voila!
+The errlog will contain all the info spit out by valgrind.
Index: /issm/trunk-jpl-damage/externalpackages/valgrind/install-altix64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/valgrind/install-altix64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/valgrind/install-altix64.sh	(revision 11330)
@@ -0,0 +1,24 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install valgrind-3.7.0
+mkdir install
+
+#Untar 
+tar -jxvf  valgrind-3.7.0.tar.bz2
+
+#Move valgrind into install directory
+mv valgrind-3.7.0/* install
+rm -rf valgrind-3.7.0
+
+#configure
+cd install
+./configure --prefix="$ISSM_TIER/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/trunk-jpl-damage/externalpackages/valgrind/install-linux64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/valgrind/install-linux64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/valgrind/install-linux64.sh	(revision 11330)
@@ -0,0 +1,24 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install valgrind-3.7.0
+mkdir install
+
+#Untar 
+tar -jxvf  valgrind-3.7.0.tar.bz2
+
+#Move valgrind into install directory
+mv valgrind-3.7.0/* install
+rm -rf valgrind-3.7.0
+
+#configure
+cd install
+./configure  --prefix="$ISSM_TIER/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/trunk-jpl-damage/externalpackages/valgrind/install-macosx32.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/valgrind/install-macosx32.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/valgrind/install-macosx32.sh	(revision 11330)
@@ -0,0 +1,20 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install valgrind-3.7.0
+mkdir install
+
+#Untar 
+tar -jxvf  valgrind-3.7.0.tar.bz2
+
+#Move valgrind into install directory
+mv valgrind-3.7.0/* install
+rm -rf valgrind-3.7.0
+
+#configure
+cd install
+./configure  --prefix="$ISSM_TIER/externalpackages/valgrind/install" --enable-only32bit
+
+#Compile valgrind
+make  -j 4
+make install
Index: /issm/trunk-jpl-damage/externalpackages/valgrind/install-macosx64.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/valgrind/install-macosx64.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/valgrind/install-macosx64.sh	(revision 11330)
@@ -0,0 +1,20 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install valgrind-3.7.0
+mkdir install
+
+#Untar 
+tar -jxvf  valgrind-3.7.0.tar.bz2
+
+#Move valgrind into install directory
+mv valgrind-3.7.0/* install
+rm -rf valgrind-3.7.0
+
+#configure
+cd install
+./configure  --prefix="$ISSM_TIER/externalpackages/valgrind/install" --enable-only64bit
+
+#Compile valgrind
+make  -j 4
+make install
Index: /issm/trunk-jpl-damage/externalpackages/valgrind/install-win32.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/valgrind/install-win32.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/valgrind/install-win32.sh	(revision 11330)
@@ -0,0 +1,24 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install valgrind-3.7.0
+mkdir install
+
+#Untar 
+tar -jxvf  valgrind-3.7.0.tar.bz2
+
+#Move valgrind into install directory
+mv valgrind-3.7.0/* install
+rm -rf valgrind-3.7.0
+
+#configure
+cd install
+./configure  --prefix="$ISSM_TIER/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/trunk-jpl-damage/externalpackages/valgrind/issm.supp
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/valgrind/issm.supp	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/valgrind/issm.supp	(revision 11330)
@@ -0,0 +1,142 @@
+# 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/public/queue/ClusterScript.m,
+#      add: --gen-suppressions=all
+#   2. in the errlog, copy and paste the suppression log
+#      in this file.
+
+#General errors from MPI, Petsc
+#PETSC General {{{1
+{
+	petsc1general
+	  Memcheck:User
+	  fun:check_mem_is_defined_untyped
+	  fun:PMPI_Allreduce
+	  fun:MPI_ALLREDUCE
+	  fun:dmumps_276_
+	  fun:dmumps_
+	  fun:dmumps_f77_
+	  fun:dmumps_c
+	  fun:MatFactorNumeric_AIJMUMPS
+	  fun:MatLUFactorNumeric
+	  fun:PCSetUp_LU
+	  fun:PCSetUp
+	  fun:KSPSetUp
+}
+{
+	petsc2general
+	  Memcheck:User
+	  fun:check_mem_is_defined_untyped
+	  fun:PMPI_Bcast
+	  fun:PMPI_BCAST
+	  fun:dmumps_300_
+	  fun:dmumps_
+	  fun:dmumps_f77_
+	  fun:dmumps_c
+	  fun:MatFactorNumeric_AIJMUMPS
+	  fun:MatLUFactorNumeric
+	  fun:PCSetUp_LU
+	  fun:PCSetUp
+	  fun:KSPSetUp
+}
+{
+	petsc3general
+	  Memcheck:User
+	  fun:check_mem_is_defined_untyped
+	  fun:PMPI_Bcast
+	  fun:PMPI_BCAST
+	  fun:dmumps_
+	  fun:dmumps_f77_
+	  fun:dmumps_c
+	  fun:MatFactorNumeric_AIJMUMPS
+	  fun:MatLUFactorNumeric
+	  fun:PCSetUp_LU
+	  fun:PCSetUp
+	  fun:KSPSetUp
+	  fun:KSPSolve
+}
+{
+	petsc4firstcall
+	  Memcheck:User
+	  fun:check_mem_is_defined_untyped
+	  fun:walk_type
+	  fun:PMPI_Allreduce
+	  fun:MPIR_Get_contextid
+	  fun:MPIR_Comm_copy
+	  fun:PMPI_Comm_dup
+	  fun:PMPI_Comm_dup
+	  fun:PetscCommDuplicate
+	  fun:PetscHeaderCreate_Private
+}
+#}}}1
+#Dakota {{{1
+{
+   dakota1
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_ZNSs4_Rep9_S_createEmmRKSaIcE
+   fun:_ZNSs12_S_constructIPKcEEPcT_S3_RKSaIcESt20forward_iterator_tag
+   fun:_ZNSsC1EPKcRKSaIcE
+   fun:_ZN4JEGA10Algorithms17SOGAOperatorGroup4NameEv
+   fun:_Z41__static_initialization_and_destruction_0ii
+}
+{
+   dakota2
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_ZNSs4_Rep9_S_createEmmRKSaIcE
+   fun:_ZNSs12_S_constructIPKcEEPcT_S3_RKSaIcESt20forward_iterator_tag
+   fun:_ZNSsC1EPKcRKSaIcE
+   fun:_ZN4JEGA10Algorithms26FavorFeasibleOperatorGroup4NameEv
+   fun:_Z41__static_initialization_and_destruction_0ii
+}
+{
+   dakota3
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_ZNSs4_Rep9_S_createEmmRKSaIcE
+   fun:_ZNSs12_S_constructIPKcEEPcT_S3_RKSaIcESt20forward_iterator_tag
+   fun:_ZNSsC1EPKcRKSaIcE
+   fun:_ZN4JEGA10Algorithms17MOGAOperatorGroup4NameEv
+   fun:_Z41__static_initialization_and_destruction_0ii
+}
+{
+   dakota4
+   Memcheck:Leak
+   fun:_Znwm
+   fun:_ZNSs4_Rep9_S_createEmmRKSaIcE
+   fun:_ZNSs12_S_constructIPKcEEPcT_S3_RKSaIcESt20forward_iterator_tag
+   fun:_ZNSsC1EPKcRKSaIcE
+   fun:_ZN4JEGA10Algorithms28DominationCountOperatorGroup4NameEv
+   fun:_Z41__static_initialization_and_destruction_0ii
+}
+#}}}
+#Miscellaneous {{{1
+{
+	miscellaneous1
+	  Memcheck:Free
+	  fun:free
+	  obj:/lib64/libc-2.5.so
+	  obj:/lib64/libc-2.5.so
+	  fun:_vgnU_freeres
+	  fun:exit
+	  fun:(below main)
+}
+#}}}
+#Solution specific errors to ignore
+#solver_diagnostic_nonlinear{{{1
+{
+	petsc1diagnosticcore
+	  Memcheck:Cond
+	  fun:dmumps_
+	  fun:dmumps_f77_
+	  fun:dmumps_c
+	  fun:MatFactorNumeric_AIJMUMPS
+	  fun:MatLUFactorNumeric
+	  fun:PCSetUp_LU
+	  fun:PCSetUp
+	  fun:KSPSetUp
+	  fun:KSPSolve
+}
Index: /issm/trunk-jpl-damage/externalpackages/vim/addons/README
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/README	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/README	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/autoload/Align.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/autoload/Align.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/autoload/Align.vim	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/autoload/AlignMaps.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/autoload/AlignMaps.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/autoload/AlignMaps.vim	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/colors/issm_black.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/colors/issm_black.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/colors/issm_black.vim	(revision 11330)
@@ -0,0 +1,227 @@
+" ir_black color scheme
+" More at: http://blog.infinitered.com/entries/show/8
+
+
+" ********************************************************************************
+" Standard colors used in all ir_black themes:
+" Note, x:x:x are RGB values
+"
+"  normal: #f6f3e8
+" 
+"  string: #A8FF60  168:255:96                   
+"    string inner (punc, code, etc): #00A0A0  0:160:160
+"  number: #FF73FD  255:115:253                 
+"  comments: #7C7C7C  124:124:124
+"  keywords: #96CBFE  150:203:254             
+"  operators: white
+"  class: #FFFFB6  255:255:182
+"  method declaration name: #FFD2A7  255:210:167
+"  regular expression: #E9C062  233:192:98
+"    regexp alternate: #FF8000  255:128:0
+"    regexp alternate 2: #B18A3D  177:138:61
+"  variable: #C6C5FE  198:197:254
+"  
+" Misc colors:
+"  red color (used for whatever): #FF6C60   255:108:96 
+"     light red: #FFB6B0   255:182:176
+"
+"  brown: #E18964  good for special
+"
+"  lightpurpleish: #FFCCFF
+" 
+" Interface colors:
+"  background color: black
+"  cursor (where underscore is used): #FFA560  255:165:96
+"  cursor (where block is used): white
+"  visual selection: #1D1E2C  
+"  current line: #151515  21:21:21
+"  search selection: #07281C  7:40:28
+"  line number: #3D3D3D  61:61:61
+
+
+" ********************************************************************************
+" The following are the preferred 16 colors for your terminal
+"           Colors      Bright Colors
+" Black     #4E4E4E     #7C7C7C
+" Red       #FF6C60     #FFB6B0
+" Green     #A8FF60     #CEFFAB
+" Yellow    #FFFFB6     #FFFFCB
+" Blue      #96CBFE     #FFFFCB
+" Magenta   #FF73FD     #FF9CFE
+" Cyan      #C6C5FE     #DFDFFE
+" White     #EEEEEE     #FFFFFF
+
+
+" ********************************************************************************
+hi clear
+
+if exists("syntax_on")
+  syntax reset
+endif
+syntax on
+
+let colors_name = "issm_black"
+
+"                   GUI not used in terminal mode                     forground           background          style (reverse,bold,..)
+"hi Example         guifg=NONE        guibg=NONE        gui=NONE      ctermfg=NONE        ctermbg=NONE        cterm=NONE
+
+" General colors
+hi Normal           guifg=#f6f3e8     guibg=black       gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=NONE
+hi NonText          guifg=#070707     guibg=black       gui=NONE      ctermfg=129        ctermbg=NONE        cterm=NONE         "214 =orange
+
+hi Cursor           guifg=black       guibg=white       gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=reverse      "cursor (mouse)
+hi LineNr           guifg=#3D3D3D     guibg=black       gui=NONE      ctermfg=249        ctermbg=232         cterm=NONE         "line numbering gray/blak 
+
+hi VertSplit        guifg=#202020     guibg=#202020     gui=NONE      ctermfg=241        ctermbg=241         cterm=NONE         "vertical split
+hi StatusLine       guifg=#CCCCCC     guibg=#202020     gui=italic    ctermfg=241        ctermbg=87          cterm=NONE         "87 = cyan
+hi StatusLineNC     guifg=black       guibg=#202020     gui=NONE      ctermfg=87         ctermbg=241         cterm=NONE         "241 = dark gray
+
+hi Folded           guifg=#a0a8b0     guibg=#384048     gui=NONE      ctermfg=135        ctermbg=234         cterm=NONE         "folded 129 = violet ,234 Gray
+hi Title            guifg=#f6f3e8     guibg=NONE        gui=bold      ctermfg=NONE       ctermbg=NONE        cterm=NONE
+hi Visual           guifg=NONE        guibg=#262D51     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=reverse "visual 255 = white
+
+hi SpecialKey       guifg=#808080     guibg=#343434     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=NONE
+
+hi WildMenu         guifg=green       guibg=yellow      gui=NONE      ctermfg=black      ctermbg=yellow      cterm=NONE          "?????
+hi PmenuSbar        guifg=black       guibg=white       gui=NONE      ctermfg=black      ctermbg=magenta     cterm=NONE          "????
+"hi Ignore           guifg=gray        guibg=black       gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=NONE
+
+hi Error            guifg=white        guibg=NONE        gui=none ctermfg=255      ctermbg=129         cterm=NONE
+hi ErrorMsg         guifg=white       guibg=#FF6C60     gui=BOLD      ctermfg=255      ctermbg=129         cterm=NONE                   " 196 = red
+hi WarningMsg       guifg=white       guibg=#FF6C60     gui=BOLD      ctermfg=255      ctermbg=201         cterm=NONE                   "201 = magenta
+
+" Message displayed in lower left, such as --INSERT--
+hi ModeMsg          guifg=black       guibg=#C6C5FE     gui=BOLD      ctermfg=241      ctermbg=87        cterm=BOLD
+
+if version >= 700 " Vim 7.x specific colors
+  hi CursorLine     guifg=NONE        guibg=#121212     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=BOLD
+  hi CursorColumn   guifg=NONE        guibg=#121212     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=BOLD
+  hi MatchParen     guifg=#f6f3e8     guibg=#857b6f     gui=BOLD      ctermfg=87         ctermbg=241         cterm=BOLD,reverse  "matching parenthesis
+  hi Pmenu          guifg=#f6f3e8     guibg=#444444     gui=NONE      ctermfg=black      ctermbg=white         cterm=NONE "auto completion panel
+  hi PmenuSel       guifg=#000000     guibg=#cae682     gui=NONE      ctermfg=255        ctermbg=darkgray    cterm=NONE
+  hi Search         guifg=NONE        guibg=NONE        gui=underline ctermfg=black      ctermbg=220         cterm=NONE  "227 = yellow
+endif
+
+" Syntax highlighting
+hi Comment          guifg=#7C7C7C     guibg=NONE        gui=NONE      ctermfg=243         ctermbg=NONE        cterm=NONE
+hi String           guifg=#A8FF60     guibg=NONE        gui=NONE      ctermfg=120         ctermbg=NONE        cterm=NONE
+hi Number           guifg=#FF73FD     guibg=NONE        gui=NONE      ctermfg=201         ctermbg=NONE        cterm=NONE
+
+hi Keyword          guifg=#96CBFE     guibg=NONE        gui=NONE      ctermfg=red         ctermbg=NONE        cterm=NONE  " matlab function
+hi PreProc          guifg=#96CBFE     guibg=NONE        gui=NONE      ctermfg=red         ctermbg=NONE        cterm=NONE   " def undef include
+hi Conditional      guifg=#6699CC     guibg=NONE        gui=NONE      ctermfg=220         ctermbg=NONE        cterm=NONE  " if else end
+
+hi Todo             guifg=#8f8f8f     guibg=NONE        gui=NONE      ctermfg=214          ctermbg=NONE        cterm=NONE
+hi Constant         guifg=#99CC99     guibg=NONE        gui=NONE      ctermfg=196         ctermbg=NONE        cterm=NONE
+
+hi Identifier       guifg=#C6C5FE     guibg=NONE        gui=NONE      ctermfg=red         ctermbg=NONE        cterm=NONE
+hi Function         guifg=#FFD2A7     guibg=NONE        gui=NONE      ctermfg=69          ctermbg=NONE        cterm=NONE "functions 69 = pastel blue
+hi Type             guifg=#FFFFB6     guibg=NONE        gui=NONE      ctermfg=87         ctermbg=NONE        cterm=NONE "cterm matlab global
+hi Statement        guifg=#6699CC     guibg=NONE        gui=NONE      ctermfg=69          ctermbg=NONE        cterm=NONE " cd ls sed mv
+
+hi Special          guifg=#E18964     guibg=NONE        gui=NONE      ctermfg=202         ctermbg=NONE        cterm=NONE  " ; 202  = orange 
+hi Delimiter        guifg=#00A0A0     guibg=NONE        gui=NONE      ctermfg=NONE        ctermbg=NONE        cterm=NONE  " [ ]
+hi Operator         guifg=white       guibg=NONE        gui=NONE      ctermfg=202         ctermbg=NONE        cterm=NONE  " == &  178 = darkyellow
+
+hi Directory        guifg=white       guibg=NONE        gui=NONE      ctermfg=87          ctermbg=NONE        cterm=NONE  " == &  178 = darkyellow
+
+ "Specific for diff
+ hi DiffAdd      guifg=#ffff33 guibg=#404010 gui=bold term=none cterm=none ctermfg=black ctermbg=119
+ hi DiffChange                 guibg=#202020 gui=bold term=none cterm=none ctermfg=black ctermbg=228
+ hi DiffText     guifg=#3333ff guibg=#100040 gui=bold term=none cterm=none ctermfg=black ctermbg=178
+ hi DiffDelete   guifg=#ff0000 guibg=#401010 gui=bold term=none cterm=none ctermfg=black ctermbg=197
+ hi diffLine     guifg=#444444 guibg=bg gui=bold term=none cterm=bold ctermfg=darkgrey
+ hi diffOldLine  guifg=#444444 guibg=bg gui=none term=none cterm=none ctermfg=darkgrey
+ hi diffOldFile  guifg=#444444 guibg=bg gui=none term=none cterm=none ctermfg=darkgrey
+ hi diffNewFile  guifg=#444444 guibg=bg gui=none term=none cterm=none ctermfg=darkgrey
+ hi diffAdded    guifg=#80ff80 guibg=bg gui=none term=none cterm=none
+ hi diffRemoved  guifg=#ff0000 guibg=bg gui=none term=none cterm=none ctermfg=red
+ hi diffChanged  guifg=#0000ff guibg=bg gui=none term=none cterm=none ctermfg=blue
+
+hi link Character       Constant
+hi link Boolean         Constant
+hi link Float           Number
+hi link Repeat          Statement
+hi link Label           Statement
+hi link Exception       Statement
+hi link Include         PreProc
+hi link Define          PreProc
+hi link Macro           PreProc
+hi link PreCondit       PreProc
+hi link StorageClass    Type
+hi link Structure       Type
+hi link Typedef         Type
+hi link Tag             Special
+hi link SpecialChar     Special
+hi link SpecialComment  Special
+hi link Debug           Special
+
+
+" Special for Ruby
+hi rubyRegexp                  guifg=#B18A3D      guibg=NONE      gui=NONE      ctermfg=brown          ctermbg=NONE      cterm=NONE
+hi rubyRegexpDelimiter         guifg=#FF8000      guibg=NONE      gui=NONE      ctermfg=brown          ctermbg=NONE      cterm=NONE
+hi rubyEscape                  guifg=white        guibg=NONE      gui=NONE      ctermfg=cyan           ctermbg=NONE      cterm=NONE
+hi rubyInterpolationDelimiter  guifg=#00A0A0      guibg=NONE      gui=NONE      ctermfg=blue           ctermbg=NONE      cterm=NONE
+hi rubyControl                 guifg=#6699CC      guibg=NONE      gui=NONE      ctermfg=blue           ctermbg=NONE      cterm=NONE  "and break, etc
+"hi rubyGlobalVariable          guifg=#FFCCFF      guibg=NONE      gui=NONE      ctermfg=lightblue      ctermbg=NONE      cterm=NONE  "yield
+hi rubyStringDelimiter         guifg=#336633      guibg=NONE      gui=NONE      ctermfg=lightgreen     ctermbg=NONE      cterm=NONE
+"rubyInclude
+"rubySharpBang
+"rubyAccess
+"rubyPredefinedVariable
+"rubyBoolean
+"rubyClassVariable
+"rubyBeginEnd
+"rubyRepeatModifier
+"hi link rubyArrayDelimiter    Special  " [ , , ]
+"rubyCurlyBlock  { , , }
+
+hi link rubyClass             Keyword 
+hi link rubyModule            Keyword 
+hi link rubyKeyword           Keyword 
+hi link rubyOperator          Operator
+hi link rubyIdentifier        Identifier
+hi link rubyInstanceVariable  Identifier
+hi link rubyGlobalVariable    Identifier
+hi link rubyClassVariable     Identifier
+hi link rubyConstant          Type  
+
+
+" Special for Java
+" hi link javaClassDecl    Type
+hi link javaScopeDecl         Identifier 
+hi link javaCommentTitle      javaDocSeeTag 
+hi link javaDocTags           javaDocSeeTag 
+hi link javaDocParam          javaDocSeeTag 
+hi link javaDocSeeTagParam    javaDocSeeTag 
+
+hi javaDocSeeTag              guifg=#CCCCCC     guibg=NONE        gui=NONE      ctermfg=darkgray    ctermbg=NONE        cterm=NONE
+hi javaDocSeeTag              guifg=#CCCCCC     guibg=NONE        gui=NONE      ctermfg=darkgray    ctermbg=NONE        cterm=NONE
+"hi javaClassDecl              guifg=#CCFFCC     guibg=NONE        gui=NONE      ctermfg=white       ctermbg=NONE        cterm=NONE
+
+
+" Special for XML
+hi link xmlTag          Keyword 
+hi link xmlTagName      Conditional 
+hi link xmlEndTag       Identifier 
+
+
+" Special for HTML
+hi link htmlTag         Keyword 
+hi link htmlTagName     Conditional 
+hi link htmlEndTag      Identifier 
+
+
+" Special for Javascript
+hi link javaScriptNumber      Number 
+
+
+" Special for Python
+"hi  link pythonEscape         Keyword      
+
+
+" Special for CSharp
+hi  link csXmlTag             Keyword      
+
+
+" Special for PHP
Index: /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/colors/issm_white.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/colors/issm_white.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/colors/issm_white.vim	(revision 11330)
@@ -0,0 +1,212 @@
+" ir_black color scheme
+" More at: http://blog.infinitered.com/entries/show/8
+
+
+" ********************************************************************************
+" Standard colors used in all ir_black themes:
+" Note, x:x:x are RGB values
+"
+"  normal: #f6f3e8
+" 
+"  string: #A8FF60  168:255:96                   
+"    string inner (punc, code, etc): #00A0A0  0:160:160
+"  number: #FF73FD  255:115:253                 
+"  comments: #7C7C7C  124:124:124
+"  keywords: #96CBFE  150:203:254             
+"  operators: white
+"  class: #FFFFB6  255:255:182
+"  method declaration name: #FFD2A7  255:210:167
+"  regular expression: #E9C062  233:192:98
+"    regexp alternate: #FF8000  255:128:0
+"    regexp alternate 2: #B18A3D  177:138:61
+"  variable: #C6C5FE  198:197:254
+"  
+" Misc colors:
+"  red color (used for whatever): #FF6C60   255:108:96 
+"     light red: #FFB6B0   255:182:176
+"
+"  brown: #E18964  good for special
+"
+"  lightpurpleish: #FFCCFF
+" 
+" Interface colors:
+"  background color: black
+"  cursor (where underscore is used): #FFA560  255:165:96
+"  cursor (where block is used): white
+"  visual selection: #1D1E2C  
+"  current line: #151515  21:21:21
+"  search selection: #07281C  7:40:28
+"  line number: #3D3D3D  61:61:61
+
+
+" ********************************************************************************
+" The following are the preferred 16 colors for your terminal
+"           Colors      Bright Colors
+" Black     #4E4E4E     #7C7C7C
+" Red       #FF6C60     #FFB6B0
+" Green     #A8FF60     #CEFFAB
+" Yellow    #FFFFB6     #FFFFCB
+" Blue      #96CBFE     #FFFFCB
+" Magenta   #FF73FD     #FF9CFE
+" Cyan      #C6C5FE     #DFDFFE
+" White     #EEEEEE     #FFFFFF
+
+
+" ********************************************************************************
+hi clear
+
+if exists("syntax_on")
+  syntax reset
+endif
+syntax on
+
+let colors_name = "issm_white"
+
+"                   GUI not used in terminal mode                     forground           background          style (reverse,bold,..)
+"hi Example         guifg=NONE        guibg=NONE        gui=NONE      ctermfg=NONE        ctermbg=NONE        cterm=NONE
+
+" General colors
+hi Normal           guifg=#f6f3e8     guibg=black       gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=NONE
+hi NonText          guifg=#070707     guibg=black       gui=NONE      ctermfg=129        ctermbg=NONE        cterm=NONE         "214 =orange
+
+hi Cursor           guifg=black       guibg=white       gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=reverse      "cursor (mouse)
+hi LineNr           guifg=#3D3D3D     guibg=black       gui=NONE      ctermfg=249        ctermbg=232         cterm=NONE         "line numbering gray/blak 
+
+hi VertSplit        guifg=#202020     guibg=#202020     gui=NONE      ctermfg=241        ctermbg=241         cterm=NONE         "vertical split
+hi StatusLine       guifg=#CCCCCC     guibg=#202020     gui=italic    ctermfg=241        ctermbg=87          cterm=NONE         "87 = cyan
+hi StatusLineNC     guifg=black       guibg=#202020     gui=NONE      ctermfg=87         ctermbg=241         cterm=NONE         "241 = dark gray
+
+hi Folded           guifg=#a0a8b0     guibg=#384048     gui=NONE      ctermfg=NONE       ctermbg=129         cterm=NONE         "folded 129 = violet
+hi Title            guifg=#f6f3e8     guibg=NONE        gui=bold      ctermfg=NONE       ctermbg=NONE        cterm=NONE
+hi Visual           guifg=NONE        guibg=#262D51     gui=NONE                         ctermbg=255         cterm=bold,reverse "visual 255 = white
+
+hi SpecialKey       guifg=#808080     guibg=#343434     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=NONE
+
+hi WildMenu         guifg=green       guibg=yellow      gui=NONE      ctermfg=black      ctermbg=yellow      cterm=NONE          "?????
+hi PmenuSbar        guifg=black       guibg=white       gui=NONE      ctermfg=black      ctermbg=magenta     cterm=NONE          "????
+"hi Ignore           guifg=gray        guibg=black       gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=NONE
+
+hi Error            guifg=NONE        guibg=black       gui=NONE ctermfg=255      ctermbg=129         cterm=NONE
+hi ErrorMsg         guifg=white       guibg=#FF6C60     gui=BOLD      ctermfg=255      ctermbg=129         cterm=NONE                   " 196 = red
+hi WarningMsg       guifg=white       guibg=#FF6C60     gui=BOLD      ctermfg=255      ctermbg=201         cterm=NONE                   "201 = magenta
+
+" Message displayed in lower left, such as --INSERT--
+hi ModeMsg          guifg=black       guibg=#C6C5FE     gui=BOLD      ctermfg=241      ctermbg=87        cterm=BOLD
+
+if version >= 700 " Vim 7.x specific colors
+  hi CursorLine     guifg=NONE        guibg=#121212     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=BOLD
+  hi CursorColumn   guifg=NONE        guibg=#121212     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=BOLD
+  hi MatchParen     guifg=#f6f3e8     guibg=#857b6f     gui=BOLD      ctermfg=87         ctermbg=241         cterm=BOLD,reverse  "matching parenthesis
+  hi Pmenu          guifg=#f6f3e8     guibg=#444444     gui=NONE      ctermfg=232        ctermbg=254         cterm=NONE "auto completion panel
+  hi PmenuSel       guifg=#000000     guibg=#cae682     gui=NONE      ctermfg=255        ctermbg=201        cterm=NONE
+  hi Search         guifg=NONE        guibg=NONE        gui=underline ctermfg=NONE       ctermbg=227         cterm=NONE  "227 = yellow
+endif
+
+" Syntax highlighting
+hi Comment          guifg=#7C7C7C     guibg=NONE        gui=NONE      ctermfg=243         ctermbg=NONE        cterm=NONE
+hi String           guifg=#A8FF60     guibg=NONE        gui=NONE      ctermfg=40          ctermbg=NONE        cterm=NONE
+hi Number           guifg=#FF73FD     guibg=NONE        gui=NONE      ctermfg=201         ctermbg=NONE        cterm=NONE
+
+hi Keyword          guifg=#96CBFE     guibg=NONE        gui=NONE      ctermfg=196          ctermbg=NONE        cterm=NONE  " matlab function
+hi PreProc          guifg=#96CBFE     guibg=NONE        gui=NONE      ctermfg=196         ctermbg=NONE        cterm=NONE   " def undef include
+hi Conditional      guifg=#6699CC     guibg=NONE        gui=NONE      ctermfg=93         ctermbg=NONE        cterm=NONE  " if else end
+
+hi Todo             guifg=#8f8f8f     guibg=NONE        gui=NONE      ctermfg=18         ctermbg=NONE        cterm=NONE
+hi Constant         guifg=#99CC99     guibg=NONE        gui=NONE      ctermfg=21         ctermbg=NONE        cterm=NONE
+
+hi Identifier       guifg=#C6C5FE     guibg=NONE        gui=NONE      ctermfg=21          ctermbg=NONE        cterm=NONE
+hi Function         guifg=#FFD2A7     guibg=NONE        gui=NONE      ctermfg=69          ctermbg=NONE        cterm=NONE "functions 69 = pastel blue
+hi Type             guifg=#FFFFB6     guibg=NONE        gui=NONE      ctermfg=165         ctermbg=NONE        cterm=NONE
+hi Statement        guifg=#6699CC     guibg=NONE        gui=NONE      ctermfg=69         ctermbg=NONE        cterm=NONE " cd ls sed mv
+
+hi Special          guifg=#E18964     guibg=NONE        gui=NONE      ctermfg=43          ctermbg=NONE        cterm=NONE  " ; 202  = orange 
+hi Delimiter        guifg=#00A0A0     guibg=NONE        gui=NONE      ctermfg=NONE        ctermbg=NONE        cterm=NONE  " [ ]
+hi Operator         guifg=white       guibg=NONE        gui=NONE      ctermfg=43          ctermbg=NONE        cterm=NONE  " == &  178 = darkyellow
+
+hi link Character       Constant
+hi link Boolean         Constant
+hi link Float           Number
+hi link Repeat          Statement
+hi link Label           Statement
+hi link Exception       Statement
+hi link Include         PreProc
+hi link Define          PreProc
+hi link Macro           PreProc
+hi link PreCondit       PreProc
+hi link StorageClass    Type
+hi link Structure       Type
+hi link Typedef         Type
+hi link Tag             Special
+hi link SpecialChar     Special
+hi link SpecialComment  Special
+hi link Debug           Special
+
+
+" Special for Ruby
+hi rubyRegexp                  guifg=#B18A3D      guibg=NONE      gui=NONE      ctermfg=brown          ctermbg=NONE      cterm=NONE
+hi rubyRegexpDelimiter         guifg=#FF8000      guibg=NONE      gui=NONE      ctermfg=brown          ctermbg=NONE      cterm=NONE
+hi rubyEscape                  guifg=white        guibg=NONE      gui=NONE      ctermfg=cyan           ctermbg=NONE      cterm=NONE
+hi rubyInterpolationDelimiter  guifg=#00A0A0      guibg=NONE      gui=NONE      ctermfg=blue           ctermbg=NONE      cterm=NONE
+hi rubyControl                 guifg=#6699CC      guibg=NONE      gui=NONE      ctermfg=blue           ctermbg=NONE      cterm=NONE  "and break, etc
+"hi rubyGlobalVariable          guifg=#FFCCFF      guibg=NONE      gui=NONE      ctermfg=lightblue      ctermbg=NONE      cterm=NONE  "yield
+hi rubyStringDelimiter         guifg=#336633      guibg=NONE      gui=NONE      ctermfg=lightgreen     ctermbg=NONE      cterm=NONE
+"rubyInclude
+"rubySharpBang
+"rubyAccess
+"rubyPredefinedVariable
+"rubyBoolean
+"rubyClassVariable
+"rubyBeginEnd
+"rubyRepeatModifier
+"hi link rubyArrayDelimiter    Special  " [ , , ]
+"rubyCurlyBlock  { , , }
+
+hi link rubyClass             Keyword 
+hi link rubyModule            Keyword 
+hi link rubyKeyword           Keyword 
+hi link rubyOperator          Operator
+hi link rubyIdentifier        Identifier
+hi link rubyInstanceVariable  Identifier
+hi link rubyGlobalVariable    Identifier
+hi link rubyClassVariable     Identifier
+hi link rubyConstant          Type  
+
+
+" Special for Java
+" hi link javaClassDecl    Type
+hi link javaScopeDecl         Identifier 
+hi link javaCommentTitle      javaDocSeeTag 
+hi link javaDocTags           javaDocSeeTag 
+hi link javaDocParam          javaDocSeeTag 
+hi link javaDocSeeTagParam    javaDocSeeTag 
+
+hi javaDocSeeTag              guifg=#CCCCCC     guibg=NONE        gui=NONE      ctermfg=darkgray    ctermbg=NONE        cterm=NONE
+hi javaDocSeeTag              guifg=#CCCCCC     guibg=NONE        gui=NONE      ctermfg=darkgray    ctermbg=NONE        cterm=NONE
+"hi javaClassDecl              guifg=#CCFFCC     guibg=NONE        gui=NONE      ctermfg=white       ctermbg=NONE        cterm=NONE
+
+
+" Special for XML
+hi link xmlTag          Keyword 
+hi link xmlTagName      Conditional 
+hi link xmlEndTag       Identifier 
+
+
+" Special for HTML
+hi link htmlTag         Keyword 
+hi link htmlTagName     Conditional 
+hi link htmlEndTag      Identifier 
+
+
+" Special for Javascript
+hi link javaScriptNumber      Number 
+
+
+" Special for Python
+"hi  link pythonEscape         Keyword      
+
+
+" Special for CSharp
+hi  link csXmlTag             Keyword      
+
+
+" Special for PHP
Index: /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/doc/Align.txt
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/doc/Align.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/doc/Align.txt	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/doc/skeleton.txt
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/doc/skeleton.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/doc/skeleton.txt	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/doc/tags
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/doc/tags	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/doc/tags	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/indent/matlab.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/indent/matlab.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/indent/matlab.vim	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/indent/tex.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/indent/tex.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/indent/tex.vim	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/AlignMapsPlugin.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/AlignMapsPlugin.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/AlignMapsPlugin.vim	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/AlignPlugin.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/AlignPlugin.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/AlignPlugin.vim	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/cecutil.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/cecutil.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/cecutil.vim	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/file_line.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/file_line.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/file_line.vim	(revision 11330)
@@ -0,0 +1,16 @@
+function! s:gotoline()
+	let file = bufname("%")
+	let names =  matchlist( file, '\(.*\):\(\d\+\)')
+
+	if len(names) != 0 && filereadable(names[1])
+		let l:bufn = bufnr("%")
+		exec ":e " . names[1]
+		exec ":" . names[2]
+		exec ":bdelete " . l:bufn
+		if foldlevel(names[2]) > 0
+			exec ":foldopen!"
+		endif
+	endif
+endfunction
+
+autocmd! BufNewFile *:* nested call s:gotoline()
Index: /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/issmfolds.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/issmfolds.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/issmfolds.vim	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/skeleton.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/skeleton.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/plugin/skeleton.vim	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/Synchronize.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 11330)
@@ -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/EnumDefinitions/EnumDefinitions.h | grep -e "[0-9]Enum," -e "[Aa-Zz]Enum," | grep -v StringToEnum | sed -e "s/,//g" | awk '{ printf "syn keyword cConstant " $1 "\n"}' >> temp
+echo "\"ISSM's Enums end" >> temp
+cat c.vim | sed "1,/ISSM's Enums end/d" >> temp
+
+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
+cat ../../../../../src/c/objects/objects.h  | grep "\.h" | sed -e "s/\// /g" -e "s/\.h\"//" | awk '{print  $(NF)}' | awk '{ printf "syn keyword cType " $1 "\n"}' >> temp
+echo "\"ISSM's objects end" >> temp
+cat c.vim | sed "1,/ISSM's objects end/d" >> temp
+
+mv temp c.vim
Index: /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/c.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/c.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/c.vim	(revision 11330)
@@ -0,0 +1,1255 @@
+" 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                                                                    "
+"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
+"ISSM containers:
+syn keyword	cType		Constraints DataSet Elements Inputs Loads Materials Parameters Results Vertices
+"Petsc
+syn keyword	cType		Vec Mat 
+"other ISSM's syntax
+syn keyword	cType		mxArray ErrorException
+
+"ISSM's objects begin
+syn keyword cType objects.h
+syn keyword cType Object
+syn keyword cType Hook
+syn keyword cType DofIndexing
+syn keyword cType Vertex
+syn keyword cType Node
+syn keyword cType Segment
+syn keyword cType IoModel
+syn keyword cType Patch
+syn keyword cType Update
+syn keyword cType Constraint
+syn keyword cType SpcStatic
+syn keyword cType SpcTransient
+syn keyword cType SpcDynamic
+syn keyword cType GaussTria
+syn keyword cType GaussPenta
+syn keyword cType Friction
+syn keyword cType Icefront
+syn keyword cType Numericalflux
+syn keyword cType Riftfront
+syn keyword cType Penpair
+syn keyword cType Pengrid
+syn keyword cType Element
+syn keyword cType Penta
+syn keyword cType PentaHook
+syn keyword cType PentaRef
+syn keyword cType Tria
+syn keyword cType TriaHook
+syn keyword cType TriaRef
+syn keyword cType KML_Attribute
+syn keyword cType KML_Comment
+syn keyword cType KML_ColorStyle
+syn keyword cType KML_Container
+syn keyword cType KML_Document
+syn keyword cType KML_Feature
+syn keyword cType KML_File
+syn keyword cType KML_Folder
+syn keyword cType KML_Geometry
+syn keyword cType KML_GroundOverlay
+syn keyword cType KML_Icon
+syn keyword cType KML_LatLonBox
+syn keyword cType KML_LinearRing
+syn keyword cType KML_LineString
+syn keyword cType KML_LineStyle
+syn keyword cType KML_MultiGeometry
+syn keyword cType KML_Object
+syn keyword cType KML_Overlay
+syn keyword cType KML_Point
+syn keyword cType KML_Placemark
+syn keyword cType KML_Polygon
+syn keyword cType KML_PolyStyle
+syn keyword cType KML_Style
+syn keyword cType KML_StyleSelector
+syn keyword cType KML_SubStyle
+syn keyword cType KMLFileReadUtils
+syn keyword cType Option
+syn keyword cType OptionDouble
+syn keyword cType OptionLogical
+syn keyword cType OptionChar
+syn keyword cType OptionStruct
+syn keyword cType OptionCell
+syn keyword cType OptionUtilities
+syn keyword cType Input
+syn keyword cType BoolInput
+syn keyword cType DoubleInput
+syn keyword cType IntInput
+syn keyword cType PentaVertexInput
+syn keyword cType TriaVertexInput
+syn keyword cType ControlInput
+syn keyword cType DatasetInput
+syn keyword cType TransientInput
+syn keyword cType ElementResult
+syn keyword cType DoubleElementResult
+syn keyword cType TriaVertexElementResult
+syn keyword cType PentaVertexElementResult
+syn keyword cType BoolElementResult
+syn keyword cType ExternalResult
+syn keyword cType BoolExternalResult
+syn keyword cType DoubleExternalResult
+syn keyword cType DoubleVecExternalResult
+syn keyword cType DoubleMatExternalResult
+syn keyword cType IntExternalResult
+syn keyword cType PetscVecExternalResult
+syn keyword cType StringExternalResult
+syn keyword cType Material
+syn keyword cType Matice
+syn keyword cType Matpar
+syn keyword cType ElementMatrix
+syn keyword cType ElementVector
+syn keyword cType BoolParam
+syn keyword cType DoubleMatParam
+syn keyword cType DoubleTransientMatParam
+syn keyword cType DoubleMatArrayParam
+syn keyword cType DoubleParam
+syn keyword cType DoubleVecParam
+syn keyword cType IntParam
+syn keyword cType IntVecParam
+syn keyword cType IntMatParam
+syn keyword cType FileParam
+syn keyword cType Param
+syn keyword cType PetscMatParam
+syn keyword cType PetscVecParam
+syn keyword cType StringArrayParam
+syn keyword cType StringParam
+syn keyword cType Contour
+syn keyword cType FemModel
+syn keyword cType OptArgs
+syn keyword cType OptPars
+syn keyword cType BamgOpts
+syn keyword cType BamgGeom
+syn keyword cType BamgMesh
+syn keyword cType Metric
+syn keyword cType DoubleAndInt
+syn keyword cType Direction
+syn keyword cType BamgVertex
+syn keyword cType AdjacentTriangle
+syn keyword cType Edge
+syn keyword cType GeomVertex
+syn keyword cType GeomEdge
+syn keyword cType Curve
+syn keyword cType Triangle
+syn keyword cType ListofIntersectionTriangles
+syn keyword cType GeomSubDomain
+syn keyword cType SubDomain
+syn keyword cType VertexOnGeom
+syn keyword cType VertexOnVertex
+syn keyword cType VertexOnEdge
+syn keyword cType CrackedEdge
+syn keyword cType Mesh
+syn keyword cType Geometry
+syn keyword cType QuadTree
+syn keyword cType SetOfE4
+"ISSM's objects end
+
+"ISSM's Enums begin
+syn keyword cConstant AutodiffForwardEnum
+syn keyword cConstant AutodiffIsautodiffEnum
+syn keyword cConstant AutodiffReverseEnum
+syn keyword cConstant BalancethicknessSpcthicknessEnum
+syn keyword cConstant BalancethicknessStabilizationEnum
+syn keyword cConstant BalancethicknessThickeningRateEnum
+syn keyword cConstant BasalforcingsGeothermalfluxEnum
+syn keyword cConstant BasalforcingsMeltingRateCorrectionEnum
+syn keyword cConstant BasalforcingsMeltingRateEnum
+syn keyword cConstant BathymetryEnum
+syn keyword cConstant BedEnum
+syn keyword cConstant ConstantsGEnum
+syn keyword cConstant ConstantsReferencetemperatureEnum
+syn keyword cConstant ConstantsYtsEnum
+syn keyword cConstant DiagnosticAbstolEnum
+syn keyword cConstant DiagnosticIcefrontEnum
+syn keyword cConstant DiagnosticMaxiterEnum
+syn keyword cConstant DiagnosticNumRequestedOutputsEnum
+syn keyword cConstant DiagnosticPenaltyFactorEnum
+syn keyword cConstant DiagnosticReferentialEnum
+syn keyword cConstant DiagnosticReltolEnum
+syn keyword cConstant DiagnosticRequestedOutputsEnum
+syn keyword cConstant DiagnosticRestolEnum
+syn keyword cConstant DiagnosticRiftPenaltyLockEnum
+syn keyword cConstant DiagnosticRiftPenaltyThresholdEnum
+syn keyword cConstant DiagnosticShelfDampeningEnum
+syn keyword cConstant DiagnosticSpcvxEnum
+syn keyword cConstant DiagnosticSpcvyEnum
+syn keyword cConstant DiagnosticSpcvzEnum
+syn keyword cConstant DiagnosticStokesreconditioningEnum
+syn keyword cConstant DiagnosticVertexPairingEnum
+syn keyword cConstant DiagnosticViscosityOvershootEnum
+syn keyword cConstant FlowequationBordermacayealEnum
+syn keyword cConstant FlowequationBorderpattynEnum
+syn keyword cConstant FlowequationBorderstokesEnum
+syn keyword cConstant FlowequationElementEquationEnum
+syn keyword cConstant FlowequationIshutterEnum
+syn keyword cConstant FlowequationIsmacayealpattynEnum
+syn keyword cConstant FlowequationIsstokesEnum
+syn keyword cConstant FlowequationVertexEquationEnum
+syn keyword cConstant FrictionCoefficientEnum
+syn keyword cConstant FrictionPEnum
+syn keyword cConstant FrictionQEnum
+syn keyword cConstant GeometryHydrostaticRatioEnum
+syn keyword cConstant HydrologyCREnum
+syn keyword cConstant HydrologyKnEnum
+syn keyword cConstant HydrologyNEnum
+syn keyword cConstant HydrologyPEnum
+syn keyword cConstant HydrologyQEnum
+syn keyword cConstant HydrologySpcwatercolumnEnum
+syn keyword cConstant HydrologyStabilizationEnum
+syn keyword cConstant InversionControlParametersEnum
+syn keyword cConstant InversionCostFunctionEnum
+syn keyword cConstant InversionCostFunctionThresholdEnum
+syn keyword cConstant InversionCostFunctionsCoefficientsEnum
+syn keyword cConstant InversionCostFunctionsEnum
+syn keyword cConstant InversionGradientOnlyEnum
+syn keyword cConstant InversionGradientScalingEnum
+syn keyword cConstant InversionIscontrolEnum
+syn keyword cConstant InversionTaoEnum
+syn keyword cConstant InversionMaxParametersEnum
+syn keyword cConstant InversionMaxiterPerStepEnum
+syn keyword cConstant InversionMinParametersEnum
+syn keyword cConstant InversionNstepsEnum
+syn keyword cConstant InversionNumControlParametersEnum
+syn keyword cConstant InversionNumCostFunctionsEnum
+syn keyword cConstant InversionStepThresholdEnum
+syn keyword cConstant InversionThicknessObsEnum
+syn keyword cConstant InversionVelObsEnum
+syn keyword cConstant InversionVxObsEnum
+syn keyword cConstant InversionVyObsEnum
+syn keyword cConstant InversionVzObsEnum
+syn keyword cConstant MaskElementonfloatingiceEnum
+syn keyword cConstant MaskElementongroundediceEnum
+syn keyword cConstant MaskElementonwaterEnum
+syn keyword cConstant MaskVertexonfloatingiceEnum
+syn keyword cConstant MaskVertexongroundediceEnum
+syn keyword cConstant MaskVertexonwaterEnum
+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 MaterialsRhoIceEnum
+syn keyword cConstant MaterialsRhoWaterEnum
+syn keyword cConstant MaterialsMuWaterEnum
+syn keyword cConstant MaterialsThermalExchangeVelocityEnum
+syn keyword cConstant MaterialsThermalconductivityEnum
+syn keyword cConstant MeshAverageVertexConnectivityEnum
+syn keyword cConstant MeshDimensionEnum
+syn keyword cConstant MeshEdgesEnum
+syn keyword cConstant MeshElementconnectivityEnum
+syn keyword cConstant MeshElementonbedEnum
+syn keyword cConstant MeshElementonsurfaceEnum
+syn keyword cConstant MeshElements2dEnum
+syn keyword cConstant MeshElementsEnum
+syn keyword cConstant MeshLowerelementsEnum
+syn keyword cConstant MeshNumberofedgesEnum
+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 MeshVertexonbedEnum
+syn keyword cConstant MeshVertexonsurfaceEnum
+syn keyword cConstant MeshXEnum
+syn keyword cConstant MeshYEnum
+syn keyword cConstant MeshZEnum
+syn keyword cConstant MiscellaneousNameEnum
+syn keyword cConstant PrognosticHydrostaticAdjustmentEnum
+syn keyword cConstant PrognosticMinThicknessEnum
+syn keyword cConstant PrognosticPenaltyFactorEnum
+syn keyword cConstant PrognosticSpcthicknessEnum
+syn keyword cConstant PrognosticStabilizationEnum
+syn keyword cConstant PrognosticVertexPairingEnum
+syn keyword cConstant QmuIsdakotaEnum
+syn keyword cConstant QmuMassFluxSegmentsEnum
+syn keyword cConstant QmuNumberofpartitionsEnum
+syn keyword cConstant QmuNumberofresponsesEnum
+syn keyword cConstant QmuPartitionEnum
+syn keyword cConstant QmuResponsedescriptorsEnum
+syn keyword cConstant QmuVariabledescriptorsEnum
+syn keyword cConstant RiftsNumriftsEnum
+syn keyword cConstant RiftsRiftstructEnum
+syn keyword cConstant SettingsIoGatherEnum
+syn keyword cConstant SettingsLowmemEnum
+syn keyword cConstant SettingsOutputFrequencyEnum
+syn keyword cConstant SettingsResultsAsPatchesEnum
+syn keyword cConstant SettingsWaitonlockEnum
+syn keyword cConstant SteadystateMaxiterEnum
+syn keyword cConstant SteadystateNumRequestedOutputsEnum
+syn keyword cConstant SteadystateReltolEnum
+syn keyword cConstant SteadystateRequestedOutputsEnum
+syn keyword cConstant SurfaceEnum
+syn keyword cConstant SurfaceforcingsAblationRateEnum
+syn keyword cConstant SurfaceforcingsAccumulationRateEnum
+syn keyword cConstant SurfaceforcingsMassBalanceEnum
+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 ThicknessEnum
+syn keyword cConstant TimesteppingCflCoefficientEnum
+syn keyword cConstant TimesteppingFinalTimeEnum
+syn keyword cConstant TimesteppingTimeAdaptEnum
+syn keyword cConstant TimesteppingTimeStepEnum
+syn keyword cConstant TransientIsdiagnosticEnum
+syn keyword cConstant TransientIsgroundinglineEnum
+syn keyword cConstant TransientIsprognosticEnum
+syn keyword cConstant TransientIsthermalEnum
+syn keyword cConstant TransientNumRequestedOutputsEnum
+syn keyword cConstant TransientRequestedOutputsEnum
+syn keyword cConstant SolutionTypeEnum
+syn keyword cConstant AnalysisTypeEnum
+syn keyword cConstant ConfigurationTypeEnum
+syn keyword cConstant AdjointBalancethicknessAnalysisEnum
+syn keyword cConstant AdjointHorizAnalysisEnum
+syn keyword cConstant AdjointSolutionEnum
+syn keyword cConstant AnalysisCounterEnum
+syn keyword cConstant BalancethicknessAnalysisEnum
+syn keyword cConstant BalancethicknessSolutionEnum
+syn keyword cConstant BedSlopeAnalysisEnum
+syn keyword cConstant BedSlopeSolutionEnum
+syn keyword cConstant BedSlopeXAnalysisEnum
+syn keyword cConstant BedSlopeYAnalysisEnum
+syn keyword cConstant DiagnosticHorizAnalysisEnum
+syn keyword cConstant DiagnosticHutterAnalysisEnum
+syn keyword cConstant DiagnosticSolutionEnum
+syn keyword cConstant DiagnosticVertAnalysisEnum
+syn keyword cConstant EnthalpyAnalysisEnum
+syn keyword cConstant EnthalpySolutionEnum
+syn keyword cConstant FlaimAnalysisEnum
+syn keyword cConstant FlaimSolutionEnum
+syn keyword cConstant HydrologyAnalysisEnum
+syn keyword cConstant HydrologySolutionEnum
+syn keyword cConstant MeltingAnalysisEnum
+syn keyword cConstant NoneAnalysisEnum
+syn keyword cConstant PrognosticAnalysisEnum
+syn keyword cConstant PrognosticSolutionEnum
+syn keyword cConstant SteadystateSolutionEnum
+syn keyword cConstant SurfaceSlopeAnalysisEnum
+syn keyword cConstant SurfaceSlopeSolutionEnum
+syn keyword cConstant SurfaceSlopeXAnalysisEnum
+syn keyword cConstant SurfaceSlopeYAnalysisEnum
+syn keyword cConstant ThermalAnalysisEnum
+syn keyword cConstant ThermalSolutionEnum
+syn keyword cConstant TransientSolutionEnum
+syn keyword cConstant ApproximationEnum
+syn keyword cConstant HutterApproximationEnum
+syn keyword cConstant MacAyealApproximationEnum
+syn keyword cConstant MacAyealPattynApproximationEnum
+syn keyword cConstant MacAyealStokesApproximationEnum
+syn keyword cConstant NoneApproximationEnum
+syn keyword cConstant PattynApproximationEnum
+syn keyword cConstant PattynStokesApproximationEnum
+syn keyword cConstant StokesApproximationEnum
+syn keyword cConstant ConstraintsEnum
+syn keyword cConstant LoadsEnum
+syn keyword cConstant MaterialsEnum
+syn keyword cConstant NodesEnum
+syn keyword cConstant ParametersEnum
+syn keyword cConstant VerticesEnum
+syn keyword cConstant ResultsEnum
+syn keyword cConstant BoolInputEnum
+syn keyword cConstant BoolParamEnum
+syn keyword cConstant ControlInputEnum
+syn keyword cConstant DatasetInputEnum
+syn keyword cConstant DofIndexingEnum
+syn keyword cConstant DoubleInputEnum
+syn keyword cConstant DoubleMatArrayParamEnum
+syn keyword cConstant DoubleMatParamEnum
+syn keyword cConstant DoubleParamEnum
+syn keyword cConstant DoubleVecParamEnum
+syn keyword cConstant ElementEnum
+syn keyword cConstant ElementResultEnum
+syn keyword cConstant ExternalResultEnum
+syn keyword cConstant FileParamEnum
+syn keyword cConstant HookEnum
+syn keyword cConstant IcefrontEnum
+syn keyword cConstant InputEnum
+syn keyword cConstant IntInputEnum
+syn keyword cConstant IntParamEnum
+syn keyword cConstant IntVecParamEnum
+syn keyword cConstant MacAyeal2dIceFrontEnum
+syn keyword cConstant MacAyeal3dIceFrontEnum
+syn keyword cConstant MaticeEnum
+syn keyword cConstant MatparEnum
+syn keyword cConstant NodeEnum
+syn keyword cConstant NumericalfluxEnum
+syn keyword cConstant ParamEnum
+syn keyword cConstant PattynIceFrontEnum
+syn keyword cConstant PengridEnum
+syn keyword cConstant PenpairEnum
+syn keyword cConstant PentaEnum
+syn keyword cConstant PentaVertexInputEnum
+syn keyword cConstant PetscMatParamEnum
+syn keyword cConstant PetscVecParamEnum
+syn keyword cConstant RiftfrontEnum
+syn keyword cConstant SegmentEnum
+syn keyword cConstant SegmentRiftfrontEnum
+syn keyword cConstant SpcDynamicEnum
+syn keyword cConstant SpcStaticEnum
+syn keyword cConstant SpcTransientEnum
+syn keyword cConstant StokesIceFrontEnum
+syn keyword cConstant StringArrayParamEnum
+syn keyword cConstant StringParamEnum
+syn keyword cConstant TriaEnum
+syn keyword cConstant TriaVertexInputEnum
+syn keyword cConstant VertexEnum
+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 BedSlopeXEnum
+syn keyword cConstant BedSlopeYEnum
+syn keyword cConstant BoundaryEnum
+syn keyword cConstant ConstantEnum
+syn keyword cConstant ConvergedEnum
+syn keyword cConstant ExtToIuEnum
+syn keyword cConstant FillEnum
+syn keyword cConstant FractionIncrementEnum
+syn keyword cConstant FrictionEnum
+syn keyword cConstant GroundinglineMeltingRateEnum
+syn keyword cConstant InternalEnum
+syn keyword cConstant IuToExtEnum
+syn keyword cConstant MassFluxEnum
+syn keyword cConstant MaxPenetrationEnum
+syn keyword cConstant MeltingOffsetEnum
+syn keyword cConstant MisfitEnum
+syn keyword cConstant NumberNodeToElementConnectivityEnum
+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 QmuBedEnum
+syn keyword cConstant QmuSurfaceEnum
+syn keyword cConstant QmuMeltingEnum
+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 TemperatureOldEnum
+syn keyword cConstant TemperaturePicardEnum
+syn keyword cConstant ThicknessAbsMisfitEnum
+syn keyword cConstant TypeEnum
+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 VzMacAyealEnum
+syn keyword cConstant VzPattynEnum
+syn keyword cConstant VzPicardEnum
+syn keyword cConstant VzStokesEnum
+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 StepResponsesEnum
+syn keyword cConstant IntMatParamEnum
+syn keyword cConstant RheologyBbarAbsGradientEnum
+syn keyword cConstant DragCoefficientAbsGradientEnum
+syn keyword cConstant TransientInputEnum
+syn keyword cConstant OutputfilenameEnum
+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 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 IceVolumeEnum
+syn keyword cConstant P0Enum
+syn keyword cConstant P1Enum
+syn keyword cConstant P1DGEnum
+syn keyword cConstant BoolElementResultEnum
+syn keyword cConstant BoolExternalResultEnum
+syn keyword cConstant DoubleElementResultEnum
+syn keyword cConstant DoubleExternalResultEnum
+syn keyword cConstant DoubleMatExternalResultEnum
+syn keyword cConstant DoubleVecExternalResultEnum
+syn keyword cConstant IntExternalResultEnum
+syn keyword cConstant JEnum
+syn keyword cConstant PatchEnum
+syn keyword cConstant PatchNodesEnum
+syn keyword cConstant PatchVerticesEnum
+syn keyword cConstant PentaVertexElementResultEnum
+syn keyword cConstant PetscVecExternalResultEnum
+syn keyword cConstant StringExternalResultEnum
+syn keyword cConstant TimeEnum
+syn keyword cConstant TriaVertexElementResultEnum
+syn keyword cConstant WaterColumnOldEnum
+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 RelativeEnum
+syn keyword cConstant AbsoluteEnum
+syn keyword cConstant IncrementalEnum
+syn keyword cConstant AgressiveMigrationEnum
+syn keyword cConstant NoneEnum
+syn keyword cConstant SoftMigrationEnum
+syn keyword cConstant StokesSolverEnum
+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 PetscOptionsAnalysesEnum
+syn keyword cConstant PetscOptionsStringsEnum
+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 XYZPEnum
+syn keyword cConstant OptionEnum
+syn keyword cConstant OptionCellEnum
+syn keyword cConstant OptionCharEnum
+syn keyword cConstant OptionStructEnum
+syn keyword cConstant OptionDoubleEnum
+syn keyword cConstant OptionLogicalEnum
+syn keyword cConstant PatersonEnum
+syn keyword cConstant ArrheniusEnum
+"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/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/matlab.vim
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/matlab.vim	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/matlab.vim	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/xtr/skeleton/letter.tex
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/xtr/skeleton/letter.tex	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/xtr/skeleton/letter.tex	(revision 11330)
@@ -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/trunk-jpl-damage/externalpackages/vim/addons/vim/xtr/skeleton/sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/xtr/skeleton/sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vim/xtr/skeleton/sh	(revision 11330)
@@ -0,0 +1,1 @@
+#!/bin/bash
Index: /issm/trunk-jpl-damage/externalpackages/vim/addons/vimrc
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/addons/vimrc	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/addons/vimrc	(revision 11330)
@@ -0,0 +1,228 @@
+
+" General setup{{{1
+" ----------------------------------------------------------------------
+" 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{{{1
+" ----------------------------------------------------------------------
+" 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 {{{1
+" -----------------------------------------------------------
+" updatecount   number of characters typed to cause a swap file update (0->disable)
+set uc=0
+" make no backups
+set nobackup
+" -----------------------------------------------------------}}}
+" Searching, Substituting {{{1
+" -----------------------------------------------------------
+" 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 {{{1
+" ----------------------------------------------------------------------
+" 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{{{1
+" ----------------------------------------------------------------------
+"stop highlightings when spce is pressed
+nnoremap <silent> <Space> :silent noh<Bar>echo<CR> 
+
+"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>
+
+"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 {{{1
+" ----------------------------------------------------------------------
+" 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 {{{1
+" ----------------------------------------------------------------------
+"" associate *.par with matlab filetype
+au BufRead,BufNewFile *.par setfiletype matlab
+au BufRead,BufNewFile *.tpl setfiletype html
+" ----------------------------------------------------------------------}}}
+" C special{{{1
+" ----------------------------------------------------------------------
+"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 
+" ----------------------------------------------------------------------}}}
+" TEX special{{{1
+" ----------------------------------------------------------------------
+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{{{1
+" ----------------------------------------------------------------------
+au BufRead,BufNewFile *.src setfiletype fortran
+" ----------------------------------------------------------------------}}}
+" InsertTabWrapper{{{1
+" ----------------------------------------------------------------------
+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 {{{1
+" ----------------------------------------------------------------------
+func Eatchar(pat)
+	let c = nr2char(getchar())
+	return (c =~ a:pat) ? '' : c
+endfunc
+au BufRead,BufNewFile *.html     iabbr <silent> H1 <h1></h1><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.html     iabbr <silent> H2 <h2></h2><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.html     iabbr <silent> H3 <h3></h3><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.html     iabbr <silent> CO <code></code><Left><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.html     iabbr <silent> PP <p></p><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.m        iabbr <silent> p1  disp('');<Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.m        iab <expr> p0  "disp('-------------- file: ".expand('%')." line: ".line(".")."');"
+au BufRead,BufNewFile *.c*       iabbr <silent> p1  printf("\n");<Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.c*,*.h   iabbr <silent> ER  _error_("");<Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.c*       ab VV VecView(ug,PETSC_VIEWER_STDOUT_WORLD);
+au BufRead,BufNewFile *.c*       ab AS _assert_();
+au BufRead,BufNewFile *.c*       iab <expr> p0  "printf(\"-------------- file: ".expand('%')." line: %i\\n\",__LINE__);"
+au BufRead,BufNewFile *.c*       iab <expr> pp0 "PetscSynchronizedPrintf(MPI_COMM_WORLD,\"-------------- file: ".expand('%')." line: %i\\n\",__LINE__);\nPetscSynchronizedFlush(MPI_COMM_WORLD);"
+"tex
+au BufRead,BufNewFile *.tex iab EQ 
+			\\begin{equation}
+			\<CR>\end{equation}<up><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.tex iab IT 
+			\\begin{itemize}
+			\<CR>\item 
+			\<CR>\end{itemize}<up><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.tex iab EN 
+			\\begin{enumerate}
+			\<CR>\item 
+			\<CR>\end{enumerate}<up><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.tex ab (()) \left( \right)
+"}}}
+" Skeletons {{{1
+au BufNewFile letter.tex   0r ~/.vim/xtr/skeleton/letter.tex
+"}}}
+"Status line{{{1
+set statusline=%t\ %l\ [%c,%l]
+"}}}
Index: /issm/trunk-jpl-damage/externalpackages/vim/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/vim/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/vim/install.sh	(revision 11330)
@@ -0,0 +1,26 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install src
+rm -rf vim72
+mkdir install src
+
+#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_TIER/externalpackages/vim/install" \
+	--with-gcc "/usr/bin/gcc"
+
+#Compile vim
+make
+make  install
Index: /issm/trunk-jpl-damage/externalpackages/xaifbooster/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/xaifbooster/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/xaifbooster/install.sh	(revision 11330)
@@ -0,0 +1,11 @@
+#!/bin/bash
+
+#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/trunk-jpl-damage/externalpackages/xerces/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/xerces/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/xerces/install.sh	(revision 11330)
@@ -0,0 +1,21 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install xerces-c-src_2_8_0 src
+mkdir install src
+
+#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/trunk-jpl-damage/externalpackages/yams/install.sh
===================================================================
--- /issm/trunk-jpl-damage/externalpackages/yams/install.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/externalpackages/yams/install.sh	(revision 11330)
@@ -0,0 +1,21 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install
+mkdir install
+
+#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/trunk-jpl-damage/install-sh
===================================================================
--- /issm/trunk-jpl-damage/install-sh	(revision 11330)
+++ /issm/trunk-jpl-damage/install-sh	(revision 11330)
@@ -0,0 +1,519 @@
+#!/bin/sh
+# install - install a program, script, or datafile
+
+scriptversion=2006-12-25.00
+
+# This originates from X11R5 (mit/util/scripts/install.sh), which was
+# later released in X11R6 (xc/config/util/install.sh) with the
+# following copyright and license.
+#
+# Copyright (C) 1994 X Consortium
+#
+# 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
+# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
+# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+# Except as contained in this notice, the name of the X Consortium shall not
+# be used in advertising or otherwise to promote the sale, use or other deal-
+# ings in this Software without prior written authorization from the X Consor-
+# tium.
+#
+#
+# FSF changes to this file are in the public domain.
+#
+# Calling this script install-sh is preferred over install.sh, to prevent
+# `make' implicit rules from creating a file called install from it
+# when there is no Makefile.
+#
+# This script is compatible with the BSD install script, but was written
+# from scratch.
+
+nl='
+'
+IFS=" ""	$nl"
+
+# set DOITPROG to echo to test this script
+
+# Don't use :- since 4.3BSD and earlier shells don't like it.
+doit=${DOITPROG-}
+if test -z "$doit"; then
+  doit_exec=exec
+else
+  doit_exec=$doit
+fi
+
+# Put in absolute file names if you don't have them in your path;
+# or use environment vars.
+
+chgrpprog=${CHGRPPROG-chgrp}
+chmodprog=${CHMODPROG-chmod}
+chownprog=${CHOWNPROG-chown}
+cmpprog=${CMPPROG-cmp}
+cpprog=${CPPROG-cp}
+mkdirprog=${MKDIRPROG-mkdir}
+mvprog=${MVPROG-mv}
+rmprog=${RMPROG-rm}
+stripprog=${STRIPPROG-strip}
+
+posix_glob='?'
+initialize_posix_glob='
+  test "$posix_glob" != "?" || {
+    if (set -f) 2>/dev/null; then
+      posix_glob=
+    else
+      posix_glob=:
+    fi
+  }
+'
+
+posix_mkdir=
+
+# Desired mode of installed file.
+mode=0755
+
+chgrpcmd=
+chmodcmd=$chmodprog
+chowncmd=
+mvcmd=$mvprog
+rmcmd="$rmprog -f"
+stripcmd=
+
+src=
+dst=
+dir_arg=
+dst_arg=
+
+copy_on_change=false
+no_target_directory=
+
+usage="\
+Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
+   or: $0 [OPTION]... SRCFILES... DIRECTORY
+   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
+   or: $0 [OPTION]... -d DIRECTORIES...
+
+In the 1st form, copy SRCFILE to DSTFILE.
+In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
+In the 4th, create DIRECTORIES.
+
+Options:
+     --help     display this help and exit.
+     --version  display version info and exit.
+
+  -c            (ignored)
+  -C            install only if different (preserve the last data modification time)
+  -d            create directories instead of installing files.
+  -g GROUP      $chgrpprog installed files to GROUP.
+  -m MODE       $chmodprog installed files to MODE.
+  -o USER       $chownprog installed files to USER.
+  -s            $stripprog installed files.
+  -t DIRECTORY  install into DIRECTORY.
+  -T            report an error if DSTFILE is a directory.
+
+Environment variables override the default commands:
+  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
+  RMPROG STRIPPROG
+"
+
+while test $# -ne 0; do
+  case $1 in
+    -c) ;;
+
+    -C) copy_on_change=true;;
+
+    -d) dir_arg=true;;
+
+    -g) chgrpcmd="$chgrpprog $2"
+	shift;;
+
+    --help) echo "$usage"; exit $?;;
+
+    -m) mode=$2
+	case $mode in
+	  *' '* | *'	'* | *'
+'*	  | *'*'* | *'?'* | *'['*)
+	    echo "$0: invalid mode: $mode" >&2
+	    exit 1;;
+	esac
+	shift;;
+
+    -o) chowncmd="$chownprog $2"
+	shift;;
+
+    -s) stripcmd=$stripprog;;
+
+    -t) dst_arg=$2
+	shift;;
+
+    -T) no_target_directory=true;;
+
+    --version) echo "$0 $scriptversion"; exit $?;;
+
+    --)	shift
+	break;;
+
+    -*)	echo "$0: invalid option: $1" >&2
+	exit 1;;
+
+    *)  break;;
+  esac
+  shift
+done
+
+if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
+  # When -d is used, all remaining arguments are directories to create.
+  # When -t is used, the destination is already specified.
+  # Otherwise, the last argument is the destination.  Remove it from $@.
+  for arg
+  do
+    if test -n "$dst_arg"; then
+      # $@ is not empty: it contains at least $arg.
+      set fnord "$@" "$dst_arg"
+      shift # fnord
+    fi
+    shift # arg
+    dst_arg=$arg
+  done
+fi
+
+if test $# -eq 0; then
+  if test -z "$dir_arg"; then
+    echo "$0: no input file specified." >&2
+    exit 1
+  fi
+  # It's OK to call `install-sh -d' without argument.
+  # This can happen when creating conditional directories.
+  exit 0
+fi
+
+if test -z "$dir_arg"; then
+  trap '(exit $?); exit' 1 2 13 15
+
+  # Set umask so as not to create temps with too-generous modes.
+  # However, 'strip' requires both read and write access to temps.
+  case $mode in
+    # Optimize common cases.
+    *644) cp_umask=133;;
+    *755) cp_umask=22;;
+
+    *[0-7])
+      if test -z "$stripcmd"; then
+	u_plus_rw=
+      else
+	u_plus_rw='% 200'
+      fi
+      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
+    *)
+      if test -z "$stripcmd"; then
+	u_plus_rw=
+      else
+	u_plus_rw=,u+rw
+      fi
+      cp_umask=$mode$u_plus_rw;;
+  esac
+fi
+
+for src
+do
+  # Protect names starting with `-'.
+  case $src in
+    -*) src=./$src;;
+  esac
+
+  if test -n "$dir_arg"; then
+    dst=$src
+    dstdir=$dst
+    test -d "$dstdir"
+    dstdir_status=$?
+  else
+
+    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
+    # might cause directories to be created, which would be especially bad
+    # if $src (and thus $dsttmp) contains '*'.
+    if test ! -f "$src" && test ! -d "$src"; then
+      echo "$0: $src does not exist." >&2
+      exit 1
+    fi
+
+    if test -z "$dst_arg"; then
+      echo "$0: no destination specified." >&2
+      exit 1
+    fi
+
+    dst=$dst_arg
+    # Protect names starting with `-'.
+    case $dst in
+      -*) dst=./$dst;;
+    esac
+
+    # If destination is a directory, append the input filename; won't work
+    # if double slashes aren't ignored.
+    if test -d "$dst"; then
+      if test -n "$no_target_directory"; then
+	echo "$0: $dst_arg: Is a directory" >&2
+	exit 1
+      fi
+      dstdir=$dst
+      dst=$dstdir/`basename "$src"`
+      dstdir_status=0
+    else
+      # Prefer dirname, but fall back on a substitute if dirname fails.
+      dstdir=`
+	(dirname "$dst") 2>/dev/null ||
+	expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	     X"$dst" : 'X\(//\)[^/]' \| \
+	     X"$dst" : 'X\(//\)$' \| \
+	     X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
+	echo X"$dst" |
+	    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\/\)[^/].*/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\/\)$/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\).*/{
+		   s//\1/
+		   q
+		 }
+		 s/.*/./; q'
+      `
+
+      test -d "$dstdir"
+      dstdir_status=$?
+    fi
+  fi
+
+  obsolete_mkdir_used=false
+
+  if test $dstdir_status != 0; then
+    case $posix_mkdir in
+      '')
+	# Create intermediate dirs using mode 755 as modified by the umask.
+	# This is like FreeBSD 'install' as of 1997-10-28.
+	umask=`umask`
+	case $stripcmd.$umask in
+	  # Optimize common cases.
+	  *[2367][2367]) mkdir_umask=$umask;;
+	  .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
+
+	  *[0-7])
+	    mkdir_umask=`expr $umask + 22 \
+	      - $umask % 100 % 40 + $umask % 20 \
+	      - $umask % 10 % 4 + $umask % 2
+	    `;;
+	  *) mkdir_umask=$umask,go-w;;
+	esac
+
+	# With -d, create the new directory with the user-specified mode.
+	# Otherwise, rely on $mkdir_umask.
+	if test -n "$dir_arg"; then
+	  mkdir_mode=-m$mode
+	else
+	  mkdir_mode=
+	fi
+
+	posix_mkdir=false
+	case $umask in
+	  *[123567][0-7][0-7])
+	    # POSIX mkdir -p sets u+wx bits regardless of umask, which
+	    # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
+	    ;;
+	  *)
+	    tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+	    trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
+
+	    if (umask $mkdir_umask &&
+		exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
+	    then
+	      if test -z "$dir_arg" || {
+		   # Check for POSIX incompatibilities with -m.
+		   # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+		   # other-writeable bit of parent directory when it shouldn't.
+		   # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+		   ls_ld_tmpdir=`ls -ld "$tmpdir"`
+		   case $ls_ld_tmpdir in
+		     d????-?r-*) different_mode=700;;
+		     d????-?--*) different_mode=755;;
+		     *) false;;
+		   esac &&
+		   $mkdirprog -m$different_mode -p -- "$tmpdir" && {
+		     ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
+		     test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+		   }
+		 }
+	      then posix_mkdir=:
+	      fi
+	      rmdir "$tmpdir/d" "$tmpdir"
+	    else
+	      # Remove any dirs left behind by ancient mkdir implementations.
+	      rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
+	    fi
+	    trap '' 0;;
+	esac;;
+    esac
+
+    if
+      $posix_mkdir && (
+	umask $mkdir_umask &&
+	$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+      )
+    then :
+    else
+
+      # The umask is ridiculous, or mkdir does not conform to POSIX,
+      # or it failed possibly due to a race condition.  Create the
+      # directory the slow way, step by step, checking for races as we go.
+
+      case $dstdir in
+	/*) prefix='/';;
+	-*) prefix='./';;
+	*)  prefix='';;
+      esac
+
+      eval "$initialize_posix_glob"
+
+      oIFS=$IFS
+      IFS=/
+      $posix_glob set -f
+      set fnord $dstdir
+      shift
+      $posix_glob set +f
+      IFS=$oIFS
+
+      prefixes=
+
+      for d
+      do
+	test -z "$d" && continue
+
+	prefix=$prefix$d
+	if test -d "$prefix"; then
+	  prefixes=
+	else
+	  if $posix_mkdir; then
+	    (umask=$mkdir_umask &&
+	     $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+	    # Don't fail if two instances are running concurrently.
+	    test -d "$prefix" || exit 1
+	  else
+	    case $prefix in
+	      *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+	      *) qprefix=$prefix;;
+	    esac
+	    prefixes="$prefixes '$qprefix'"
+	  fi
+	fi
+	prefix=$prefix/
+      done
+
+      if test -n "$prefixes"; then
+	# Don't fail if two instances are running concurrently.
+	(umask $mkdir_umask &&
+	 eval "\$doit_exec \$mkdirprog $prefixes") ||
+	  test -d "$dstdir" || exit 1
+	obsolete_mkdir_used=true
+      fi
+    fi
+  fi
+
+  if test -n "$dir_arg"; then
+    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
+    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
+      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
+  else
+
+    # Make a couple of temp file names in the proper directory.
+    dsttmp=$dstdir/_inst.$$_
+    rmtmp=$dstdir/_rm.$$_
+
+    # Trap to clean up those temp files at exit.
+    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
+
+    # Copy the file name to the temp name.
+    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
+
+    # and set any options; do chmod last to preserve setuid bits.
+    #
+    # If any of these fail, we abort the whole thing.  If we want to
+    # ignore errors from any of these, just make sure not to ignore
+    # errors from the above "$doit $cpprog $src $dsttmp" command.
+    #
+    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
+    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
+    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
+
+    # If -C, don't bother to copy if it wouldn't change the file.
+    if $copy_on_change &&
+       old=`LC_ALL=C ls -dlL "$dst"	2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"	2>/dev/null` &&
+
+       eval "$initialize_posix_glob" &&
+       $posix_glob set -f &&
+       set X $old && old=:$2:$4:$5:$6 &&
+       set X $new && new=:$2:$4:$5:$6 &&
+       $posix_glob set +f &&
+
+       test "$old" = "$new" &&
+       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
+    then
+      rm -f "$dsttmp"
+    else
+      # Rename the file to the real destination.
+      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
+
+      # The rename failed, perhaps because mv can't rename something else
+      # to itself, or perhaps because mv is so ancient that it does not
+      # support -f.
+      {
+	# Now remove or move aside any old file at destination location.
+	# We try this two ways since rm can't unlink itself on some
+	# systems and the destination file might be busy for other
+	# reasons.  In this case, the final cleanup might fail but the new
+	# file should still install successfully.
+	{
+	  test ! -f "$dst" ||
+	  $doit $rmcmd -f "$dst" 2>/dev/null ||
+	  { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+	    { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+	  } ||
+	  { echo "$0: cannot unlink or rename $dst" >&2
+	    (exit 1); exit 1
+	  }
+	} &&
+
+	# Now rename the file to the real destination.
+	$doit $mvcmd "$dsttmp" "$dst"
+      }
+    fi || exit 1
+
+    trap '' 0
+  fi
+done
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-end: "$"
+# End:
Index: /issm/trunk-jpl-damage/ltmain.sh
===================================================================
--- /issm/trunk-jpl-damage/ltmain.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/ltmain.sh	(revision 11330)
@@ -0,0 +1,8406 @@
+# Generated from ltmain.m4sh.
+
+# ltmain.sh (GNU libtool) 2.2.6b
+# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
+
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007 2008 Free Software Foundation, Inc.
+# 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
+#     --tag=TAG            use configuration variables from tag TAG
+# -v, --verbose            print informational messages (default)
+#     --version            print version information
+# -h, --help               print short or long help message
+#
+# 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.
+# 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.2.6b
+#       automake:		$automake_version
+#       autoconf:		$autoconf_version
+#
+# Report bugs to <bug-libtool@gnu.org>.
+
+PROGRAM=ltmain.sh
+PACKAGE=libtool
+VERSION=2.2.6b
+TIMESTAMP=""
+package_revision=1.3017
+
+# 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
+
+# NLS nuisances: We save the old values to restore during execute mode.
+# Only set LANG and LC_ALL to C if already set.
+# These must not be set unconditionally because not all systems understand
+# e.g. LANG=C (notably SCO).
+lt_user_locale=
+lt_safe_locale=
+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
+
+$lt_unset CDPATH
+
+
+
+
+
+: ${CP="cp -f"}
+: ${ECHO="echo"}
+: ${EGREP="/bin/grep -E"}
+: ${FGREP="/bin/grep -F"}
+: ${GREP="/bin/grep"}
+: ${LN_S="ln -s"}
+: ${MAKE="make"}
+: ${MKDIR="mkdir"}
+: ${MV="mv -f"}
+: ${RM="rm -f"}
+: ${SED="/bin/sed"}
+: ${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_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 "X${1}" | $Xsed -e "$dirname"`
+  if test "X$func_dirname_result" = "X${1}"; then
+    func_dirname_result="${3}"
+  else
+    func_dirname_result="$func_dirname_result${2}"
+  fi
+  func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"`
+}
+
+# Generated shell functions inserted here.
+
+# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
+# is ksh but when the shell is invoked as "sh" and the current value of
+# the _XPG environment variable is not equal to 1 (one), the special
+# positional parameter $0, within a function call, is the name of the
+# function.
+progpath="$0"
+
+# The name of this program:
+# In the unlikely event $progname began with a '-', it would play havoc with
+# func_echo (imagine progname=-n), so we prepend ./ in that case:
+func_dirname_and_basename "$progpath"
+progname=$func_basename_result
+case $progname in
+  -*) progname=./$progname ;;
+esac
+
+# Make sure we have an absolute path for reexecution:
+case $progpath in
+  [\\/]*|[A-Za-z]:\\*) ;;
+  *[\\/]*)
+     progdir=$func_dirname_result
+     progdir=`cd "$progdir" && pwd`
+     progpath="$progdir/$progname"
+     ;;
+  *)
+     save_IFS="$IFS"
+     IFS=:
+     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'
+
+# 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${mode+: }$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_error arg...
+# Echo program name prefixed message to standard error.
+func_error ()
+{
+    $ECHO "$progname${mode+: }$mode: "${1+"$@"} 1>&2
+}
+
+# func_warning arg...
+# Echo program name prefixed warning message to standard error.
+func_warning ()
+{
+    $opt_warning && $ECHO "$progname${mode+: }$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 "X$my_directory_path" | $Xsed -e "$dirname"`
+      done
+      my_dir_list=`$ECHO "X$my_dir_list" | $Xsed -e '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 "X$my_tmpdir" | $Xsed
+}
+
+
+# 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 "X$1" | $Xsed -e "$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 "X$1" | $Xsed \
+	    -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_version
+# Echo version message to standard output and exit.
+func_version ()
+{
+    $SED -n '/^# '$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 ()
+{
+    $SED -n '/^# Usage:/,/# -h/ {
+        s/^# //
+	s/^# *$//
+	s/\$progname/'$progname'/
+	p
+    }' < "$progpath"
+    $ECHO
+    $ECHO "run \`$progname --help | more' for full usage"
+    exit $?
+}
+
+# func_help
+# Echo long help message to standard output and exit.
+func_help ()
+{
+    $SED -n '/^# Usage:/,/# Report bugs to/ {
+        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 --version) 2>/dev/null |$SED 1q`"'/
+	s/\$autoconf_version/'"`(autoconf --version) 2>/dev/null |$SED 1q`"'/
+	p
+     }' < "$progpath"
+    exit $?
+}
+
+# func_missing_arg argname
+# Echo program name prefixed message to standard error and set global
+# exit_cmd.
+func_missing_arg ()
+{
+    func_error "missing argument for $1"
+    exit_cmd=exit
+}
+
+exit_cmd=:
+
+
+
+
+
+# Check that we have a working $ECHO.
+if test "X$1" = X--no-reexec; then
+  # Discard the --no-reexec flag, and continue.
+  shift
+elif test "X$1" = X--fallback-echo; then
+  # Avoid inline document here, it may be left over
+  :
+elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t'; then
+  # Yippee, $ECHO works!
+  :
+else
+  # Restart under the correct shell, and then maybe $ECHO will work.
+  exec $SHELL "$progpath" --no-reexec ${1+"$@"}
+fi
+
+if test "X$1" = X--fallback-echo; then
+  # used as fallback echo
+  shift
+  cat <<EOF
+$*
+EOF
+  exit $EXIT_SUCCESS
+fi
+
+magic="%%%MAGIC variable%%%"
+magic_exe="%%%MAGIC EXE variable%%%"
+
+# Global variables.
+# $mode is unset
+nonopt=
+execute_dlfiles=
+preserve_args=
+lo2o="s/\\.lo\$/.${objext}/"
+o2lo="s/\\.${objext}\$/.lo/"
+extracted_archives=
+extracted_serial=0
+
+opt_dry_run=false
+opt_duplicate_deps=false
+opt_silent=false
+opt_debug=:
+
+# If this variable is set in any of the actions, the command in it
+# will be execed at the end.  This prevents here-documents from being
+# left over by shells.
+exec_cmd=
+
+# 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
+}
+
+# Parse options once, thoroughly.  This comes as soon as possible in
+# the script to make things like `libtool --version' happen quickly.
+{
+
+  # Shorthand for --mode=foo, only valid as the first argument
+  case $1 in
+  clean|clea|cle|cl)
+    shift; set dummy --mode clean ${1+"$@"}; shift
+    ;;
+  compile|compil|compi|comp|com|co|c)
+    shift; set dummy --mode compile ${1+"$@"}; shift
+    ;;
+  execute|execut|execu|exec|exe|ex|e)
+    shift; set dummy --mode execute ${1+"$@"}; shift
+    ;;
+  finish|finis|fini|fin|fi|f)
+    shift; set dummy --mode finish ${1+"$@"}; shift
+    ;;
+  install|instal|insta|inst|ins|in|i)
+    shift; set dummy --mode install ${1+"$@"}; shift
+    ;;
+  link|lin|li|l)
+    shift; set dummy --mode link ${1+"$@"}; shift
+    ;;
+  uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)
+    shift; set dummy --mode uninstall ${1+"$@"}; shift
+    ;;
+  esac
+
+  # Parse non-mode specific arguments:
+  while test "$#" -gt 0; do
+    opt="$1"
+    shift
+
+    case $opt in
+      --config)		func_config					;;
+
+      --debug)		preserve_args="$preserve_args $opt"
+			func_echo "enabling shell trace mode"
+			opt_debug='set -x'
+			$opt_debug
+			;;
+
+      -dlopen)		test "$#" -eq 0 && func_missing_arg "$opt" && break
+			execute_dlfiles="$execute_dlfiles $1"
+			shift
+			;;
+
+      --dry-run | -n)	opt_dry_run=:					;;
+      --features)       func_features					;;
+      --finish)		mode="finish"					;;
+
+      --mode)		test "$#" -eq 0 && func_missing_arg "$opt" && break
+			case $1 in
+			  # Valid mode arguments:
+			  clean)	;;
+			  compile)	;;
+			  execute)	;;
+			  finish)	;;
+			  install)	;;
+			  link)		;;
+			  relink)	;;
+			  uninstall)	;;
+
+			  # Catch anything else as an error
+			  *) func_error "invalid argument for $opt"
+			     exit_cmd=exit
+			     break
+			     ;;
+		        esac
+
+			mode="$1"
+			shift
+			;;
+
+      --preserve-dup-deps)
+			opt_duplicate_deps=:				;;
+
+      --quiet|--silent)	preserve_args="$preserve_args $opt"
+			opt_silent=:
+			;;
+
+      --verbose| -v)	preserve_args="$preserve_args $opt"
+			opt_silent=false
+			;;
+
+      --tag)		test "$#" -eq 0 && func_missing_arg "$opt" && break
+			preserve_args="$preserve_args $opt $1"
+			func_enable_tag "$1"	# tagname is set here
+			shift
+			;;
+
+      # Separate optargs to long options:
+      -dlopen=*|--mode=*|--tag=*)
+			func_opt_split "$opt"
+			set dummy "$func_opt_split_opt" "$func_opt_split_arg" ${1+"$@"}
+			shift
+			;;
+
+      -\?|-h)		func_usage					;;
+      --help)		opt_help=:					;;
+      --version)	func_version					;;
+
+      -*)		func_fatal_help "unrecognized option \`$opt'"	;;
+
+      *)		nonopt="$opt"
+			break
+			;;
+    esac
+  done
+
+
+  case $host in
+    *cygwin* | *mingw* | *pw32* | *cegcc*)
+      # don't eliminate duplications in $postdeps and $predeps
+      opt_duplicate_compiler_generated_deps=:
+      ;;
+    *)
+      opt_duplicate_compiler_generated_deps=$opt_duplicate_deps
+      ;;
+  esac
+
+  # Having warned about all mis-specified options, bail out if
+  # anything was wrong.
+  $exit_cmd $EXIT_FAILURE
+}
+
+# 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
+}
+
+
+## ----------- ##
+##    Main.    ##
+## ----------- ##
+
+$opt_help || {
+  # Sanity checks first:
+  func_check_version_match
+
+  if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
+    func_fatal_configuration "not configured to build any kind of library"
+  fi
+
+  test -z "$mode" && func_fatal_error "error: you must specify a MODE."
+
+
+  # Darwin sucks
+  eval std_shrext=\"$shrext_cmds\"
+
+
+  # Only execute mode is allowed to have -dlopen flags.
+  if test -n "$execute_dlfiles" && test "$mode" != execute; then
+    func_error "unrecognized option \`-dlopen'"
+    $ECHO "$help" 1>&2
+    exit $EXIT_FAILURE
+  fi
+
+  # Change the help message to a mode-specific one.
+  generic_help="$help"
+  help="Try \`$progname --help --mode=$mode' for more information."
+}
+
+
+# func_lalib_p file
+# 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_ltwrapper_scriptname_result=""
+    if func_ltwrapper_executable_p "$1"; then
+	func_dirname_and_basename "$1" "" "."
+	func_stripname '' '.exe' "$func_basename_result"
+	func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper"
+    fi
+}
+
+# func_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_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_quote_for_eval "$arg"
+	CC_quoted="$CC_quoted $func_quote_for_eval_result"
+      done
+      case $@ in
+      # Blanks in the command may have been stripped by the calling shell,
+      # but not from the CC environment variable when configure was run.
+      " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) ;;
+      # 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_quote_for_eval "$arg"
+	      CC_quoted="$CC_quoted $func_quote_for_eval_result"
+	    done
+	    case "$@ " in
+	      " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*)
+	      # 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}"
+    }
+}
+
+# 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)
+          pie_flag="$pie_flag $arg"
+	  continue
+	  ;;
+
+	-shared | -static | -prefer-pic | -prefer-non-pic)
+	  later="$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_quote_for_eval "$arg"
+	    lastarg="$lastarg $func_quote_for_eval_result"
+	  done
+	  IFS="$save_ifs"
+	  func_stripname ' ' '' "$lastarg"
+	  lastarg=$func_stripname_result
+
+	  # Add the arguments to base_compile.
+	  base_compile="$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_quote_for_eval "$lastarg"
+      base_compile="$base_compile $func_quote_for_eval_result"
+    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 | *.obj | *.sx)
+      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 "X$srcfile" | $Xsed -e 's%^.*/%%' -e '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
+      removelist="$removelist $output_obj"
+      $ECHO "$srcfile" > "$lockfile"
+    fi
+
+    $opt_dry_run || $RM $removelist
+    removelist="$removelist $lockfile"
+    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15
+
+    if test -n "$fix_srcfile_path"; then
+      eval srcfile=\"$fix_srcfile_path\"
+    fi
+    func_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
+	command="$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
+	command="$command -o $obj"
+      fi
+
+      # Suppress compiler output if we already did a PIC compilation.
+      command="$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 "$mode" = compile && func_mode_compile ${1+"$@"}
+}
+
+func_mode_help ()
+{
+    # We need to display help for each of the modes.
+    case $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 building PIC objects only
+  -prefer-non-pic   try to building 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
+
+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 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
+  -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
+
+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 \`$mode'"
+        ;;
+    esac
+
+    $ECHO
+    $ECHO "Try \`$progname --help' for more information about other modes."
+
+    exit $?
+}
+
+  # Now that we've collected a possible --mode arg, show help if necessary
+  $opt_help && func_mode_help
+
+
+# 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 $execute_dlfiles; do
+      test -f "$file" \
+	|| func_fatal_help "\`$file' is not a file"
+
+      dir=
+      case $file in
+      *.la)
+	# 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
+	  dir="$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
+      -*) ;;
+      *)
+	# 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_quote_for_eval "$file"
+      args="$args $func_quote_for_eval_result"
+    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 "$mode" = execute && func_mode_execute ${1+"$@"}
+
+
+# func_mode_finish arg...
+func_mode_finish ()
+{
+    $opt_debug
+    libdirs="$nonopt"
+    admincmds=
+
+    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+      for dir
+      do
+	libdirs="$libdirs $dir"
+      done
+
+      for libdir in $libdirs; do
+	if test -n "$finish_cmds"; then
+	  # 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" || admincmds="$admincmds
+       $cmds"
+	fi
+      done
+    fi
+
+    # Exit here if they wanted silent mode.
+    $opt_silent && exit $EXIT_SUCCESS
+
+    $ECHO "X----------------------------------------------------------------------" | $Xsed
+    $ECHO "Libraries have been installed in:"
+    for libdir in $libdirs; do
+      $ECHO "   $libdir"
+    done
+    $ECHO
+    $ECHO "If you ever happen to want to link against installed libraries"
+    $ECHO "in a given directory, LIBDIR, you must either use libtool, and"
+    $ECHO "specify the full pathname of the library, or use the \`-LLIBDIR'"
+    $ECHO "flag during linking and do at least one of the following:"
+    if test -n "$shlibpath_var"; then
+      $ECHO "   - add LIBDIR to the \`$shlibpath_var' environment variable"
+      $ECHO "     during execution"
+    fi
+    if test -n "$runpath_var"; then
+      $ECHO "   - add LIBDIR to the \`$runpath_var' environment variable"
+      $ECHO "     during linking"
+    fi
+    if test -n "$hardcode_libdir_flag_spec"; then
+      libdir=LIBDIR
+      eval flag=\"$hardcode_libdir_flag_spec\"
+
+      $ECHO "   - use the \`$flag' linker flag"
+    fi
+    if test -n "$admincmds"; then
+      $ECHO "   - have your system administrator run these commands:$admincmds"
+    fi
+    if test -f /etc/ld.so.conf; then
+      $ECHO "   - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
+    fi
+    $ECHO
+
+    $ECHO "See any operating system documentation about shared libraries for"
+    case $host in
+      solaris2.[6789]|solaris2.1[0-9])
+        $ECHO "more information, such as the ld(1), crle(1) and ld.so(8) manual"
+	$ECHO "pages."
+	;;
+      *)
+        $ECHO "more information, such as the ld(1) and ld.so(8) manual pages."
+        ;;
+    esac
+    $ECHO "X----------------------------------------------------------------------" | $Xsed
+    exit $EXIT_SUCCESS
+}
+
+test "$mode" = finish && func_mode_finish ${1+"$@"}
+
+
+# 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.
+       $ECHO "X$nonopt" | $GREP shtool >/dev/null; 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"
+    install_prog="$install_prog$func_quote_for_eval_result"
+
+    # We need to accept at least all the BSD install flags.
+    dest=
+    files=
+    opts=
+    prev=
+    install_type=
+    isdir=no
+    stripme=
+    for arg
+    do
+      if test -n "$dest"; then
+	files="$files $dest"
+	dest=$arg
+	continue
+      fi
+
+      case $arg in
+      -d) isdir=yes ;;
+      -f)
+	case " $install_prog " in
+	*[\\\ /]cp\ *) ;;
+	*) prev=$arg ;;
+	esac
+	;;
+      -g | -m | -o)
+	prev=$arg
+	;;
+      -s)
+	stripme=" -s"
+	continue
+	;;
+      -*)
+	;;
+      *)
+	# If the previous option needed an argument, then skip it.
+	if test -n "$prev"; then
+	  prev=
+	else
+	  dest=$arg
+	  continue
+	fi
+	;;
+      esac
+
+      # Aesthetically quote the argument.
+      func_quote_for_eval "$arg"
+      install_prog="$install_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 -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.
+	staticlibs="$staticlibs $file"
+	;;
+
+      *.la)
+	# 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 "*) ;;
+	  *) current_libdirs="$current_libdirs $libdir" ;;
+	  esac
+	else
+	  # Note the libdir as a future libdir.
+	  case "$future_libdirs " in
+	  *" $libdir "*) ;;
+	  *) future_libdirs="$future_libdirs $libdir" ;;
+	  esac
+	fi
+
+	func_dirname "$file" "/" ""
+	dir="$func_dirname_result"
+	dir="$dir$objdir"
+
+	if test -n "$relink_command"; then
+	  # Determine the prefix the user has applied to our future dir.
+	  inst_prefix_dir=`$ECHO "X$destdir" | $Xsed -e "s%$libdir\$%%"`
+
+	  # 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 "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"`
+	  else
+	    relink_command=`$ECHO "X$relink_command" | $Xsed -e "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_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" && staticlibs="$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 "X$lib" | $Xsed -e '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 "X$relink_command" | $Xsed -e '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 "X$file$stripped_ext" | $Xsed -e "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_show_eval "$install_prog \$file \$oldlib" 'exit $?'
+
+      if test -n "$stripme" && test -n "$old_striplib"; then
+	func_show_eval "$old_striplib $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 "$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
+
+/* 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 "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+	  for progfile in $progfiles; do
+	    func_verbose "extracting global C symbols from \`$progfile'"
+	    $opt_dry_run || eval "$NM $progfile | $global_symbol_pipe >> '$nlist'"
+	  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"
+	  $opt_dry_run || {
+	    eval '$ECHO ": $name " >> "$nlist"'
+	    eval "$NM $dlprefile 2>/dev/null | $global_symbol_pipe >> '$nlist'"
+	  }
+	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;
+"
+	  case $host in
+	  *cygwin* | *mingw* | *cegcc* )
+	    $ECHO >> "$output_objdir/$my_dlsyms" "\
+/* DATA imports from DLLs on WIN32 con't be const, because
+   runtime relocations are performed -- see ld's documentation
+   on pseudo-relocs.  */"
+	    lt_dlsym_const= ;;
+	  *osf5*)
+	    echo >> "$output_objdir/$my_dlsyms" "\
+/* This system does not cope well with relocations in const data */"
+	    lt_dlsym_const= ;;
+	  *)
+	    lt_dlsym_const=const ;;
+	  esac
+
+	  $ECHO >> "$output_objdir/$my_dlsyms" "\
+extern $lt_dlsym_const lt_dlsymlist
+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) ;;
+	  *) symtab_cflags="$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 "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+	    finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+	  else
+	    compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
+	    finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
+	  fi
+	  ;;
+	*)
+	  compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
+	  finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
+	  ;;
+	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 "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"`
+      finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "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.
+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
+    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |
+       $EGREP 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then
+      win32_nmres=`eval $NM -f posix -A $1 |
+	$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_extract_an_archive dir oldlib
+func_extract_an_archive ()
+{
+    $opt_debug
+    f_ex_an_ar_dir="$1"; shift
+    f_ex_an_ar_oldlib="$1"
+    func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" 'exit $?'
+    if ($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 | $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 | $NL2SP`
+    done
+
+    func_extract_archives_result="$my_oldobjs"
+}
+
+
+
+# func_emit_wrapper_part1 [arg=no]
+#
+# Emit the first part of a libtool wrapper script on stdout.
+# For more information, see the description associated with
+# func_emit_wrapper(), below.
+func_emit_wrapper_part1 ()
+{
+	func_emit_wrapper_part1_arg1=no
+	if test -n "$1" ; then
+	  func_emit_wrapper_part1_arg1=$1
+	fi
+
+	$ECHO "\
+#! $SHELL
+
+# $output - temporary wrapper script for $objdir/$outputname
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+#
+# The $output program cannot be directly executed until all the libtool
+# libraries that it depends on are installed.
+#
+# This wrapper script should never be moved out of the build directory.
+# If it is, it will not operate correctly.
+
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed='${SED} -e 1s/^X//'
+sed_quote_subst='$sed_quote_subst'
+
+# Be Bourne compatible
+if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '\${1+\"\$@\"}'='\"\$@\"'
+  setopt NO_GLOB_SUBST
+else
+  case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+relink_command=\"$relink_command\"
+
+# This environment variable determines our operation mode.
+if test \"\$libtool_install_magic\" = \"$magic\"; then
+  # install mode needs the following variables:
+  generated_by_libtool_version='$macro_version'
+  notinst_deplibs='$notinst_deplibs'
+else
+  # When we are sourced in execute mode, \$file and \$ECHO are already set.
+  if test \"\$libtool_execute_magic\" != \"$magic\"; then
+    ECHO=\"$qecho\"
+    file=\"\$0\"
+    # Make sure echo works.
+    if test \"X\$1\" = X--no-reexec; then
+      # Discard the --no-reexec flag, and continue.
+      shift
+    elif test \"X\`{ \$ECHO '\t'; } 2>/dev/null\`\" = 'X\t'; then
+      # Yippee, \$ECHO works!
+      :
+    else
+      # Restart under the correct shell, and then maybe \$ECHO will work.
+      exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"}
+    fi
+  fi\
+"
+	$ECHO "\
+
+  # Find the directory that this script lives in.
+  thisdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\`
+  test \"x\$thisdir\" = \"x\$file\" && thisdir=.
+
+  # Follow symbolic links until we get to the real thisdir.
+  file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\`
+  while test -n \"\$file\"; do
+    destdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\`
+
+    # If there was a directory component, then change thisdir.
+    if test \"x\$destdir\" != \"x\$file\"; then
+      case \"\$destdir\" in
+      [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
+      *) thisdir=\"\$thisdir/\$destdir\" ;;
+      esac
+    fi
+
+    file=\`\$ECHO \"X\$file\" | \$Xsed -e 's%^.*/%%'\`
+    file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\`
+  done
+"
+}
+# end: func_emit_wrapper_part1
+
+# func_emit_wrapper_part2 [arg=no]
+#
+# Emit the second part of a libtool wrapper script on stdout.
+# For more information, see the description associated with
+# func_emit_wrapper(), below.
+func_emit_wrapper_part2 ()
+{
+	func_emit_wrapper_part2_arg1=no
+	if test -n "$1" ; then
+	  func_emit_wrapper_part2_arg1=$1
+	fi
+
+	$ECHO "\
+
+  # Usually 'no', except on cygwin/mingw when embedded into
+  # the cwrapper.
+  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_part2_arg1
+  if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then
+    # special case for '.'
+    if test \"\$thisdir\" = \".\"; then
+      thisdir=\`pwd\`
+    fi
+    # remove .libs from thisdir
+    case \"\$thisdir\" in
+    *[\\\\/]$objdir ) thisdir=\`\$ECHO \"X\$thisdir\" | \$Xsed -e 's%[\\\\/][^\\\\/]*$%%'\` ;;
+    $objdir )   thisdir=. ;;
+    esac
+  fi
+
+  # Try to get the absolute directory name.
+  absdir=\`cd \"\$thisdir\" && pwd\`
+  test -n \"\$absdir\" && thisdir=\"\$absdir\"
+"
+
+	if test "$fast_install" = yes; then
+	  $ECHO "\
+  program=lt-'$outputname'$exeext
+  progdir=\"\$thisdir/$objdir\"
+
+  if test ! -f \"\$progdir/\$program\" ||
+     { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
+       test \"X\$file\" != \"X\$progdir/\$program\"; }; then
+
+    file=\"\$\$-\$program\"
+
+    if test ! -d \"\$progdir\"; then
+      $MKDIR \"\$progdir\"
+    else
+      $RM \"\$progdir/\$file\"
+    fi"
+
+	  $ECHO "\
+
+    # relink executable if necessary
+    if test -n \"\$relink_command\"; then
+      if relink_command_output=\`eval \$relink_command 2>&1\`; then :
+      else
+	$ECHO \"\$relink_command_output\" >&2
+	$RM \"\$progdir/\$file\"
+	exit 1
+      fi
+    fi
+
+    $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
+    { $RM \"\$progdir/\$program\";
+      $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; }
+    $RM \"\$progdir/\$file\"
+  fi"
+	else
+	  $ECHO "\
+  program='$outputname'
+  progdir=\"\$thisdir/$objdir\"
+"
+	fi
+
+	$ECHO "\
+
+  if test -f \"\$progdir/\$program\"; then"
+
+	# Export our shlibpath_var if we have one.
+	if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+	  $ECHO "\
+    # Add our own library path to $shlibpath_var
+    $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
+
+    # Some systems cannot cope with colon-terminated $shlibpath_var
+    # The second colon is a workaround for a bug in BeOS R4 sed
+    $shlibpath_var=\`\$ECHO \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\`
+
+    export $shlibpath_var
+"
+	fi
+
+	# fixup the dll searchpath if we need to.
+	if test -n "$dllsearchpath"; then
+	  $ECHO "\
+    # Add the dll search path components to the executable PATH
+    PATH=$dllsearchpath:\$PATH
+"
+	fi
+
+	$ECHO "\
+    if test \"\$libtool_execute_magic\" != \"$magic\"; then
+      # Run the actual program with our arguments.
+"
+	case $host in
+	# Backslashes separate directories on plain windows
+	*-*-mingw | *-*-os2* | *-cegcc*)
+	  $ECHO "\
+      exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
+"
+	  ;;
+
+	*)
+	  $ECHO "\
+      exec \"\$progdir/\$program\" \${1+\"\$@\"}
+"
+	  ;;
+	esac
+	$ECHO "\
+      \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2
+      exit 1
+    fi
+  else
+    # The program doesn't exist.
+    \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
+    \$ECHO \"This script is just a wrapper for \$program.\" 1>&2
+    $ECHO \"See the $PACKAGE documentation for more information.\" 1>&2
+    exit 1
+  fi
+fi\
+"
+}
+# end: func_emit_wrapper_part2
+
+
+# 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=no
+	if test -n "$1" ; then
+	  func_emit_wrapper_arg1=$1
+	fi
+
+	# split this up so that func_emit_cwrapperexe_src
+	# can call each part independently.
+	func_emit_wrapper_part1 "${func_emit_wrapper_arg1}"
+	func_emit_wrapper_part2 "${func_emit_wrapper_arg1}"
+}
+
+
+# func_to_host_path arg
+#
+# Convert paths to host format when used with build tools.
+# Intended for use with "native" mingw (where libtool itself
+# is running under the msys shell), or in the following cross-
+# build environments:
+#    $build          $host
+#    mingw (msys)    mingw  [e.g. native]
+#    cygwin          mingw
+#    *nix + wine     mingw
+# where wine is equipped with the `winepath' executable.
+# In the native mingw case, the (msys) shell automatically
+# converts paths for any non-msys applications it launches,
+# but that facility isn't available from inside the cwrapper.
+# Similar accommodations are necessary for $host mingw and
+# $build cygwin.  Calling this function does no harm for other
+# $host/$build combinations not listed above.
+#
+# ARG is the path (on $build) that should be converted to
+# the proper representation for $host. The result is stored
+# in $func_to_host_path_result.
+func_to_host_path ()
+{
+  func_to_host_path_result="$1"
+  if test -n "$1" ; then
+    case $host in
+      *mingw* )
+        lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
+        case $build in
+          *mingw* ) # actually, msys
+            # awkward: cmd appends spaces to result
+            lt_sed_strip_trailing_spaces="s/[ ]*\$//"
+            func_to_host_path_tmp1=`( cmd //c echo "$1" |\
+              $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""`
+            func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\
+              $SED -e "$lt_sed_naive_backslashify"`
+            ;;
+          *cygwin* )
+            func_to_host_path_tmp1=`cygpath -w "$1"`
+            func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\
+              $SED -e "$lt_sed_naive_backslashify"`
+            ;;
+          * )
+            # Unfortunately, winepath does not exit with a non-zero
+            # error code, so we are forced to check the contents of
+            # stdout. On the other hand, if the command is not
+            # found, the shell will set an exit code of 127 and print
+            # *an error message* to stdout. So we must check for both
+            # error code of zero AND non-empty stdout, which explains
+            # the odd construction:
+            func_to_host_path_tmp1=`winepath -w "$1" 2>/dev/null`
+            if test "$?" -eq 0 && test -n "${func_to_host_path_tmp1}"; then
+              func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\
+                $SED -e "$lt_sed_naive_backslashify"`
+            else
+              # Allow warning below.
+              func_to_host_path_result=""
+            fi
+            ;;
+        esac
+        if test -z "$func_to_host_path_result" ; then
+          func_error "Could not determine host path corresponding to"
+          func_error "  '$1'"
+          func_error "Continuing, but uninstalled executables may not work."
+          # Fallback:
+          func_to_host_path_result="$1"
+        fi
+        ;;
+    esac
+  fi
+}
+# end: func_to_host_path
+
+# func_to_host_pathlist arg
+#
+# Convert pathlists to host format when used with build tools.
+# See func_to_host_path(), above. This function supports the
+# following $build/$host combinations (but does no harm for
+# combinations not listed here):
+#    $build          $host
+#    mingw (msys)    mingw  [e.g. native]
+#    cygwin          mingw
+#    *nix + wine     mingw
+#
+# Path separators are also converted from $build format to
+# $host format. If ARG begins or ends with a path separator
+# character, it is preserved (but converted to $host format)
+# on output.
+#
+# ARG is a pathlist (on $build) that should be converted to
+# the proper representation on $host. The result is stored
+# in $func_to_host_pathlist_result.
+func_to_host_pathlist ()
+{
+  func_to_host_pathlist_result="$1"
+  if test -n "$1" ; then
+    case $host in
+      *mingw* )
+        lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
+        # Remove leading and trailing path separator characters from
+        # ARG. msys behavior is inconsistent here, cygpath turns them
+        # into '.;' and ';.', and winepath ignores them completely.
+        func_to_host_pathlist_tmp2="$1"
+        # Once set for this call, this variable should not be
+        # reassigned. It is used in tha fallback case.
+        func_to_host_pathlist_tmp1=`echo "$func_to_host_pathlist_tmp2" |\
+          $SED -e 's|^:*||' -e 's|:*$||'`
+        case $build in
+          *mingw* ) # Actually, msys.
+            # Awkward: cmd appends spaces to result.
+            lt_sed_strip_trailing_spaces="s/[ ]*\$//"
+            func_to_host_pathlist_tmp2=`( cmd //c echo "$func_to_host_pathlist_tmp1" |\
+              $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""`
+            func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\
+              $SED -e "$lt_sed_naive_backslashify"`
+            ;;
+          *cygwin* )
+            func_to_host_pathlist_tmp2=`cygpath -w -p "$func_to_host_pathlist_tmp1"`
+            func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\
+              $SED -e "$lt_sed_naive_backslashify"`
+            ;;
+          * )
+            # unfortunately, winepath doesn't convert pathlists
+            func_to_host_pathlist_result=""
+            func_to_host_pathlist_oldIFS=$IFS
+            IFS=:
+            for func_to_host_pathlist_f in $func_to_host_pathlist_tmp1 ; do
+              IFS=$func_to_host_pathlist_oldIFS
+              if test -n "$func_to_host_pathlist_f" ; then
+                func_to_host_path "$func_to_host_pathlist_f"
+                if test -n "$func_to_host_path_result" ; then
+                  if test -z "$func_to_host_pathlist_result" ; then
+                    func_to_host_pathlist_result="$func_to_host_path_result"
+                  else
+                    func_to_host_pathlist_result="$func_to_host_pathlist_result;$func_to_host_path_result"
+                  fi
+                fi
+              fi
+              IFS=:
+            done
+            IFS=$func_to_host_pathlist_oldIFS
+            ;;
+        esac
+        if test -z "$func_to_host_pathlist_result" ; then
+          func_error "Could not determine the host path(s) corresponding to"
+          func_error "  '$1'"
+          func_error "Continuing, but uninstalled executables may not work."
+          # Fallback. This may break if $1 contains DOS-style drive
+          # specifications. The fix is not to complicate the expression
+          # below, but for the user to provide a working wine installation
+          # with winepath so that path translation in the cross-to-mingw
+          # case works properly.
+          lt_replace_pathsep_nix_to_dos="s|:|;|g"
+          func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp1" |\
+            $SED -e "$lt_replace_pathsep_nix_to_dos"`
+        fi
+        # Now, add the leading and trailing path separators back
+        case "$1" in
+          :* ) func_to_host_pathlist_result=";$func_to_host_pathlist_result"
+            ;;
+        esac
+        case "$1" in
+          *: ) func_to_host_pathlist_result="$func_to_host_pathlist_result;"
+            ;;
+        esac
+        ;;
+    esac
+  fi
+}
+# end: func_to_host_pathlist
+
+# 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.
+
+   Currently, it simply execs the wrapper *script* "$SHELL $output",
+   but could eventually absorb all of the scripts functionality and
+   exec $objdir/$outputname directly.
+*/
+EOF
+	    cat <<"EOF"
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef _MSC_VER
+# include <direct.h>
+# include <process.h>
+# include <io.h>
+# define setmode _setmode
+#else
+# include <unistd.h>
+# include <stdint.h>
+# ifdef __CYGWIN__
+#  include <io.h>
+#  define HAVE_SETENV
+#  ifdef __STRICT_ANSI__
+char *realpath (const char *, char *);
+int putenv (char *);
+int setenv (const char *, const char *, int);
+#  endif
+# endif
+#endif
+#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>
+
+#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
+
+#ifdef _MSC_VER
+# define S_IXUSR _S_IEXEC
+# define stat _stat
+# ifndef _INTPTR_T_DEFINED
+#  define intptr_t int
+# endif
+#endif
+
+#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 */
+
+#ifdef __CYGWIN__
+# define FOPEN_WB "wb"
+#endif
+
+#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)
+
+#undef LTWRAPPER_DEBUGPRINTF
+#if defined DEBUGWRAPPER
+# define LTWRAPPER_DEBUGPRINTF(args) ltwrapper_debugprintf args
+static void
+ltwrapper_debugprintf (const char *fmt, ...)
+{
+    va_list args;
+    va_start (args, fmt);
+    (void) vfprintf (stderr, fmt, args);
+    va_end (args);
+}
+#else
+# define LTWRAPPER_DEBUGPRINTF(args)
+#endif
+
+const char *program_name = NULL;
+
+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_fatal (const char *message, ...);
+void lt_setenv (const char *name, const char *value);
+char *lt_extend_str (const char *orig_value, const char *add, int to_end);
+void lt_opt_process_env_set (const char *arg);
+void lt_opt_process_env_prepend (const char *arg);
+void lt_opt_process_env_append (const char *arg);
+int lt_split_name_value (const char *arg, char** name, char** value);
+void lt_update_exe_path (const char *name, const char *value);
+void lt_update_lib_path (const char *name, const char *value);
+
+static const char *script_text_part1 =
+EOF
+
+	    func_emit_wrapper_part1 yes |
+	        $SED -e 's/\([\\"]\)/\\\1/g' \
+	             -e 's/^/  "/' -e 's/$/\\n"/'
+	    echo ";"
+	    cat <<EOF
+
+static const char *script_text_part2 =
+EOF
+	    func_emit_wrapper_part2 yes |
+	        $SED -e 's/\([\\"]\)/\\\1/g' \
+	             -e 's/^/  "/' -e 's/$/\\n"/'
+	    echo ";"
+
+	    cat <<EOF
+const char * MAGIC_EXE = "$magic_exe";
+const char * LIB_PATH_VARNAME = "$shlibpath_var";
+EOF
+
+	    if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+              func_to_host_pathlist "$temp_rpath"
+	      cat <<EOF
+const char * LIB_PATH_VALUE   = "$func_to_host_pathlist_result";
+EOF
+	    else
+	      cat <<"EOF"
+const char * LIB_PATH_VALUE   = "";
+EOF
+	    fi
+
+	    if test -n "$dllsearchpath"; then
+              func_to_host_pathlist "$dllsearchpath:"
+	      cat <<EOF
+const char * EXE_PATH_VARNAME = "PATH";
+const char * EXE_PATH_VALUE   = "$func_to_host_pathlist_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-"
+#define LTWRAPPER_OPTION_PREFIX_LENGTH  5
+
+static const size_t opt_prefix_len         = LTWRAPPER_OPTION_PREFIX_LENGTH;
+static const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;
+
+static const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX "dump-script";
+
+static const size_t env_set_opt_len     = LTWRAPPER_OPTION_PREFIX_LENGTH + 7;
+static const char *env_set_opt          = LTWRAPPER_OPTION_PREFIX "env-set";
+  /* argument is putenv-style "foo=bar", value of foo is set to bar */
+
+static const size_t env_prepend_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 11;
+static const char *env_prepend_opt      = LTWRAPPER_OPTION_PREFIX "env-prepend";
+  /* argument is putenv-style "foo=bar", new value of foo is bar${foo} */
+
+static const size_t env_append_opt_len  = LTWRAPPER_OPTION_PREFIX_LENGTH + 10;
+static const char *env_append_opt       = LTWRAPPER_OPTION_PREFIX "env-append";
+  /* argument is putenv-style "foo=bar", new value of foo is ${foo}bar */
+
+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]));
+  LTWRAPPER_DEBUGPRINTF (("(main) argv[0]      : %s\n", argv[0]));
+  LTWRAPPER_DEBUGPRINTF (("(main) program_name : %s\n", program_name));
+
+  /* very simple arg parsing; don't want to rely on getopt */
+  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"
+	  printf ("%s", script_text_part1);
+	  printf ("%s", script_text_part2);
+	  return 0;
+	}
+    }
+
+  newargz = XMALLOC (char *, argc + 1);
+  tmp_pathspec = find_executable (argv[0]);
+  if (tmp_pathspec == NULL)
+    lt_fatal ("Couldn't find %s", argv[0]);
+  LTWRAPPER_DEBUGPRINTF (("(main) found exe (before symlink chase) at : %s\n",
+			  tmp_pathspec));
+
+  actual_cwrapper_path = chase_symlinks (tmp_pathspec);
+  LTWRAPPER_DEBUGPRINTF (("(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;
+
+  LTWRAPPER_DEBUGPRINTF (("(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 */
+  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);
+  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);
+
+  newargc=0;
+  for (i = 1; i < argc; i++)
+    {
+      if (strncmp (argv[i], env_set_opt, env_set_opt_len) == 0)
+        {
+          if (argv[i][env_set_opt_len] == '=')
+            {
+              const char *p = argv[i] + env_set_opt_len + 1;
+              lt_opt_process_env_set (p);
+            }
+          else if (argv[i][env_set_opt_len] == '\0' && i + 1 < argc)
+            {
+              lt_opt_process_env_set (argv[++i]); /* don't copy */
+            }
+          else
+            lt_fatal ("%s missing required argument", env_set_opt);
+          continue;
+        }
+      if (strncmp (argv[i], env_prepend_opt, env_prepend_opt_len) == 0)
+        {
+          if (argv[i][env_prepend_opt_len] == '=')
+            {
+              const char *p = argv[i] + env_prepend_opt_len + 1;
+              lt_opt_process_env_prepend (p);
+            }
+          else if (argv[i][env_prepend_opt_len] == '\0' && i + 1 < argc)
+            {
+              lt_opt_process_env_prepend (argv[++i]); /* don't copy */
+            }
+          else
+            lt_fatal ("%s missing required argument", env_prepend_opt);
+          continue;
+        }
+      if (strncmp (argv[i], env_append_opt, env_append_opt_len) == 0)
+        {
+          if (argv[i][env_append_opt_len] == '=')
+            {
+              const char *p = argv[i] + env_append_opt_len + 1;
+              lt_opt_process_env_append (p);
+            }
+          else if (argv[i][env_append_opt_len] == '\0' && i + 1 < argc)
+            {
+              lt_opt_process_env_append (argv[++i]); /* don't copy */
+            }
+          else
+            lt_fatal ("%s missing required argument", env_append_opt);
+          continue;
+        }
+      if (strncmp (argv[i], ltwrapper_option_prefix, opt_prefix_len) == 0)
+        {
+          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX
+             namespace, but it is not one of the ones we know about and
+             have already dealt with, above (inluding dump-script), then
+             report an error. Otherwise, targets might begin to believe
+             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX
+             namespace. The first time any user complains about this, we'll
+             need to make LTWRAPPER_OPTION_PREFIX a configure-time option
+             or a configure.ac-settable value.
+           */
+          lt_fatal ("Unrecognized option in %s namespace: '%s'",
+                    ltwrapper_option_prefix, argv[i]);
+        }
+      /* otherwise ... */
+      newargz[++newargc] = xstrdup (argv[i]);
+    }
+  newargz[++newargc] = NULL;
+
+  LTWRAPPER_DEBUGPRINTF     (("(main) lt_argv_zero : %s\n", (lt_argv_zero ? lt_argv_zero : "<NULL>")));
+  for (i = 0; i < newargc; i++)
+    {
+      LTWRAPPER_DEBUGPRINTF (("(main) newargz[%d]   : %s\n", i, (newargz[i] ? newargz[i] : "<NULL>")));
+    }
+
+EOF
+
+	    case $host_os in
+	      mingw*)
+		cat <<"EOF"
+  /* execv doesn't actually work on mingw as expected on unix */
+  rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);
+  if (rval == -1)
+    {
+      /* failed to start process */
+      LTWRAPPER_DEBUGPRINTF (("(main) failed to launch target \"%s\": errno = %d\n", lt_argv_zero, errno));
+      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 ("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;
+
+  LTWRAPPER_DEBUGPRINTF (("(check_executable)  : %s\n",
+			  path ? (*path ? path : "EMPTY!") : "NULL!"));
+  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;
+
+  LTWRAPPER_DEBUGPRINTF (("(make_executable)   : %s\n",
+			  path ? (*path ? path : "EMPTY!") : "NULL!"));
+  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;
+
+  LTWRAPPER_DEBUGPRINTF (("(find_executable)   : %s\n",
+			  wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!"));
+
+  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 ("getcwd failed");
+		  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 ("getcwd failed");
+  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)
+    {
+      LTWRAPPER_DEBUGPRINTF (("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
+	{
+	  char *errstr = strerror (errno);
+	  lt_fatal ("Error accessing file %s (%s)", tmp_pathspec, errstr);
+	}
+    }
+  XFREE (tmp_pathspec);
+
+  if (!has_symlinks)
+    {
+      return xstrdup (pathspec);
+    }
+
+  tmp_pathspec = realpath (pathspec, buf);
+  if (tmp_pathspec == 0)
+    {
+      lt_fatal ("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;
+}
+
+static void
+lt_error_core (int exit_status, const char *mode,
+	       const char *message, va_list ap)
+{
+  fprintf (stderr, "%s: %s: ", program_name, mode);
+  vfprintf (stderr, message, ap);
+  fprintf (stderr, ".\n");
+
+  if (exit_status >= 0)
+    exit (exit_status);
+}
+
+void
+lt_fatal (const char *message, ...)
+{
+  va_list ap;
+  va_start (ap, message);
+  lt_error_core (EXIT_FAILURE, "FATAL", message, ap);
+  va_end (ap);
+}
+
+void
+lt_setenv (const char *name, const char *value)
+{
+  LTWRAPPER_DEBUGPRINTF (("(lt_setenv) setting '%s' to '%s'\n",
+                          (name ? name : "<NULL>"),
+                          (value ? value : "<NULL>")));
+  {
+#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;
+}
+
+int
+lt_split_name_value (const char *arg, char** name, char** value)
+{
+  const char *p;
+  int len;
+  if (!arg || !*arg)
+    return 1;
+
+  p = strchr (arg, (int)'=');
+
+  if (!p)
+    return 1;
+
+  *value = xstrdup (++p);
+
+  len = strlen (arg) - strlen (*value);
+  *name = XMALLOC (char, len);
+  strncpy (*name, arg, len-1);
+  (*name)[len - 1] = '\0';
+
+  return 0;
+}
+
+void
+lt_opt_process_env_set (const char *arg)
+{
+  char *name = NULL;
+  char *value = NULL;
+
+  if (lt_split_name_value (arg, &name, &value) != 0)
+    {
+      XFREE (name);
+      XFREE (value);
+      lt_fatal ("bad argument for %s: '%s'", env_set_opt, arg);
+    }
+
+  lt_setenv (name, value);
+  XFREE (name);
+  XFREE (value);
+}
+
+void
+lt_opt_process_env_prepend (const char *arg)
+{
+  char *name = NULL;
+  char *value = NULL;
+  char *new_value = NULL;
+
+  if (lt_split_name_value (arg, &name, &value) != 0)
+    {
+      XFREE (name);
+      XFREE (value);
+      lt_fatal ("bad argument for %s: '%s'", env_prepend_opt, arg);
+    }
+
+  new_value = lt_extend_str (getenv (name), value, 0);
+  lt_setenv (name, new_value);
+  XFREE (new_value);
+  XFREE (name);
+  XFREE (value);
+}
+
+void
+lt_opt_process_env_append (const char *arg)
+{
+  char *name = NULL;
+  char *value = NULL;
+  char *new_value = NULL;
+
+  if (lt_split_name_value (arg, &name, &value) != 0)
+    {
+      XFREE (name);
+      XFREE (value);
+      lt_fatal ("bad argument for %s: '%s'", env_append_opt, arg);
+    }
+
+  new_value = lt_extend_str (getenv (name), value, 1);
+  lt_setenv (name, new_value);
+  XFREE (new_value);
+  XFREE (name);
+  XFREE (value);
+}
+
+void
+lt_update_exe_path (const char *name, const char *value)
+{
+  LTWRAPPER_DEBUGPRINTF (("(lt_update_exe_path) modifying '%s' by prepending '%s'\n",
+                          (name ? name : "<NULL>"),
+                          (value ? value : "<NULL>")));
+
+  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)
+{
+  LTWRAPPER_DEBUGPRINTF (("(lt_update_lib_path) modifying '%s' by prepending '%s'\n",
+                          (name ? name : "<NULL>"),
+                          (value ? value : "<NULL>")));
+
+  if (name && *name && value && *value)
+    {
+      char *new_value = lt_extend_str (getenv (name), value, 0);
+      lt_setenv (name, new_value);
+      XFREE (new_value);
+    }
+}
+
+
+EOF
+}
+# end: func_emit_cwrapperexe_src
+
+# 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
+    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
+	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
+	      dlfiles="$dlfiles $arg"
+	    else
+	      dlprefiles="$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 "*) ;;
+		*) deplibs="$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
+#	      moreargs="$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
+		      dlfiles="$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.
+		    dlprefiles="$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 "*) ;;
+	    *) rpath="$rpath $arg" ;;
+	    esac
+	  else
+	    case "$xrpath " in
+	    *" $arg "*) ;;
+	    *) xrpath="$xrpath $arg" ;;
+	    esac
+	  fi
+	  prev=
+	  continue
+	  ;;
+	shrext)
+	  shrext_cmds="$arg"
+	  prev=
+	  continue
+	  ;;
+	weak)
+	  weak_libs="$weak_libs $arg"
+	  prev=
+	  continue
+	  ;;
+	xcclinker)
+	  linker_flags="$linker_flags $qarg"
+	  compiler_flags="$compiler_flags $qarg"
+	  prev=
+	  func_append compile_command " $qarg"
+	  func_append finalize_command " $qarg"
+	  continue
+	  ;;
+	xcompiler)
+	  compiler_flags="$compiler_flags $qarg"
+	  prev=
+	  func_append compile_command " $qarg"
+	  func_append finalize_command " $qarg"
+	  continue
+	  ;;
+	xlinker)
+	  linker_flags="$linker_flags $qarg"
+	  compiler_flags="$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
+	;;
+
+      -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"
+	dir=$func_stripname_result
+	if test -z "$dir"; 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
+	# 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 "*) ;;
+	*)
+	  deplibs="$deplibs -L$dir"
+	  lib_search_path="$lib_search_path $dir"
+	  ;;
+	esac
+	case $host in
+	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+	  testbindir=`$ECHO "X$dir" | $Xsed -e 's*/lib$*/bin*'`
+	  case :$dllsearchpath: in
+	  *":$dir:"*) ;;
+	  ::) dllsearchpath=$dir;;
+	  *) dllsearchpath="$dllsearchpath:$dir";;
+	  esac
+	  case :$dllsearchpath: in
+	  *":$testbindir:"*) ;;
+	  ::) dllsearchpath=$testbindir;;
+	  *) dllsearchpath="$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*)
+	    # 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
+	    deplibs="$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
+	deplibs="$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)
+	compiler_flags="$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)
+	compiler_flags="$compiler_flags $arg"
+	func_append compile_command " $arg"
+	func_append finalize_command " $arg"
+	case "$new_inherited_linker_flags " in
+	    *" $arg "*) ;;
+	    * ) new_inherited_linker_flags="$new_inherited_linker_flags $arg" ;;
+	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_fatal_error "only absolute run-paths are allowed"
+	  ;;
+	esac
+	case "$xrpath " in
+	*" $dir "*) ;;
+	*) xrpath="$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"
+	  arg="$arg $wl$func_quote_for_eval_result"
+	  compiler_flags="$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"
+	  arg="$arg $wl$func_quote_for_eval_result"
+	  compiler_flags="$compiler_flags $wl$func_quote_for_eval_result"
+	  linker_flags="$linker_flags $func_quote_for_eval_result"
+	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"
+	;;
+
+      # -64, -mips[0-9] enable 64-bit mode on the SGI compiler
+      # -r[0-9][0-9]* specifies the processor on the SGI compiler
+      # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler
+      # +DA*, +DD* enable 64-bit mode on the HP compiler
+      # -q* pass through compiler args for the IBM compiler
+      # -m*, -t[45]*, -txscale* pass through architecture-specific
+      # compiler args for GCC
+      # -F/path gives path to uninstalled frameworks, gcc on darwin
+      # -p, -pg, --coverage, -fprofile-* pass through profiling flag for GCC
+      # @file GCC response files
+      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \
+      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*)
+        func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+        func_append compile_command " $arg"
+        func_append finalize_command " $arg"
+        compiler_flags="$compiler_flags $arg"
+        continue
+        ;;
+
+      # Some other compiler flag.
+      -* | +*)
+        func_quote_for_eval "$arg"
+	arg="$func_quote_for_eval_result"
+	;;
+
+      *.$objext)
+	# A standard object.
+	objs="$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
+		dlfiles="$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.
+	      dlprefiles="$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.
+	deplibs="$deplibs $arg"
+	old_deplibs="$old_deplibs $arg"
+	continue
+	;;
+
+      *.la)
+	# A libtool-controlled library.
+
+	if test "$prev" = dlfiles; then
+	  # This library was specified with -dlopen.
+	  dlfiles="$dlfiles $arg"
+	  prev=
+	elif test "$prev" = dlprefiles; then
+	  # The library was specified with -dlpreopen.
+	  dlprefiles="$dlprefiles $arg"
+	  prev=
+	else
+	  deplibs="$deplibs $arg"
+	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 \"X\${$shlibpath_var}\" \| \$Xsed -e \'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"
+    # 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_duplicate_deps ; then
+	case "$libs " in
+	*" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+	esac
+      fi
+      libs="$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 "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;;
+	  esac
+	  pre_post_deps="$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=
+	  case $lib in
+	  *.la)	func_source "$lib" ;;
+	  esac
+
+	  # Collect preopened libtool deplibs, except any this library
+	  # has declared as weak libs
+	  for deplib in $dependency_libs; do
+            deplib_base=`$ECHO "X$deplib" | $Xsed -e "$basename"`
+	    case " $weak_libs " in
+	    *" $deplib_base "*) ;;
+	    *) deplibs="$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)
+	  if test "$linkmode,$pass" = "prog,link"; then
+	    compile_deplibs="$deplib $compile_deplibs"
+	    finalize_deplibs="$deplib $finalize_deplibs"
+	  else
+	    compiler_flags="$compiler_flags $deplib"
+	    if test "$linkmode" = lib ; then
+		case "$new_inherited_linker_flags " in
+		    *" $deplib "*) ;;
+		    * ) new_inherited_linker_flags="$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 "*) ;;
+		    * ) new_inherited_linker_flags="$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"
+	    newlib_search_path="$newlib_search_path $func_stripname_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"
+	    newlib_search_path="$newlib_search_path $func_stripname_result"
+	    ;;
+	  *)
+	    func_warning "\`-L' is ignored for archives/objects"
+	    ;;
+	  esac # linkmode
+	  continue
+	  ;; # -L
+	-R*)
+	  if test "$pass" = link; then
+	    func_stripname '-R' '' "$deplib"
+	    dir=$func_stripname_result
+	    # Make sure the xrpath contains only unique directories.
+	    case "$xrpath " in
+	    *" $dir "*) ;;
+	    *) xrpath="$xrpath $dir" ;;
+	    esac
+	  fi
+	  deplibs="$deplib $deplibs"
+	  continue
+	  ;;
+	*.la) lib="$deplib" ;;
+	*.$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 \"X$deplib\"" 2>/dev/null | $Xsed -e 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.
+	      newdlprefiles="$newdlprefiles $deplib"
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    else
+	      newdlfiles="$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 "X$inherited_linker_flags" | $Xsed -e 's/-framework \([^ $]*\)/\1.ltframework/g'`
+	  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do
+	    case " $new_inherited_linker_flags " in
+	      *" $tmp_inherited_linker_flag "*) ;;
+	      *) new_inherited_linker_flags="$new_inherited_linker_flags $tmp_inherited_linker_flag";;
+	    esac
+	  done
+	fi
+	dependency_libs=`$ECHO "X $dependency_libs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	if test "$linkmode,$pass" = "lib,link" ||
+	   test "$linkmode,$pass" = "prog,scan" ||
+	   { test "$linkmode" != prog && test "$linkmode" != lib; }; then
+	  test -n "$dlopen" && dlfiles="$dlfiles $dlopen"
+	  test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen"
+	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.
+	    convenience="$convenience $ladir/$objdir/$old_library"
+	    old_convenience="$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_duplicate_deps ; then
+	      case "$tmp_libs " in
+	      *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+	      esac
+	    fi
+	    tmp_libs="$tmp_libs $deplib"
+	  done
+	  continue
+	fi # $pass = conv
+
+
+	# Get the name of the library we link against.
+	linklib=
+	for l in $old_library $library_names; do
+	  linklib="$l"
+	done
+	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.
+	    dlprefiles="$dlprefiles $lib $dependency_libs"
+	  else
+	    newdlfiles="$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 "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+	    func_warning "library \`$lib' was moved."
+	    dir="$ladir"
+	    absdir="$abs_ladir"
+	    libdir="$abs_ladir"
+	  else
+	    dir="$libdir"
+	    absdir="$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
+	    notinst_path="$notinst_path $abs_ladir"
+	  else
+	    dir="$ladir/$objdir"
+	    absdir="$abs_ladir/$objdir"
+	    # Remove this search path later
+	    notinst_path="$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
+	  # Prefer using a static library (so that no silly _DYNAMIC symbols
+	  # are required to link).
+	  if test -n "$old_library"; then
+	    newdlprefiles="$newdlprefiles $dir/$old_library"
+	    # Keep a list of preopened convenience libraries to check
+	    # that they are being used correctly in the link pass.
+	    test -z "$libdir" && \
+		dlpreconveniencelibs="$dlpreconveniencelibs $dir/$old_library"
+	  # Otherwise, use the dlname, so that lt_dlopen finds it.
+	  elif test -n "$dlname"; then
+	    newdlprefiles="$newdlprefiles $dir/$dlname"
+	  else
+	    newdlprefiles="$newdlprefiles $dir/$linklib"
+	  fi
+	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
+	  newlib_search_path="$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"
+	         newlib_search_path="$newlib_search_path $func_stripname_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_duplicate_deps ; then
+	      case "$tmp_libs " in
+	      *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+	      esac
+	    fi
+	    tmp_libs="$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:"*) ;;
+	      *) temp_rpath="$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 "*) ;;
+	      *) compile_rpath="$compile_rpath $absdir"
+	      esac
+	      ;;
+	    esac
+	    case " $sys_lib_dlsearch_path " in
+	    *" $libdir "*) ;;
+	    *)
+	      case "$finalize_rpath " in
+	      *" $libdir "*) ;;
+	      *) finalize_rpath="$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
+	      notinst_deplibs="$notinst_deplibs $lib"
+	      need_relink=no
+	    ;;
+	  *)
+	    if test "$installed" = no; then
+	      notinst_deplibs="$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 "*) ;;
+	      *) compile_rpath="$compile_rpath $absdir"
+	      esac
+	      ;;
+	    esac
+	    case " $sys_lib_dlsearch_path " in
+	    *" $libdir "*) ;;
+	    *)
+	      case "$finalize_rpath " in
+	      *" $libdir "*) ;;
+	      *) finalize_rpath="$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 "$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$dir"
+		# Try looking first in the location we're being installed to.
+		if test -n "$inst_prefix_dir"; then
+		  case $libdir in
+		    [\\/]*)
+		      add_dir="$add_dir -L$inst_prefix_dir$libdir"
+		      ;;
+		  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:"*) ;;
+	      *) compile_shlibpath="$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:"*) ;;
+		*) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
+		esac
+	      fi
+	    fi
+	  fi
+
+	  if test "$linkmode" = prog || test "$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:"*) ;;
+	      *) finalize_shlibpath="$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
+		  [\\/]*)
+		    add_dir="$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 "*) ;;
+		   *) xrpath="$xrpath $temp_xrpath";;
+		   esac;;
+	      *) temp_deplibs="$temp_deplibs $libdir";;
+	      esac
+	    done
+	    dependency_libs="$temp_deplibs"
+	  fi
+
+	  newlib_search_path="$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"
+	    if $opt_duplicate_deps ; then
+	      case "$tmp_libs " in
+	      *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+	      esac
+	    fi
+	    tmp_libs="$tmp_libs $deplib"
+	  done
+
+	  if test "$link_all_deplibs" != no; then
+	    # Add the search paths of all dependency libraries
+	    for deplib in $dependency_libs; do
+	      case $deplib in
+	      -L*) path="$deplib" ;;
+	      *.la)
+	        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
+		      compiler_flags="$compiler_flags ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}"
+		      linker_flags="$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 "X $new_inherited_linker_flags" | $Xsed -e '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 "*) ;;
+	    *) lib_search_path="$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 "*) ;;
+	      *) tmp_libs="$tmp_libs $deplib" ;;
+	      esac
+	      ;;
+	    *) tmp_libs="$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
+	  tmp_libs="$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"
+      objs="$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!"
+	  libobjs="$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
+	  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|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)
+	  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.
+	  verstring="$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"
+      libobjs="$libobjs $symfileobj"
+      test "X$libobjs" = "X " && libobjs=
+
+      if test "$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
+	       removelist="$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
+	oldlibs="$oldlibs $output_objdir/$libname.$libext"
+
+	# Transform .lo files to .o files.
+	oldobjs="$objs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP`
+      fi
+
+      # Eliminate all temporary directories.
+      #for path in $notinst_path; do
+      #	lib_search_path=`$ECHO "X$lib_search_path " | $Xsed -e "s% $path % %g"`
+      #	deplibs=`$ECHO "X$deplibs " | $Xsed -e "s% -L$path % %g"`
+      #	dependency_libs=`$ECHO "X$dependency_libs " | $Xsed -e "s% -L$path % %g"`
+      #done
+
+      if test -n "$xrpath"; then
+	# If the user specified any rpath flags, then add them.
+	temp_xrpath=
+	for libdir in $xrpath; do
+	  temp_xrpath="$temp_xrpath -R$libdir"
+	  case "$finalize_rpath " in
+	  *" $libdir "*) ;;
+	  *) finalize_rpath="$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 "*) ;;
+	*) dlfiles="$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 "*) ;;
+	*) dlprefiles="$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*)
+	    # these systems don't actually have a c library (as such)!
+	    ;;
+	  *-*-rhapsody* | *-*-darwin1.[012])
+	    # Rhapsody C library is in the System framework
+	    deplibs="$deplibs System.ltframework"
+	    ;;
+	  *-*-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
+	      deplibs="$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 "*)
+		    newdeplibs="$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
+		    newdeplibs="$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
+		;;
+	      *)
+		newdeplibs="$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 "*)
+		      newdeplibs="$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
+		      newdeplibs="$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
+		;;
+	      *)
+		newdeplibs="$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 "*)
+		  newdeplibs="$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
+		      # 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 "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";;
+			esac
+		      done
+		      if eval $file_magic_cmd \"\$potlib\" 2>/dev/null |
+			 $SED -e 10q |
+			 $EGREP "$file_magic_regex" > /dev/null; then
+			newdeplibs="$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.
+	      newdeplibs="$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 "*)
+		  newdeplibs="$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 \"X$potent_lib\"" 2>/dev/null | $Xsed -e 10q | \
+		       $EGREP "$match_pattern_regex" > /dev/null; then
+		      newdeplibs="$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.
+	      newdeplibs="$newdeplibs $a_deplib"
+	      ;;
+	    esac
+	  done # Gone through all deplibs.
+	  ;;
+	none | unknown | *)
+	  newdeplibs=""
+	  tmp_deplibs=`$ECHO "X $deplibs" | $Xsed \
+	      -e 's/ -lc$//' -e 's/ -[LR][^ ]*//g'`
+	  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+	    for i in $predeps $postdeps ; do
+	      # can't use Xsed below, because $i might contain '/'
+	      tmp_deplibs=`$ECHO "X $tmp_deplibs" | $Xsed -e "s,$i,,"`
+	    done
+	  fi
+	  if $ECHO "X $tmp_deplibs" | $Xsed -e 's/[	 ]//g' |
+	     $GREP . >/dev/null; then
+	    $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
+	  fi
+	  ;;
+	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 "X $newdeplibs" | $Xsed -e '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 "X $newdeplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  new_inherited_linker_flags=`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  deplibs=`$ECHO "X $deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  ;;
+      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 "*)
+	    new_libs="$new_libs -L$path/$objdir" ;;
+	  esac
+	  ;;
+	esac
+      done
+      for deplib in $deplibs; do
+	case $deplib in
+	-L*)
+	  case " $new_libs " in
+	  *" $deplib "*) ;;
+	  *) new_libs="$new_libs $deplib" ;;
+	  esac
+	  ;;
+	*) new_libs="$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
+	if test "$hardcode_into_libs" = yes; then
+	  # Hardcode the library paths
+	  hardcode_libdirs=
+	  dep_rpath=
+	  rpath="$finalize_rpath"
+	  test "$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
+		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"*)
+		    ;;
+		  *)
+		    hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+		    ;;
+		  esac
+		fi
+	      else
+		eval flag=\"$hardcode_libdir_flag_spec\"
+		dep_rpath="$dep_rpath $flag"
+	      fi
+	    elif test -n "$runpath_var"; then
+	      case "$perm_rpath " in
+	      *" $libdir "*) ;;
+	      *) perm_rpath="$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"
+	    if test -n "$hardcode_libdir_flag_spec_ld"; then
+	      eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\"
+	    else
+	      eval dep_rpath=\"$hardcode_libdir_flag_spec\"
+	    fi
+	  fi
+	  if test -n "$runpath_var" && test -n "$perm_rpath"; then
+	    # We should set the runpath_var.
+	    rpath=
+	    for dir in $perm_rpath; do
+	      rpath="$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 "$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
+	  linknames="$linknames $link"
+	done
+
+	# Use standard objects if they are pic
+	test -z "$pic_flag" && libobjs=`$ECHO "X$libobjs" | $SP2NL | $Xsed -e "$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"
+	  delfiles="$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 cmd in $cmds; do
+	      IFS="$save_ifs"
+	      eval cmd=\"$cmd\"
+	      func_len " $cmd"
+	      len=$func_len_result
+	      if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+		func_show_eval "$cmd" 'exit $?'
+		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 "X$include_expsyms" | $Xsed | $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
+	  delfiles="$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 "*) ;;
+	  *)
+	    tmp_deplibs="$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"
+	    generated="$generated $gentop"
+
+	    func_extract_archives $gentop $convenience
+	    libobjs="$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\"
+	  linker_flags="$linker_flags $flag"
+	fi
+
+	# Make a backup of the uninstalled library when relinking
+	if test "$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
+	  output_la=`$ECHO "X$output" | $Xsed -e "$basename"`
+
+	  # 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
+	      $ECHO "$obj" >> $output
+	    done
+	    $ECHO ')' >> $output
+	    delfiles="$delfiles $output"
+	  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
+	      $ECHO "$obj" >> $output
+	    done
+	    delfiles="$delfiles $output"
+	    output=$firstobj\"$file_list_spec$output\"
+	  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.
+		    eval concat_cmds=\"$reload_cmds $objlist $last_robj\"
+		  else
+		    # All subsequent reloadable object files will link in
+		    # the last one created.
+		    eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj~\$RM $last_robj\"
+		  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~
+	      eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\"
+	      if test -n "$last_robj"; then
+	        eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\"
+	      fi
+	      delfiles="$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 "$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 "X$include_expsyms" | $Xsed | $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
+	      delfiles="$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"
+	  generated="$generated $gentop"
+
+	  func_extract_archives $gentop $dlprefiles
+	  libobjs="$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 "$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 "$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 "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'`
+	else
+	  gentop="$output_objdir/${obj}x"
+	  generated="$generated $gentop"
+
+	  func_extract_archives $gentop $convenience
+	  reload_conv_objs="$reload_objs $func_extract_archives_result"
+	fi
+      fi
+
+      # Create the old-style object.
+      reload_objs="$objs$old_deplibs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
+
+      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 "X $compile_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'`
+	finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e '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])
+	      compile_command="$compile_command ${wl}-bind_at_load"
+	      finalize_command="$finalize_command ${wl}-bind_at_load"
+	    ;;
+	  esac
+	fi
+	# Time to change all our "foo.ltframework" stuff back to "-framework foo"
+	compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	;;
+      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 "*)
+	    new_libs="$new_libs -L$path/$objdir" ;;
+	  esac
+	  ;;
+	esac
+      done
+      for deplib in $compile_deplibs; do
+	case $deplib in
+	-L*)
+	  case " $new_libs " in
+	  *" $deplib "*) ;;
+	  *) new_libs="$new_libs $deplib" ;;
+	  esac
+	  ;;
+	*) new_libs="$new_libs $deplib" ;;
+	esac
+      done
+      compile_deplibs="$new_libs"
+
+
+      compile_command="$compile_command $compile_deplibs"
+      finalize_command="$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 "*) ;;
+	  *) finalize_rpath="$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"*)
+		;;
+	      *)
+		hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+		;;
+	      esac
+	    fi
+	  else
+	    eval flag=\"$hardcode_libdir_flag_spec\"
+	    rpath="$rpath $flag"
+	  fi
+	elif test -n "$runpath_var"; then
+	  case "$perm_rpath " in
+	  *" $libdir "*) ;;
+	  *) perm_rpath="$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;;
+	  *) dllsearchpath="$dllsearchpath:$libdir";;
+	  esac
+	  case :$dllsearchpath: in
+	  *":$testbindir:"*) ;;
+	  ::) dllsearchpath=$testbindir;;
+	  *) dllsearchpath="$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"*)
+		;;
+	      *)
+		hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+		;;
+	      esac
+	    fi
+	  else
+	    eval flag=\"$hardcode_libdir_flag_spec\"
+	    rpath="$rpath $flag"
+	  fi
+	elif test -n "$runpath_var"; then
+	  case "$finalize_perm_rpath " in
+	  *" $libdir "*) ;;
+	  *) finalize_perm_rpath="$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 "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+	finalize_command=`$ECHO "X$finalize_command" | $SP2NL | $Xsed -e "$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
+      *cygwin* | *mingw* )
+        if test "$build_libtool_libs" != yes; then
+          wrappers_required=no
+        fi
+        ;;
+      *cegcc)
+        # Disable wrappers for cegcc, we are cross compiling anyway.
+        wrappers_required=no
+        ;;
+      *)
+        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 "X$compile_command" | $Xsed -e '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=$?'
+
+	# 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
+	    rpath="$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
+	    rpath="$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 "X$link_command" | $Xsed -e '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 $?'
+	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 "X$compile_var$compile_command$compile_rpath" | $Xsed -e '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 "X$link_command" | $Xsed -e '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 $?'
+
+      # 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 "X$relink_command" | $Xsed -e "$sed_quote_subst"`
+      fi
+
+      # Quote $ECHO for shipping.
+      if test "X$ECHO" = "X$SHELL $progpath --fallback-echo"; then
+	case $progpath in
+	[\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";;
+	*) qecho="$SHELL `pwd`/$progpath --fallback-echo";;
+	esac
+	qecho=`$ECHO "X$qecho" | $Xsed -e "$sed_quote_subst"`
+      else
+	qecho=`$ECHO "X$ECHO" | $Xsed -e "$sed_quote_subst"`
+      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
+	    oldobjs="$oldobjs $symfileobj"
+	  fi
+	fi
+	addlibs="$old_convenience"
+      fi
+
+      if test -n "$addlibs"; then
+	gentop="$output_objdir/${outputname}x"
+	generated="$generated $gentop"
+
+	func_extract_archives $gentop $addlibs
+	oldobjs="$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"
+	  generated="$generated $gentop"
+
+	  func_extract_archives $gentop $dlprefiles
+	  oldobjs="$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"
+	  generated="$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"
+	      oldobjs="$oldobjs $gentop/$newobj"
+	      ;;
+	    *) oldobjs="$oldobjs $obj" ;;
+	    esac
+	  done
+	fi
+	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
+	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 "X$relink_command" | $Xsed -e "$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"
+		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
+		test -z "$libdir" && \
+		  func_fatal_error "\`$deplib' is not a valid libtool archive"
+		newdependency_libs="$newdependency_libs $libdir/$name"
+		;;
+	      *) newdependency_libs="$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"
+		newdlfiles="$newdlfiles $libdir/$name"
+		;;
+	      *) newdlfiles="$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"
+		newdlprefiles="$newdlprefiles $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
+	      newdlfiles="$newdlfiles $abs"
+	    done
+	    dlfiles="$newdlfiles"
+	    newdlprefiles=
+	    for lib in $dlprefiles; do
+	      case $lib in
+		[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+		*) abs=`pwd`"/$lib" ;;
+	      esac
+	      newdlprefiles="$newdlprefiles $abs"
+	    done
+	    dlprefiles="$newdlprefiles"
+	  fi
+	  $RM $output
+	  # place dlname in correct position for cygwin
+	  tdlname=$dlname
+	  case $host,$output,$installed,$module,$dlname in
+	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;;
+	  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 "$mode" = link || test "$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) RM="$RM $arg"; rmforce=yes ;;
+      -*) RM="$RM $arg" ;;
+      *) files="$files $arg" ;;
+      esac
+    done
+
+    test -z "$RM" && \
+      func_fatal_help "you must specify an RM program"
+
+    rmdirs=
+
+    origobjdir="$objdir"
+    for file in $files; do
+      func_dirname "$file" "" "."
+      dir="$func_dirname_result"
+      if test "X$dir" = X.; then
+	objdir="$origobjdir"
+      else
+	objdir="$dir/$origobjdir"
+      fi
+      func_basename "$file"
+      name="$func_basename_result"
+      test "$mode" = uninstall && objdir="$dir"
+
+      # Remember objdir for removal later, being careful to avoid duplicates
+      if test "$mode" = clean; then
+	case " $rmdirs " in
+	  *" $objdir "*) ;;
+	  *) rmdirs="$rmdirs $objdir" ;;
+	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
+	    rmfiles="$rmfiles $objdir/$n"
+	  done
+	  test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library"
+
+	  case "$mode" in
+	  clean)
+	    case "  $library_names " in
+	    # "  " in the beginning catches empty $dlname
+	    *" $dlname "*) ;;
+	    *) rmfiles="$rmfiles $objdir/$dlname" ;;
+	    esac
+	    test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${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
+	    rmfiles="$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
+	    rmfiles="$rmfiles $dir/$non_pic_object"
+	  fi
+	fi
+	;;
+
+      *)
+	if test "$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
+	    rmfiles="$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
+	      rmfiles="$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
+	    rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}"
+	    if test "$fast_install" = yes && test -n "$relink_command"; then
+	      rmfiles="$rmfiles $objdir/lt-$name"
+	    fi
+	    if test "X$noexename" != "X$name" ; then
+	      rmfiles="$rmfiles $objdir/lt-${noexename}.c"
+	    fi
+	  fi
+	fi
+	;;
+      esac
+      func_show_eval "$RM $rmfiles" 'exit_status=1'
+    done
+    objdir="$origobjdir"
+
+    # 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 "$mode" = uninstall || test "$mode" = clean; } &&
+    func_mode_uninstall ${1+"$@"}
+
+test -z "$mode" && {
+  help="$generic_help"
+  func_fatal_help "you must specify a MODE"
+}
+
+test -z "$exec_cmd" && \
+  func_fatal_help "invalid operation mode \`$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/trunk-jpl-damage/m4/issm_options.m4
===================================================================
--- /issm/trunk-jpl-damage/m4/issm_options.m4	(revision 11330)
+++ /issm/trunk-jpl-damage/m4/issm_options.m4	(revision 11330)
@@ -0,0 +1,1111 @@
+dnl ISSM Options
+
+AC_DEFUN([ISSM_OPTIONS],[
+
+	dnl ISSM's internal options
+	dnl Debugging {{{1
+	AC_ARG_ENABLE([debugging],AS_HELP_STRING([--enable-debugging],
+					 [turn debug support on]),
+		[enable_debugging=$enableval],[enable_debugging=no])
+	if test "x$enable_debugging" = xyes; then
+	 AC_DEFINE([_ISSM_DEBUG_],[1],[Macro to enable debugging in ISSM.])
+	fi
+	dnl }}}
+	dnl Serial build {{{1
+	AC_ARG_WITH([serial],
+			  AS_HELP_STRING([--with-serial = value],
+							 [serial compilation. ]),
+			  [SERIAL_VALUE=$withval],[SERIAL_VALUE="yes"])
+	AC_MSG_CHECKING(for serial compilation)
+	AM_CONDITIONAL([NOSERIAL], [test $SERIAL_VALUE = no])
+	AC_MSG_RESULT($SERIAL_VALUE) 
+	dnl }}}
+	dnl Parallel build {{{1
+	AC_ARG_WITH([parallel],
+			  AS_HELP_STRING([--with-parallel = value],
+							 [parallel compilation. ]),
+			  [PARALLEL_VALUE=$withval],[PARALLEL_VALUE="yes"])
+	AC_MSG_CHECKING(for parallel compilation)
+	AM_CONDITIONAL([NOPARALLEL], [test $PARALLEL_VALUE = no])
+	AC_MSG_RESULT($PARALLEL_VALUE) 
+	dnl }}}
+	dnl Serial or Parallel check {{{1
+	dnl Check that at least serial or parallel builds have been requested!
+	if test "$SERIAL_VALUE" != "yes" ; then
+		if test "$PARALLEL_VALUE" != "yes"; then
+		AC_MSG_ERROR([cannot request --with-serial=no and --with-parallel=no at the same time!])
+		fi
+	fi
+	dnl }}}
+
+	dnl ISSM's externalpackages
+	dnl Matlab {{{1
+	AC_ARG_WITH([matlab-dir],
+			  AS_HELP_STRING([--with-matlab-dir = DIR],
+							 [matlab root directory. necessary for serial build.]),
+			 [MATLAB_ROOT=$withval],[MATLAB_ROOT=""]) 
+	
+	if test -d "$MATLAB_ROOT"; then
+
+		dnl matlab version (matlab.m4)
+		AX_MATLAB_VERSION
+
+		AC_MSG_CHECKING(for Matlab headers and libraries in $MATLAB_ROOT)
+
+		dnl defaults
+		HAVE_MATLAB=yes
+		MATLABINCL=-I"$MATLAB_ROOT/extern/include";
+		
+		dnl OS-dependent variables and checks
+		case "${host_os}" in
+			*linux*)
+				if test "${host_cpu}" = "x86_64";
+				then
+					MEXLIB=-L"$MATLAB_ROOT/bin/glnxa64/ -lmex"
+					MEXLINK="-pthread -shared -W2,--version-script,${MATLAB_ROOT}/extern/lib/glnxa64/mexFunction.map";
+				else
+					MEXLIB=-L"$MATLAB_ROOT/bin/glnx86/ -lmex"
+					MEXLINK="-pthread -shared -W2,--version-script,${MATLAB_ROOT}/extern/lib/glnx86/mexFunction.map";
+				fi
+				MEXEXT=`$MATLAB_ROOT/bin/mexext`
+				MEXEXT=".$MEXEXT"
+			;;
+			*darwin*)
+
+				dnl mex -v gives all the flags for compilation of mex files
+				dnl if matlab version is 7.10 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"
+				if test $MATLAB_MAJOR -ge 7; then 
+					 if test $MATLAB_MINOR -ge 10; then 
+						  MEXLINK="-O -Wl,-flat_namespace -undefined suppress -bundle -Wl,-exported_symbols_list,$MATLAB_ROOT/extern/lib/maci64/mexFunction.map"
+					 fi
+				fi
+
+				MEXLIB=" mexversion.o -L$MATLAB_ROOT/bin/maci/ -lmx -lmex -lmat -lstdc++ -largeArrayDims"
+				MEXEXT=`$MATLAB_ROOT/bin/mexext`
+				MEXEXT=".$MEXEXT"
+
+				dnl Old MEXLINK
+				dnl MEXLINK="-Wl,-twolevel_namespace -undefined error -arch i386 -Wl,-syslibroot,/Developer/SDKs/MacOSX10.5.sdk -mmacosx-version-min=10.5 -bundle -Wl,-exported_symbols_list,$MATLAB_ROOT/extern/lib/maci/mexFunction.map"
+			;;
+			*cygwin*)
+				MEXLIB="-dll -export:mexFunction -LIBPATH:\"$MATLAB_ROOT\extern\lib\win32\microsoft\" libmx.lib libmex.lib libmat.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  -NOLOGO -INCREMENTAL:NO"
+
+				MEXEXT=`$MATLAB_ROOT/bin/mexext.bat`
+				MEXEXT=".$MEXEXT"
+			;;
+		esac
+
+		AC_DEFINE([_HAVE_MATLAB_],[1],[with Matlab in ISSM src])
+		AC_SUBST([MATLABINCL])
+		AC_SUBST([MEX])
+		AC_SUBST([MEXEXT])
+		AC_SUBST([MEXLIB]) 
+		AC_SUBST([MEXLINK])
+	
+		AC_MSG_RESULT($HAVE_MATLAB)
+	else
+		HAVE_MATLAB=no
+	fi
+
+	
+	if test $HAVE_MATLAB = no; then
+		if test "$SERIAL_VALUE" = "yes" ; then
+			AC_MSG_ERROR([--with-matlab-dir  missing. Matlab is needed to run ISSM serially!])
+		fi
+	fi
+
+	dnl should we use large arrays compilation (Matlab 7.5 and upper?)
+	if test $HAVE_MATLAB = yes; then
+		
+		dnl  if matlab version is 7.5 and more, and if platform is x86_64, then compile with largearray
+		dnl  default is no 
+		largearrays=no
+		if test $MATLAB_MAJOR -ge 7; then 
+			if test $MATLAB_MINOR -ge 5; then 
+				case "${host_os}" in
+					*linux*)
+						if test "${host_cpu}" = "x86_64"; then
+							largearrays=yes 
+						fi
+					;;
+					*darwin*)
+						if test $MATLAB_MAJOR -ge 7; then 
+							if test $MATLAB_MINOR -ge 10; then
+								largearrays=yes
+							fi
+						fi
+					;;
+				esac
+			fi
+		fi
+	fi
+	AM_CONDITIONAL(LARGEARRAYS, test x$largearrays = xyes)
+	
+	dnl }}}
+	dnl triangle {{{1
+	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/
+		TRIANGLELIB=$TRIANGLE_ROOT/triangle.a
+
+		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)
+
+	AC_MSG_CHECKING(for triangle and parallel status)
+	if test $HAVE_TRIANGLE = no; then
+		if test "$SERIAL_VALUE" = "yes" ; then
+			AC_MSG_ERROR([--with-triangle-dir  missing. Triangle is needed to run ISSM serially!])
+		fi
+	fi
+	AC_MSG_RESULT(ok)
+	dnl }}}
+	dnl dakota{{{1
+	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
+		DAKOTAINCL=-I$DAKOTA_ROOT/include
+		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="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -lfftw3 -llhs -levidence -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -lopt -lpsuade -lnewmat -lncsuopt -lgsl -lgslcblas -lquadrature -lcoliny -lcolin -lpebbl -lutilib -l3po -lnappspack -lappspack -lconveyor -lshared -lcdd -lamplsolver"
+		AC_DEFINE([_HAVE_DAKOTA_],[1],[with Dakota in ISSM src])
+		AC_SUBST([DAKOTAINCL])
+		AC_SUBST([DAKOTALIB])
+
+	else
+		HAVE_DAKOTA=no
+	fi
+	AM_CONDITIONAL([DAKOTA], [test x$HAVE_DAKOTA = xyes])
+	AC_MSG_RESULT($HAVE_DAKOTA)
+	dnl }}}
+	dnl chaco{{{1
+	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{{{1
+	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 adic2{{{1
+	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 rose{{{1
+	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 metis{{{1
+	AC_ARG_WITH([metis-dir],
+			  AS_HELP_STRING([--with-metis-dir = DIR],
+							 [metis root directory. necessary for serial build]),
+			  [METIS_ROOT=$withval],[METIS_ROOT=""])
+
+	if test -d "$METIS_ROOT"; then
+
+		AC_MSG_CHECKING(for Metis headers and libraries in $METIS_ROOT)
+
+		dnl first figure out version of metis: does the VERSION file exist?
+		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
+
+			case "${host_os}" in
+				*cygwin*)
+				METISLIB="-LIBPATH:\"$METIS_ROOT\" libmetis.lib"
+				;;
+				*linux*)
+				METISLIB=-L"$METIS_ROOT/ -lmetis"
+				;;
+				*darwin*)
+				METISLIB=-L"$METIS_ROOT/ -lmetis"
+				;;
+			esac
+
+   			METISINCL=-I"$METIS_ROOT/Lib" 
+   			AC_DEFINE([_METIS_VERSION_],[4],[ Metis version number])
+		fi
+		if test "$METIS_VERSION" = "5" ; then
+	
+			case "${host_os}" in
+				*cygwin*)
+				METISLIB="-LIBPATH:\"$METIS_ROOT\" libmetis.lib"
+				;;
+				*linux*)
+				METISLIB=-L"$METIS_ROOT/lib -lmetis"
+				;;
+				*darwin*)
+				METISLIB=-L"$METIS_ROOT/lib -lmetis"
+				;;
+			esac
+	
+			METISINCL=-I"$METIS_ROOT/include" 
+			AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
+		fi
+
+
+		AC_DEFINE([_HAVE_METIS_],[1],[with Metis in ISSM src])
+		AC_SUBST([METISINCL])
+		AC_SUBST([METISLIB])
+	else
+		HAVE_METIS=no
+	fi
+
+	if test $HAVE_METIS = no; then
+	AC_MSG_ERROR([--with-metis-dir  missing. Metis is needed to run ISSM]);
+	else
+	AC_MSG_RESULT($HAVE_METIS)
+	fi
+	dnl }}}
+	dnl mpi{{{1
+	AC_MSG_CHECKING(for mpi)
+	AC_ARG_WITH([mpi-lib],
+			  AS_HELP_STRING([--with-mpi-lib = otions],
+							 [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=""])
+
+	dnl check that --with-mpi-include and --with-mpi-lib have been provided
+	if test -z "$MPILIB" ; then
+		if test "$PARALLEL_VALUE" = "yes" ; then
+			AC_MSG_ERROR([empty --with-mpi-lib options! MPI is needed to run ISSM in parallel!])
+		fi
+	else
+		if test -z "$MPI_INCLUDE" ; then
+			if test "$PARALLEL_VALUE" = "yes" ; then
+				AC_MSG_ERROR([empty --with-mpi-include directory! MPI is needed to run ISSM in parallel!])
+			fi
+		else
+			HAVE_MPI=yes
+			MPIINCL=-I"$MPI_INCLUDE/"
+			
+			AC_DEFINE([_HAVE_MPI_],[1],[with Mpi in ISSM src])
+			AC_DEFINE([HAVE_MPI],[1],[with Mpi in ISSM src])
+			AC_SUBST([MPIINCL])
+			AC_SUBST([MPILIB])
+		fi
+	fi
+	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl petsc{{{1
+	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 "$PARALLEL_VALUE" = "yes" ; then
+		if test "$PETSC_ROOT" = "" ; then
+			AC_MSG_ERROR([missing --with-petsc-dir argument for parallel compilation!])
+		fi
+	fi
+
+	dnl if test "$PARALLEL_VALUE" = "yes" ; 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)
+	dnl fi
+	
+		
+	AC_ARG_WITH([petsc-arch],
+			  AS_HELP_STRING([--with-petsc-arch = DIR],
+							 [petsc arch , necessary for parallel build]),
+			  [PETSC_ARCH=$withval],[PETSC_ARCH=""])
+
+	if test "$PARALLEL_VALUE" = "yes" ; then
+		if test "$PETSC_ARCH" = "" ; then
+			AC_MSG_ERROR([missing --with-petsc-arch argument for parallel compilation!])
+		fi
+	fi
+	
+	AC_MSG_CHECKING(for Petsc headers and libraries in $PETSC_ROOT for architecture $PETSC_ARCH)
+	
+	if test -d "$PETSC_ROOT"; then
+
+		PETSCINCL="-I$PETSC_ROOT/$PETSC_ARCH/include -I$PETSC_ROOT/include/$PETSC_ARCH/ -I$PETSC_ROOT/include -I$PETSC_ROOT/ -I$PETSC_ROOT/bmake/$PETSC_ARCH -I$PETSC_ROOT/src/mat/impls/dense/mpi/plapack/"
+	
+		case "${host_os}" in
+			*cygwin*)
+			PETSCLIB="-link -LIBPATH:\"$PETSC_ROOT/$PETSC_ARCH/lib\" -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib/$PETSC_ARCH\" libpetscksp.lib  libpetscdm.lib  libpetscmat.lib  libpetscvec.lib libpetscsnes.lib libpetscts.lib libmpiuni.lib libpetsc.lib"
+			;;
+			*linux*)
+			if test "$PETSC_MAJOR" = "2" ; then
+			PETSCLIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetsc  -lpetscsnes -lpetscts"
+			else
+			PETSCLIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetsc"
+			fi
+			;;
+			*darwin*)
+			if test "$PETSC_MAJOR" = "2" ; then
+			PETSCLIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib/$PETSC_ARCH/ -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lpetsc"
+			else
+			PETSCLIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib/$PETSC_ARCH/ -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetsc"
+			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
+
+	if test $HAVE_PETSC = no; then
+		AC_MSG_ERROR([could not find petsc. user should specify --with-petsc-dir and --with-petsc-arch options. Petsc is needed to run ISSM!])
+	else
+		AC_MSG_RESULT($HAVE_PETSC)
+	fi
+	dnl }}}
+	dnl tao{{{1
+	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
+
+		dnl defaults
+		  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 mpiuni{{{1
+	dnl when running in serial mode, MPI must be ignored, and set to internal petsc mpiuni: 
+	if test "$PARALLEL_VALUE" = "no" ; then
+		HAVE_MPI=yes
+		MPIINCL=-I"$PETSC_ROOT/include/mpiuni"
+
+		case "${host_os}" in
+			*cygwin*)
+			MPILIB="-link -LIBPATH:\"$PETSC_ROOT/$PETSC_ARCH/lib\" -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib/$PETSC_ARCH\" libmpiuni.lib"
+			;;
+			*linux*)
+			MPILIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lmpiuni"
+			;;
+			*darwin*)
+			MPILIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lmpiuni"
+			;;
+		esac
+								  
+		AC_DEFINE([_HAVE_MPI_],[1],[with Mpi in ISSM src])
+		AC_DEFINE([HAVE_MPI],[1],[with Mpi in ISSM src])
+		AC_SUBST([MPIINCL])
+		AC_SUBST([MPILIB])
+	fi
+	dnl }}}
+	dnl slepc{{{1
+	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
+
+
+		dnl defaults
+		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{{{1
+	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{{{1
+	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
+		SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lscalapack"
+
+		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{{{1
+	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=""
+		
+		dnl: branch on whether we are running on windows or linux.
+		case "${host_os}" in
+			*cygwin*)
+			BLASLAPACKLIB="-link -LIBPATH:\"$BLASLAPACK_ROOT\" libf2cblas.lib  libf2clapack.lib"
+			;;
+			*linux*)
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lflapack -lfblas " 
+			;;
+			*darwin*)
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lflapack -lfblas " 
+			;;
+		esac
+								  
+
+
+		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{{{1
+	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{{{1
+	AC_ARG_WITH([plapack-lib],
+			  AS_HELP_STRING([--with-plapack-lib = lib],
+							 [plapack library]),
+			  [PLAPACK_LIB=$withval],[PLAPACK_LIB=""])
+	AC_MSG_CHECKING(for Plapack libraries)
+	
+	AC_ARG_WITH([plapack-include],
+			  AS_HELP_STRING([--with-plapack-include = include],
+							 [plapack include ]),
+			  [PLAPACK_INCLUDE=$withval],[PLAPACK_INCLUDE=""])
+	AC_MSG_CHECKING(for Plapack headers)
+	  
+	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{{{1
+
+	dnl Mumps directory
+	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
+		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
+	AC_MSG_RESULT($HAVE_MUMPS)
+	dnl }}}
+	dnl blacs{{{1
+	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=""
+		BLACSLIB=-L"$BLACS_ROOT/ -lblacs"
+        
+		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{{{1
+	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/ -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 ml{{{1
+	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=""
+		MLLIB=-L"$ML_ROOT/ -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 math{{{1
+	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{{{1
+	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
+		HAVE_FORTRAN=yes
+		FORTRANLIB="$FORTRAN_LIB"
+
+		AC_DEFINE([_HAVE_FORTRAN_],[1],[with FORTRAN in ISSM src])
+		AC_SUBST([FORTRANLIB])
+	fi
+	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl graphics{{{1
+	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
+		HAVE_GRAPHICS=yes
+		GRAPHICSLIB="$GRAPHICS_LIB"
+
+		AC_DEFINE([_HAVE_GRAPHICS_],[1],[with GRAPHICS in ISSM src])
+		AC_SUBST([GRAPHICSLIB])
+	fi
+	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl vendor{{{1
+	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-win; then
+			export CC=icl
+			export CXX=icl
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_"
+		elif test $VENDOR = intel-linux; then
+			export CC=icc
+			export CXX=icpc
+			export CXXFLAGS=" -D_INTEL_LINUX_"
+		elif test $VENDOR = intel-pleiades; then
+			export CC=icc
+			export CXX=icpc
+			export CXXFLAGS=" -O3 -xS -D_INTEL_LINUX_ "
+		else
+		AC_MSG_ERROR([unknow compiler vendor!])
+		fi
+	fi
+	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl with-steadystate{{{1
+	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{{{1
+	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{{{1
+	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{{{1
+	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{{{1
+	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{{{1
+	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{{{1
+	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{{{1
+	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{{{1
+	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{{{1
+	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{{{1
+	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{{{1
+	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 with-3d{{{1
+	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_THREED=yes
+
+		AC_DEFINE([_HAVE_THREED_],[1],[with 3d capability])
+	else
+		HAVE_THREED=no
+	fi
+	AM_CONDITIONAL([THREED], [test x$HAVE_THREED = xyes])
+	AC_MSG_RESULT($HAVE_THREED)
+	dnl }}}
+
+	dnl other options
+	dnl optimization{{{1
+	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{{{1
+	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 {{{1
+	AC_ARG_WITH([64bit-indices],
+			  AS_HELP_STRING([--with-64bit-indices = bool], [use 64 bit integers, default 0, ex: --with-64bit-indices=1]),
+			 [USE_64BIT_INDICES=$withval],[USE_64BIT_INDICES=0]) 
+	AC_MSG_CHECKING(for 64 bit indices)
+
+
+	if test "$USE_64BIT_INDICES" == "1"; then
+	AC_DEFINE([ISSM_USE_64BIT_INDICES],[1],[with 64 bits indices])
+	else
+	AC_DEFINE([ISSM_USE_64BIT_INDICES],[0],[with 64 bits indices])
+	fi
+	AC_MSG_RESULT($USE_64BIT_INDICES)
+	dnl }}}
+
+])
Index: /issm/trunk-jpl-damage/m4/libtool.m4
===================================================================
--- /issm/trunk-jpl-damage/m4/libtool.m4	(revision 11330)
+++ /issm/trunk-jpl-damage/m4/libtool.m4	(revision 11330)
@@ -0,0 +1,7357 @@
+# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
+#
+#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
+#                 2006, 2007, 2008 Free Software Foundation, Inc.
+#   Written by Gordon Matzigkeit, 1996
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+m4_define([_LT_COPYING], [dnl
+#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
+#                 2006, 2007, 2008 Free Software Foundation, Inc.
+#   Written by Gordon Matzigkeit, 1996
+#
+#   This file is part of GNU Libtool.
+#
+# GNU Libtool is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation; either version 2 of
+# the License, or (at your option) any later version.
+#
+# As a special exception to the GNU General Public License,
+# if you distribute this file as part of a program or library that
+# is built using GNU Libtool, you may include this file under the
+# same distribution terms that you use for the rest of that program.
+#
+# GNU Libtool is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Libtool; see the file COPYING.  If not, a copy
+# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
+# obtained by writing to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+])
+
+# serial 56 LT_INIT
+
+
+# LT_PREREQ(VERSION)
+# ------------------
+# Complain and exit if this libtool version is less that VERSION.
+m4_defun([LT_PREREQ],
+[m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1,
+       [m4_default([$3],
+		   [m4_fatal([Libtool version $1 or higher is required],
+		             63)])],
+       [$2])])
+
+
+# _LT_CHECK_BUILDDIR
+# ------------------
+# Complain if the absolute build directory name contains unusual characters
+m4_defun([_LT_CHECK_BUILDDIR],
+[case `pwd` in
+  *\ * | *\	*)
+    AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;;
+esac
+])
+
+
+# LT_INIT([OPTIONS])
+# ------------------
+AC_DEFUN([LT_INIT],
+[AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT
+AC_BEFORE([$0], [LT_LANG])dnl
+AC_BEFORE([$0], [LT_OUTPUT])dnl
+AC_BEFORE([$0], [LTDL_INIT])dnl
+m4_require([_LT_CHECK_BUILDDIR])dnl
+
+dnl Autoconf doesn't catch unexpanded LT_ macros by default:
+m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl
+m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl
+dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4
+dnl unless we require an AC_DEFUNed macro:
+AC_REQUIRE([LTOPTIONS_VERSION])dnl
+AC_REQUIRE([LTSUGAR_VERSION])dnl
+AC_REQUIRE([LTVERSION_VERSION])dnl
+AC_REQUIRE([LTOBSOLETE_VERSION])dnl
+m4_require([_LT_PROG_LTMAIN])dnl
+
+dnl Parse OPTIONS
+_LT_SET_OPTIONS([$0], [$1])
+
+# This can be used to rebuild libtool when needed
+LIBTOOL_DEPS="$ltmain"
+
+# Always use our own libtool.
+LIBTOOL='$(SHELL) $(top_builddir)/libtool'
+AC_SUBST(LIBTOOL)dnl
+
+_LT_SETUP
+
+# Only expand once:
+m4_define([LT_INIT])
+])# LT_INIT
+
+# Old names:
+AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT])
+AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_PROG_LIBTOOL], [])
+dnl AC_DEFUN([AM_PROG_LIBTOOL], [])
+
+
+# _LT_CC_BASENAME(CC)
+# -------------------
+# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
+m4_defun([_LT_CC_BASENAME],
+[for cc_temp in $1""; do
+  case $cc_temp in
+    compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
+    distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
+    \-*) ;;
+    *) break;;
+  esac
+done
+cc_basename=`$ECHO "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+])
+
+
+# _LT_FILEUTILS_DEFAULTS
+# ----------------------
+# It is okay to use these file commands and assume they have been set
+# sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'.
+m4_defun([_LT_FILEUTILS_DEFAULTS],
+[: ${CP="cp -f"}
+: ${MV="mv -f"}
+: ${RM="rm -f"}
+])# _LT_FILEUTILS_DEFAULTS
+
+
+# _LT_SETUP
+# ---------
+m4_defun([_LT_SETUP],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+_LT_DECL([], [host_alias], [0], [The host system])dnl
+_LT_DECL([], [host], [0])dnl
+_LT_DECL([], [host_os], [0])dnl
+dnl
+_LT_DECL([], [build_alias], [0], [The build system])dnl
+_LT_DECL([], [build], [0])dnl
+_LT_DECL([], [build_os], [0])dnl
+dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([LT_PATH_LD])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+dnl
+AC_REQUIRE([AC_PROG_LN_S])dnl
+test -z "$LN_S" && LN_S="ln -s"
+_LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl
+dnl
+AC_REQUIRE([LT_CMD_MAX_LEN])dnl
+_LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl
+_LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl
+dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_CHECK_SHELL_FEATURES])dnl
+m4_require([_LT_CMD_RELOAD])dnl
+m4_require([_LT_CHECK_MAGIC_METHOD])dnl
+m4_require([_LT_CMD_OLD_ARCHIVE])dnl
+m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
+
+_LT_CONFIG_LIBTOOL_INIT([
+# See if we are running on zsh, and set the options which allow our
+# commands through without removal of \ escapes INIT.
+if test -n "\${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
+fi
+])
+if test -n "${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
+fi
+
+_LT_CHECK_OBJDIR
+
+m4_require([_LT_TAG_COMPILER])dnl
+_LT_PROG_ECHO_BACKSLASH
+
+case $host_os in
+aix3*)
+  # AIX sometimes has problems with the GCC collect2 program.  For some
+  # reason, if we set the COLLECT_NAMES environment variable, the problems
+  # vanish in a puff of smoke.
+  if test "X${COLLECT_NAMES+set}" != Xset; then
+    COLLECT_NAMES=
+    export COLLECT_NAMES
+  fi
+  ;;
+esac
+
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+sed_quote_subst='s/\([["`$\\]]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst='s/\([["`\\]]\)/\\\1/g'
+
+# Sed substitution to delay expansion of an escaped shell variable in a
+# double_quote_subst'ed string.
+delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
+
+# Sed substitution to delay expansion of an escaped single quote.
+delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'
+
+# Sed substitution to avoid accidental globbing in evaled expressions
+no_glob_subst='s/\*/\\\*/g'
+
+# Global variables:
+ofile=libtool
+can_build_shared=yes
+
+# All known linkers require a `.a' archive for static linking (except MSVC,
+# which needs '.lib').
+libext=a
+
+with_gnu_ld="$lt_cv_prog_gnu_ld"
+
+old_CC="$CC"
+old_CFLAGS="$CFLAGS"
+
+# Set sane defaults for various variables
+test -z "$CC" && CC=cc
+test -z "$LTCC" && LTCC=$CC
+test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
+test -z "$LD" && LD=ld
+test -z "$ac_objext" && ac_objext=o
+
+_LT_CC_BASENAME([$compiler])
+
+# Only perform the check for file, if the check method requires it
+test -z "$MAGIC_CMD" && MAGIC_CMD=file
+case $deplibs_check_method in
+file_magic*)
+  if test "$file_magic_cmd" = '$MAGIC_CMD'; then
+    _LT_PATH_MAGIC
+  fi
+  ;;
+esac
+
+# Use C for the default configuration in the libtool script
+LT_SUPPORTED_TAG([CC])
+_LT_LANG_C_CONFIG
+_LT_LANG_DEFAULT_CONFIG
+_LT_CONFIG_COMMANDS
+])# _LT_SETUP
+
+
+# _LT_PROG_LTMAIN
+# ---------------
+# Note that this code is called both from `configure', and `config.status'
+# now that we use AC_CONFIG_COMMANDS to generate libtool.  Notably,
+# `config.status' has no value for ac_aux_dir unless we are using Automake,
+# so we pass a copy along to make sure it has a sensible value anyway.
+m4_defun([_LT_PROG_LTMAIN],
+[m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl
+_LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir'])
+ltmain="$ac_aux_dir/ltmain.sh"
+])# _LT_PROG_LTMAIN
+
+
+## ------------------------------------- ##
+## Accumulate code for creating libtool. ##
+## ------------------------------------- ##
+
+# So that we can recreate a full libtool script including additional
+# tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS
+# in macros and then make a single call at the end using the `libtool'
+# label.
+
+
+# _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS])
+# ----------------------------------------
+# Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later.
+m4_define([_LT_CONFIG_LIBTOOL_INIT],
+[m4_ifval([$1],
+          [m4_append([_LT_OUTPUT_LIBTOOL_INIT],
+                     [$1
+])])])
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_INIT])
+
+
+# _LT_CONFIG_LIBTOOL([COMMANDS])
+# ------------------------------
+# Register COMMANDS to be passed to AC_CONFIG_COMMANDS later.
+m4_define([_LT_CONFIG_LIBTOOL],
+[m4_ifval([$1],
+          [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS],
+                     [$1
+])])])
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS])
+
+
+# _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS])
+# -----------------------------------------------------
+m4_defun([_LT_CONFIG_SAVE_COMMANDS],
+[_LT_CONFIG_LIBTOOL([$1])
+_LT_CONFIG_LIBTOOL_INIT([$2])
+])
+
+
+# _LT_FORMAT_COMMENT([COMMENT])
+# -----------------------------
+# Add leading comment marks to the start of each line, and a trailing
+# full-stop to the whole comment if one is not present already.
+m4_define([_LT_FORMAT_COMMENT],
+[m4_ifval([$1], [
+m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])],
+              [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.])
+)])
+
+
+
+## ------------------------ ##
+## FIXME: Eliminate VARNAME ##
+## ------------------------ ##
+
+
+# _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?])
+# -------------------------------------------------------------------
+# CONFIGNAME is the name given to the value in the libtool script.
+# VARNAME is the (base) name used in the configure script.
+# VALUE may be 0, 1 or 2 for a computed quote escaped value based on
+# VARNAME.  Any other value will be used directly.
+m4_define([_LT_DECL],
+[lt_if_append_uniq([lt_decl_varnames], [$2], [, ],
+    [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name],
+	[m4_ifval([$1], [$1], [$2])])
+    lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3])
+    m4_ifval([$4],
+	[lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])])
+    lt_dict_add_subkey([lt_decl_dict], [$2],
+	[tagged?], [m4_ifval([$5], [yes], [no])])])
+])
+
+
+# _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION])
+# --------------------------------------------------------
+m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])])
+
+
+# lt_decl_tag_varnames([SEPARATOR], [VARNAME1...])
+# ------------------------------------------------
+m4_define([lt_decl_tag_varnames],
+[_lt_decl_filter([tagged?], [yes], $@)])
+
+
+# _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..])
+# ---------------------------------------------------------
+m4_define([_lt_decl_filter],
+[m4_case([$#],
+  [0], [m4_fatal([$0: too few arguments: $#])],
+  [1], [m4_fatal([$0: too few arguments: $#: $1])],
+  [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)],
+  [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)],
+  [lt_dict_filter([lt_decl_dict], $@)])[]dnl
+])
+
+
+# lt_decl_quote_varnames([SEPARATOR], [VARNAME1...])
+# --------------------------------------------------
+m4_define([lt_decl_quote_varnames],
+[_lt_decl_filter([value], [1], $@)])
+
+
+# lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...])
+# ---------------------------------------------------
+m4_define([lt_decl_dquote_varnames],
+[_lt_decl_filter([value], [2], $@)])
+
+
+# lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...])
+# ---------------------------------------------------
+m4_define([lt_decl_varnames_tagged],
+[m4_assert([$# <= 2])dnl
+_$0(m4_quote(m4_default([$1], [[, ]])),
+    m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]),
+    m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))])
+m4_define([_lt_decl_varnames_tagged],
+[m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])])
+
+
+# lt_decl_all_varnames([SEPARATOR], [VARNAME1...])
+# ------------------------------------------------
+m4_define([lt_decl_all_varnames],
+[_$0(m4_quote(m4_default([$1], [[, ]])),
+     m4_if([$2], [],
+	   m4_quote(lt_decl_varnames),
+	m4_quote(m4_shift($@))))[]dnl
+])
+m4_define([_lt_decl_all_varnames],
+[lt_join($@, lt_decl_varnames_tagged([$1],
+			lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl
+])
+
+
+# _LT_CONFIG_STATUS_DECLARE([VARNAME])
+# ------------------------------------
+# Quote a variable value, and forward it to `config.status' so that its
+# declaration there will have the same value as in `configure'.  VARNAME
+# must have a single quote delimited value for this to work.
+m4_define([_LT_CONFIG_STATUS_DECLARE],
+[$1='`$ECHO "X$][$1" | $Xsed -e "$delay_single_quote_subst"`'])
+
+
+# _LT_CONFIG_STATUS_DECLARATIONS
+# ------------------------------
+# We delimit libtool config variables with single quotes, so when
+# we write them to config.status, we have to be sure to quote all
+# embedded single quotes properly.  In configure, this macro expands
+# each variable declared with _LT_DECL (and _LT_TAGDECL) into:
+#
+#    <var>='`$ECHO "X$<var>" | $Xsed -e "$delay_single_quote_subst"`'
+m4_defun([_LT_CONFIG_STATUS_DECLARATIONS],
+[m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames),
+    [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])])
+
+
+# _LT_LIBTOOL_TAGS
+# ----------------
+# Output comment and list of tags supported by the script
+m4_defun([_LT_LIBTOOL_TAGS],
+[_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl
+available_tags="_LT_TAGS"dnl
+])
+
+
+# _LT_LIBTOOL_DECLARE(VARNAME, [TAG])
+# -----------------------------------
+# Extract the dictionary values for VARNAME (optionally with TAG) and
+# expand to a commented shell variable setting:
+#
+#    # Some comment about what VAR is for.
+#    visible_name=$lt_internal_name
+m4_define([_LT_LIBTOOL_DECLARE],
+[_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1],
+					   [description])))[]dnl
+m4_pushdef([_libtool_name],
+    m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl
+m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])),
+    [0], [_libtool_name=[$]$1],
+    [1], [_libtool_name=$lt_[]$1],
+    [2], [_libtool_name=$lt_[]$1],
+    [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl
+m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl
+])
+
+
+# _LT_LIBTOOL_CONFIG_VARS
+# -----------------------
+# Produce commented declarations of non-tagged libtool config variables
+# suitable for insertion in the LIBTOOL CONFIG section of the `libtool'
+# script.  Tagged libtool config variables (even for the LIBTOOL CONFIG
+# section) are produced by _LT_LIBTOOL_TAG_VARS.
+m4_defun([_LT_LIBTOOL_CONFIG_VARS],
+[m4_foreach([_lt_var],
+    m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)),
+    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])])
+
+
+# _LT_LIBTOOL_TAG_VARS(TAG)
+# -------------------------
+m4_define([_LT_LIBTOOL_TAG_VARS],
+[m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames),
+    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])])
+
+
+# _LT_TAGVAR(VARNAME, [TAGNAME])
+# ------------------------------
+m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])])
+
+
+# _LT_CONFIG_COMMANDS
+# -------------------
+# Send accumulated output to $CONFIG_STATUS.  Thanks to the lists of
+# variables for single and double quote escaping we saved from calls
+# to _LT_DECL, we can put quote escaped variables declarations
+# into `config.status', and then the shell code to quote escape them in
+# for loops in `config.status'.  Finally, any additional code accumulated
+# from calls to _LT_CONFIG_LIBTOOL_INIT is expanded.
+m4_defun([_LT_CONFIG_COMMANDS],
+[AC_PROVIDE_IFELSE([LT_OUTPUT],
+	dnl If the libtool generation code has been placed in $CONFIG_LT,
+	dnl instead of duplicating it all over again into config.status,
+	dnl then we will have config.status run $CONFIG_LT later, so it
+	dnl needs to know what name is stored there:
+        [AC_CONFIG_COMMANDS([libtool],
+            [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])],
+    dnl If the libtool generation code is destined for config.status,
+    dnl expand the accumulated commands and init code now:
+    [AC_CONFIG_COMMANDS([libtool],
+        [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])])
+])#_LT_CONFIG_COMMANDS
+
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT],
+[
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+sed_quote_subst='$sed_quote_subst'
+double_quote_subst='$double_quote_subst'
+delay_variable_subst='$delay_variable_subst'
+_LT_CONFIG_STATUS_DECLARATIONS
+LTCC='$LTCC'
+LTCFLAGS='$LTCFLAGS'
+compiler='$compiler_DEFAULT'
+
+# Quote evaled strings.
+for var in lt_decl_all_varnames([[ \
+]], lt_decl_quote_varnames); do
+    case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in
+    *[[\\\\\\\`\\"\\\$]]*)
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
+
+# Double-quote double-evaled strings.
+for var in lt_decl_all_varnames([[ \
+]], lt_decl_dquote_varnames); do
+    case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in
+    *[[\\\\\\\`\\"\\\$]]*)
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
+
+# Fix-up fallback echo if it was mangled by the above quoting rules.
+case \$lt_ECHO in
+*'\\\[$]0 --fallback-echo"')dnl "
+  lt_ECHO=\`\$ECHO "X\$lt_ECHO" | \$Xsed -e 's/\\\\\\\\\\\\\\\[$]0 --fallback-echo"\[$]/\[$]0 --fallback-echo"/'\`
+  ;;
+esac
+
+_LT_OUTPUT_LIBTOOL_INIT
+])
+
+
+# LT_OUTPUT
+# ---------
+# This macro allows early generation of the libtool script (before
+# AC_OUTPUT is called), incase it is used in configure for compilation
+# tests.
+AC_DEFUN([LT_OUTPUT],
+[: ${CONFIG_LT=./config.lt}
+AC_MSG_NOTICE([creating $CONFIG_LT])
+cat >"$CONFIG_LT" <<_LTEOF
+#! $SHELL
+# Generated by $as_me.
+# Run this file to recreate a libtool stub with the current configuration.
+
+lt_cl_silent=false
+SHELL=\${CONFIG_SHELL-$SHELL}
+_LTEOF
+
+cat >>"$CONFIG_LT" <<\_LTEOF
+AS_SHELL_SANITIZE
+_AS_PREPARE
+
+exec AS_MESSAGE_FD>&1
+exec AS_MESSAGE_LOG_FD>>config.log
+{
+  echo
+  AS_BOX([Running $as_me.])
+} >&AS_MESSAGE_LOG_FD
+
+lt_cl_help="\
+\`$as_me' creates a local libtool stub from the current configuration,
+for use in further configure time tests before the real libtool is
+generated.
+
+Usage: $[0] [[OPTIONS]]
+
+  -h, --help      print this help, then exit
+  -V, --version   print version number, then exit
+  -q, --quiet     do not print progress messages
+  -d, --debug     don't remove temporary files
+
+Report bugs to <bug-libtool@gnu.org>."
+
+lt_cl_version="\
+m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl
+m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION])
+configured by $[0], generated by m4_PACKAGE_STRING.
+
+Copyright (C) 2008 Free Software Foundation, Inc.
+This config.lt script is free software; the Free Software Foundation
+gives unlimited permision to copy, distribute and modify it."
+
+while test $[#] != 0
+do
+  case $[1] in
+    --version | --v* | -V )
+      echo "$lt_cl_version"; exit 0 ;;
+    --help | --h* | -h )
+      echo "$lt_cl_help"; exit 0 ;;
+    --debug | --d* | -d )
+      debug=: ;;
+    --quiet | --q* | --silent | --s* | -q )
+      lt_cl_silent=: ;;
+
+    -*) AC_MSG_ERROR([unrecognized option: $[1]
+Try \`$[0] --help' for more information.]) ;;
+
+    *) AC_MSG_ERROR([unrecognized argument: $[1]
+Try \`$[0] --help' for more information.]) ;;
+  esac
+  shift
+done
+
+if $lt_cl_silent; then
+  exec AS_MESSAGE_FD>/dev/null
+fi
+_LTEOF
+
+cat >>"$CONFIG_LT" <<_LTEOF
+_LT_OUTPUT_LIBTOOL_COMMANDS_INIT
+_LTEOF
+
+cat >>"$CONFIG_LT" <<\_LTEOF
+AC_MSG_NOTICE([creating $ofile])
+_LT_OUTPUT_LIBTOOL_COMMANDS
+AS_EXIT(0)
+_LTEOF
+chmod +x "$CONFIG_LT"
+
+# configure is writing to config.log, but config.lt does its own redirection,
+# appending to config.log, which fails on DOS, as config.log is still kept
+# open by configure.  Here we exec the FD to /dev/null, effectively closing
+# config.log, so it can be properly (re)opened and appended to by config.lt.
+if test "$no_create" != yes; then
+  lt_cl_success=:
+  test "$silent" = yes &&
+    lt_config_lt_args="$lt_config_lt_args --quiet"
+  exec AS_MESSAGE_LOG_FD>/dev/null
+  $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false
+  exec AS_MESSAGE_LOG_FD>>config.log
+  $lt_cl_success || AS_EXIT(1)
+fi
+])# LT_OUTPUT
+
+
+# _LT_CONFIG(TAG)
+# ---------------
+# If TAG is the built-in tag, create an initial libtool script with a
+# default configuration from the untagged config vars.  Otherwise add code
+# to config.status for appending the configuration named by TAG from the
+# matching tagged config vars.
+m4_defun([_LT_CONFIG],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+_LT_CONFIG_SAVE_COMMANDS([
+  m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl
+  m4_if(_LT_TAG, [C], [
+    # See if we are running on zsh, and set the options which allow our
+    # commands through without removal of \ escapes.
+    if test -n "${ZSH_VERSION+set}" ; then
+      setopt NO_GLOB_SUBST
+    fi
+
+    cfgfile="${ofile}T"
+    trap "$RM \"$cfgfile\"; exit 1" 1 2 15
+    $RM "$cfgfile"
+
+    cat <<_LT_EOF >> "$cfgfile"
+#! $SHELL
+
+# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
+# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+# NOTE: Changes made to this file will be lost: look at ltmain.sh.
+#
+_LT_COPYING
+_LT_LIBTOOL_TAGS
+
+# ### BEGIN LIBTOOL CONFIG
+_LT_LIBTOOL_CONFIG_VARS
+_LT_LIBTOOL_TAG_VARS
+# ### END LIBTOOL CONFIG
+
+_LT_EOF
+
+  case $host_os in
+  aix3*)
+    cat <<\_LT_EOF >> "$cfgfile"
+# AIX sometimes has problems with the GCC collect2 program.  For some
+# reason, if we set the COLLECT_NAMES environment variable, the problems
+# vanish in a puff of smoke.
+if test "X${COLLECT_NAMES+set}" != Xset; then
+  COLLECT_NAMES=
+  export COLLECT_NAMES
+fi
+_LT_EOF
+    ;;
+  esac
+
+  _LT_PROG_LTMAIN
+
+  # We use sed instead of cat because bash on DJGPP gets confused if
+  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
+  # text mode, it properly converts lines to CR/LF.  This bash problem
+  # is reportedly fixed, but why not run on old versions too?
+  sed '/^# Generated shell functions inserted here/q' "$ltmain" >> "$cfgfile" \
+    || (rm -f "$cfgfile"; exit 1)
+
+  _LT_PROG_XSI_SHELLFNS
+
+  sed -n '/^# Generated shell functions inserted here/,$p' "$ltmain" >> "$cfgfile" \
+    || (rm -f "$cfgfile"; exit 1)
+
+  mv -f "$cfgfile" "$ofile" ||
+    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
+  chmod +x "$ofile"
+],
+[cat <<_LT_EOF >> "$ofile"
+
+dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded
+dnl in a comment (ie after a #).
+# ### BEGIN LIBTOOL TAG CONFIG: $1
+_LT_LIBTOOL_TAG_VARS(_LT_TAG)
+# ### END LIBTOOL TAG CONFIG: $1
+_LT_EOF
+])dnl /m4_if
+],
+[m4_if([$1], [], [
+    PACKAGE='$PACKAGE'
+    VERSION='$VERSION'
+    TIMESTAMP='$TIMESTAMP'
+    RM='$RM'
+    ofile='$ofile'], [])
+])dnl /_LT_CONFIG_SAVE_COMMANDS
+])# _LT_CONFIG
+
+
+# LT_SUPPORTED_TAG(TAG)
+# ---------------------
+# Trace this macro to discover what tags are supported by the libtool
+# --tag option, using:
+#    autoconf --trace 'LT_SUPPORTED_TAG:$1'
+AC_DEFUN([LT_SUPPORTED_TAG], [])
+
+
+# C support is built-in for now
+m4_define([_LT_LANG_C_enabled], [])
+m4_define([_LT_TAGS], [])
+
+
+# LT_LANG(LANG)
+# -------------
+# Enable libtool support for the given language if not already enabled.
+AC_DEFUN([LT_LANG],
+[AC_BEFORE([$0], [LT_OUTPUT])dnl
+m4_case([$1],
+  [C],			[_LT_LANG(C)],
+  [C++],		[_LT_LANG(CXX)],
+  [Java],		[_LT_LANG(GCJ)],
+  [Fortran 77],		[_LT_LANG(F77)],
+  [Fortran],		[_LT_LANG(FC)],
+  [Windows Resource],	[_LT_LANG(RC)],
+  [m4_ifdef([_LT_LANG_]$1[_CONFIG],
+    [_LT_LANG($1)],
+    [m4_fatal([$0: unsupported language: "$1"])])])dnl
+])# LT_LANG
+
+
+# _LT_LANG(LANGNAME)
+# ------------------
+m4_defun([_LT_LANG],
+[m4_ifdef([_LT_LANG_]$1[_enabled], [],
+  [LT_SUPPORTED_TAG([$1])dnl
+  m4_append([_LT_TAGS], [$1 ])dnl
+  m4_define([_LT_LANG_]$1[_enabled], [])dnl
+  _LT_LANG_$1_CONFIG($1)])dnl
+])# _LT_LANG
+
+
+# _LT_LANG_DEFAULT_CONFIG
+# -----------------------
+m4_defun([_LT_LANG_DEFAULT_CONFIG],
+[AC_PROVIDE_IFELSE([AC_PROG_CXX],
+  [LT_LANG(CXX)],
+  [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])])
+
+AC_PROVIDE_IFELSE([AC_PROG_F77],
+  [LT_LANG(F77)],
+  [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])])
+
+AC_PROVIDE_IFELSE([AC_PROG_FC],
+  [LT_LANG(FC)],
+  [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])])
+
+dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal
+dnl pulling things in needlessly.
+AC_PROVIDE_IFELSE([AC_PROG_GCJ],
+  [LT_LANG(GCJ)],
+  [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],
+    [LT_LANG(GCJ)],
+    [AC_PROVIDE_IFELSE([LT_PROG_GCJ],
+      [LT_LANG(GCJ)],
+      [m4_ifdef([AC_PROG_GCJ],
+	[m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])])
+       m4_ifdef([A][M_PROG_GCJ],
+	[m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])])
+       m4_ifdef([LT_PROG_GCJ],
+	[m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])])
+
+AC_PROVIDE_IFELSE([LT_PROG_RC],
+  [LT_LANG(RC)],
+  [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])])
+])# _LT_LANG_DEFAULT_CONFIG
+
+# Obsolete macros:
+AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)])
+AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)])
+AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)])
+AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_CXX], [])
+dnl AC_DEFUN([AC_LIBTOOL_F77], [])
+dnl AC_DEFUN([AC_LIBTOOL_FC], [])
+dnl AC_DEFUN([AC_LIBTOOL_GCJ], [])
+
+
+# _LT_TAG_COMPILER
+# ----------------
+m4_defun([_LT_TAG_COMPILER],
+[AC_REQUIRE([AC_PROG_CC])dnl
+
+_LT_DECL([LTCC], [CC], [1], [A C compiler])dnl
+_LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl
+_LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl
+_LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+])# _LT_TAG_COMPILER
+
+
+# _LT_COMPILER_BOILERPLATE
+# ------------------------
+# Check for compiler boilerplate output or warnings with
+# the simple compiler test code.
+m4_defun([_LT_COMPILER_BOILERPLATE],
+[m4_require([_LT_DECL_SED])dnl
+ac_outfile=conftest.$ac_objext
+echo "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$RM conftest*
+])# _LT_COMPILER_BOILERPLATE
+
+
+# _LT_LINKER_BOILERPLATE
+# ----------------------
+# Check for linker boilerplate output or warnings with
+# the simple link test code.
+m4_defun([_LT_LINKER_BOILERPLATE],
+[m4_require([_LT_DECL_SED])dnl
+ac_outfile=conftest.$ac_objext
+echo "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$RM -r conftest*
+])# _LT_LINKER_BOILERPLATE
+
+# _LT_REQUIRED_DARWIN_CHECKS
+# -------------------------
+m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[
+  case $host_os in
+    rhapsody* | darwin*)
+    AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:])
+    AC_CHECK_TOOL([NMEDIT], [nmedit], [:])
+    AC_CHECK_TOOL([LIPO], [lipo], [:])
+    AC_CHECK_TOOL([OTOOL], [otool], [:])
+    AC_CHECK_TOOL([OTOOL64], [otool64], [:])
+    _LT_DECL([], [DSYMUTIL], [1],
+      [Tool to manipulate archived DWARF debug symbol files on Mac OS X])
+    _LT_DECL([], [NMEDIT], [1],
+      [Tool to change global to local symbols on Mac OS X])
+    _LT_DECL([], [LIPO], [1],
+      [Tool to manipulate fat objects and archives on Mac OS X])
+    _LT_DECL([], [OTOOL], [1],
+      [ldd/readelf like tool for Mach-O binaries on Mac OS X])
+    _LT_DECL([], [OTOOL64], [1],
+      [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4])
+
+    AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod],
+      [lt_cv_apple_cc_single_mod=no
+      if test -z "${LT_MULTI_MODULE}"; then
+	# By default we will add the -single_module flag. You can override
+	# by either setting the environment variable LT_MULTI_MODULE
+	# non-empty at configure time, or by adding -multi_module to the
+	# link flags.
+	rm -rf libconftest.dylib*
+	echo "int foo(void){return 1;}" > conftest.c
+	echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+-dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD
+	$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+	  -dynamiclib -Wl,-single_module conftest.c 2>conftest.err
+        _lt_result=$?
+	if test -f libconftest.dylib && test ! -s conftest.err && test $_lt_result = 0; then
+	  lt_cv_apple_cc_single_mod=yes
+	else
+	  cat conftest.err >&AS_MESSAGE_LOG_FD
+	fi
+	rm -rf libconftest.dylib*
+	rm -f conftest.*
+      fi])
+    AC_CACHE_CHECK([for -exported_symbols_list linker flag],
+      [lt_cv_ld_exported_symbols_list],
+      [lt_cv_ld_exported_symbols_list=no
+      save_LDFLAGS=$LDFLAGS
+      echo "_main" > conftest.sym
+      LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym"
+      AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+	[lt_cv_ld_exported_symbols_list=yes],
+	[lt_cv_ld_exported_symbols_list=no])
+	LDFLAGS="$save_LDFLAGS"
+    ])
+    case $host_os in
+    rhapsody* | darwin1.[[012]])
+      _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;;
+    darwin1.*)
+      _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+    darwin*) # darwin 5.x on
+      # if running on 10.5 or later, the deployment target defaults
+      # to the OS version, if on x86, and 10.4, the deployment
+      # target defaults to 10.4. Don't you love it?
+      case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
+	10.0,*86*-darwin8*|10.0,*-darwin[[91]]*)
+	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+	10.[[012]]*)
+	  _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+	10.*)
+	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+      esac
+    ;;
+  esac
+    if test "$lt_cv_apple_cc_single_mod" = "yes"; then
+      _lt_dar_single_mod='$single_module'
+    fi
+    if test "$lt_cv_ld_exported_symbols_list" = "yes"; then
+      _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym'
+    else
+      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
+    fi
+    if test "$DSYMUTIL" != ":"; then
+      _lt_dsymutil='~$DSYMUTIL $lib || :'
+    else
+      _lt_dsymutil=
+    fi
+    ;;
+  esac
+])
+
+
+# _LT_DARWIN_LINKER_FEATURES
+# --------------------------
+# Checks for linker and compiler features on darwin
+m4_defun([_LT_DARWIN_LINKER_FEATURES],
+[
+  m4_require([_LT_REQUIRED_DARWIN_CHECKS])
+  _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+  _LT_TAGVAR(hardcode_direct, $1)=no
+  _LT_TAGVAR(hardcode_automatic, $1)=yes
+  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+  _LT_TAGVAR(whole_archive_flag_spec, $1)=''
+  _LT_TAGVAR(link_all_deplibs, $1)=yes
+  _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined"
+  case $cc_basename in
+     ifort*) _lt_dar_can_shared=yes ;;
+     *) _lt_dar_can_shared=$GCC ;;
+  esac
+  if test "$_lt_dar_can_shared" = "yes"; then
+    output_verbose_link_cmd=echo
+    _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
+    _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
+    _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
+    _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
+    m4_if([$1], [CXX],
+[   if test "$lt_cv_apple_cc_single_mod" != "yes"; then
+      _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}"
+      _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}"
+    fi
+],[])
+  else
+  _LT_TAGVAR(ld_shlibs, $1)=no
+  fi
+])
+
+# _LT_SYS_MODULE_PATH_AIX
+# -----------------------
+# Links a minimal program and checks the executable
+# for the system default hardcoded library path. In most cases,
+# this is /usr/lib:/lib, but when the MPI compilers are used
+# the location of the communication and MPI libs are included too.
+# If we don't find anything, use the default library path according
+# to the aix ld manual.
+m4_defun([_LT_SYS_MODULE_PATH_AIX],
+[m4_require([_LT_DECL_SED])dnl
+AC_LINK_IFELSE(AC_LANG_PROGRAM,[
+lt_aix_libpath_sed='
+    /Import File Strings/,/^$/ {
+	/^0/ {
+	    s/^0  *\(.*\)$/\1/
+	    p
+	}
+    }'
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then
+  aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+fi],[])
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+])# _LT_SYS_MODULE_PATH_AIX
+
+
+# _LT_SHELL_INIT(ARG)
+# -------------------
+m4_define([_LT_SHELL_INIT],
+[ifdef([AC_DIVERSION_NOTICE],
+	     [AC_DIVERT_PUSH(AC_DIVERSION_NOTICE)],
+	 [AC_DIVERT_PUSH(NOTICE)])
+$1
+AC_DIVERT_POP
+])# _LT_SHELL_INIT
+
+
+# _LT_PROG_ECHO_BACKSLASH
+# -----------------------
+# Add some code to the start of the generated configure script which
+# will find an echo command which doesn't interpret backslashes.
+m4_defun([_LT_PROG_ECHO_BACKSLASH],
+[_LT_SHELL_INIT([
+# Check that we are running under the correct shell.
+SHELL=${CONFIG_SHELL-/bin/sh}
+
+case X$lt_ECHO in
+X*--fallback-echo)
+  # Remove one level of quotation (which was required for Make).
+  ECHO=`echo "$lt_ECHO" | sed 's,\\\\\[$]\\[$]0,'[$]0','`
+  ;;
+esac
+
+ECHO=${lt_ECHO-echo}
+if test "X[$]1" = X--no-reexec; then
+  # Discard the --no-reexec flag, and continue.
+  shift
+elif test "X[$]1" = X--fallback-echo; then
+  # Avoid inline document here, it may be left over
+  :
+elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' ; then
+  # Yippee, $ECHO works!
+  :
+else
+  # Restart under the correct shell.
+  exec $SHELL "[$]0" --no-reexec ${1+"[$]@"}
+fi
+
+if test "X[$]1" = X--fallback-echo; then
+  # used as fallback echo
+  shift
+  cat <<_LT_EOF
+[$]*
+_LT_EOF
+  exit 0
+fi
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+if test -z "$lt_ECHO"; then
+  if test "X${echo_test_string+set}" != Xset; then
+    # find a string as large as possible, as long as the shell can cope with it
+    for cmd in 'sed 50q "[$]0"' 'sed 20q "[$]0"' 'sed 10q "[$]0"' 'sed 2q "[$]0"' 'echo test'; do
+      # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ...
+      if { echo_test_string=`eval $cmd`; } 2>/dev/null &&
+	 { test "X$echo_test_string" = "X$echo_test_string"; } 2>/dev/null
+      then
+        break
+      fi
+    done
+  fi
+
+  if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' &&
+     echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` &&
+     test "X$echo_testing_string" = "X$echo_test_string"; then
+    :
+  else
+    # The Solaris, AIX, and Digital Unix default echo programs unquote
+    # backslashes.  This makes it impossible to quote backslashes using
+    #   echo "$something" | sed 's/\\/\\\\/g'
+    #
+    # So, first we look for a working echo in the user's PATH.
+
+    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+    for dir in $PATH /usr/ucb; do
+      IFS="$lt_save_ifs"
+      if (test -f $dir/echo || test -f $dir/echo$ac_exeext) &&
+         test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' &&
+         echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` &&
+         test "X$echo_testing_string" = "X$echo_test_string"; then
+        ECHO="$dir/echo"
+        break
+      fi
+    done
+    IFS="$lt_save_ifs"
+
+    if test "X$ECHO" = Xecho; then
+      # We didn't find a better echo, so look for alternatives.
+      if test "X`{ print -r '\t'; } 2>/dev/null`" = 'X\t' &&
+         echo_testing_string=`{ print -r "$echo_test_string"; } 2>/dev/null` &&
+         test "X$echo_testing_string" = "X$echo_test_string"; then
+        # This shell has a builtin print -r that does the trick.
+        ECHO='print -r'
+      elif { test -f /bin/ksh || test -f /bin/ksh$ac_exeext; } &&
+	   test "X$CONFIG_SHELL" != X/bin/ksh; then
+        # If we have ksh, try running configure again with it.
+        ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh}
+        export ORIGINAL_CONFIG_SHELL
+        CONFIG_SHELL=/bin/ksh
+        export CONFIG_SHELL
+        exec $CONFIG_SHELL "[$]0" --no-reexec ${1+"[$]@"}
+      else
+        # Try using printf.
+        ECHO='printf %s\n'
+        if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' &&
+	   echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` &&
+	   test "X$echo_testing_string" = "X$echo_test_string"; then
+	  # Cool, printf works
+	  :
+        elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` &&
+	     test "X$echo_testing_string" = 'X\t' &&
+	     echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
+	     test "X$echo_testing_string" = "X$echo_test_string"; then
+	  CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL
+	  export CONFIG_SHELL
+	  SHELL="$CONFIG_SHELL"
+	  export SHELL
+	  ECHO="$CONFIG_SHELL [$]0 --fallback-echo"
+        elif echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` &&
+	     test "X$echo_testing_string" = 'X\t' &&
+	     echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
+	     test "X$echo_testing_string" = "X$echo_test_string"; then
+	  ECHO="$CONFIG_SHELL [$]0 --fallback-echo"
+        else
+	  # maybe with a smaller string...
+	  prev=:
+
+	  for cmd in 'echo test' 'sed 2q "[$]0"' 'sed 10q "[$]0"' 'sed 20q "[$]0"' 'sed 50q "[$]0"'; do
+	    if { test "X$echo_test_string" = "X`eval $cmd`"; } 2>/dev/null
+	    then
+	      break
+	    fi
+	    prev="$cmd"
+	  done
+
+	  if test "$prev" != 'sed 50q "[$]0"'; then
+	    echo_test_string=`eval $prev`
+	    export echo_test_string
+	    exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "[$]0" ${1+"[$]@"}
+	  else
+	    # Oops.  We lost completely, so just stick with echo.
+	    ECHO=echo
+	  fi
+        fi
+      fi
+    fi
+  fi
+fi
+
+# Copy echo and quote the copy suitably for passing to libtool from
+# the Makefile, instead of quoting the original, which is used later.
+lt_ECHO=$ECHO
+if test "X$lt_ECHO" = "X$CONFIG_SHELL [$]0 --fallback-echo"; then
+   lt_ECHO="$CONFIG_SHELL \\\$\[$]0 --fallback-echo"
+fi
+
+AC_SUBST(lt_ECHO)
+])
+_LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts])
+_LT_DECL([], [ECHO], [1],
+    [An echo program that does not interpret backslashes])
+])# _LT_PROG_ECHO_BACKSLASH
+
+
+# _LT_ENABLE_LOCK
+# ---------------
+m4_defun([_LT_ENABLE_LOCK],
+[AC_ARG_ENABLE([libtool-lock],
+  [AS_HELP_STRING([--disable-libtool-lock],
+    [avoid locking (might break parallel builds)])])
+test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
+
+# Some flags need to be propagated to the compiler or linker for good
+# libtool support.
+case $host in
+ia64-*-hpux*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.$ac_objext` in
+      *ELF-32*)
+	HPUX_IA64_MODE="32"
+	;;
+      *ELF-64*)
+	HPUX_IA64_MODE="64"
+	;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+*-*-irix6*)
+  # Find out which ABI we are using.
+  echo '[#]line __oline__ "configure"' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    if test "$lt_cv_prog_gnu_ld" = yes; then
+      case `/usr/bin/file conftest.$ac_objext` in
+	*32-bit*)
+	  LD="${LD-ld} -melf32bsmip"
+	  ;;
+	*N32*)
+	  LD="${LD-ld} -melf32bmipn32"
+	  ;;
+	*64-bit*)
+	  LD="${LD-ld} -melf64bmip"
+	;;
+      esac
+    else
+      case `/usr/bin/file conftest.$ac_objext` in
+	*32-bit*)
+	  LD="${LD-ld} -32"
+	  ;;
+	*N32*)
+	  LD="${LD-ld} -n32"
+	  ;;
+	*64-bit*)
+	  LD="${LD-ld} -64"
+	  ;;
+      esac
+    fi
+  fi
+  rm -rf conftest*
+  ;;
+
+x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \
+s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.o` in
+      *32-bit*)
+	case $host in
+	  x86_64-*kfreebsd*-gnu)
+	    LD="${LD-ld} -m elf_i386_fbsd"
+	    ;;
+	  x86_64-*linux*)
+	    LD="${LD-ld} -m elf_i386"
+	    ;;
+	  ppc64-*linux*|powerpc64-*linux*)
+	    LD="${LD-ld} -m elf32ppclinux"
+	    ;;
+	  s390x-*linux*)
+	    LD="${LD-ld} -m elf_s390"
+	    ;;
+	  sparc64-*linux*)
+	    LD="${LD-ld} -m elf32_sparc"
+	    ;;
+	esac
+	;;
+      *64-bit*)
+	case $host in
+	  x86_64-*kfreebsd*-gnu)
+	    LD="${LD-ld} -m elf_x86_64_fbsd"
+	    ;;
+	  x86_64-*linux*)
+	    LD="${LD-ld} -m elf_x86_64"
+	    ;;
+	  ppc*-*linux*|powerpc*-*linux*)
+	    LD="${LD-ld} -m elf64ppc"
+	    ;;
+	  s390*-*linux*|s390*-*tpf*)
+	    LD="${LD-ld} -m elf64_s390"
+	    ;;
+	  sparc*-*linux*)
+	    LD="${LD-ld} -m elf64_sparc"
+	    ;;
+	esac
+	;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+
+*-*-sco3.2v5*)
+  # On SCO OpenServer 5, we need -belf to get full-featured binaries.
+  SAVE_CFLAGS="$CFLAGS"
+  CFLAGS="$CFLAGS -belf"
+  AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf,
+    [AC_LANG_PUSH(C)
+     AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no])
+     AC_LANG_POP])
+  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
+    # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
+    CFLAGS="$SAVE_CFLAGS"
+  fi
+  ;;
+sparc*-*solaris*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.o` in
+    *64-bit*)
+      case $lt_cv_prog_gnu_ld in
+      yes*) LD="${LD-ld} -m elf64_sparc" ;;
+      *)
+	if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then
+	  LD="${LD-ld} -64"
+	fi
+	;;
+      esac
+      ;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+esac
+
+need_locks="$enable_libtool_lock"
+])# _LT_ENABLE_LOCK
+
+
+# _LT_CMD_OLD_ARCHIVE
+# -------------------
+m4_defun([_LT_CMD_OLD_ARCHIVE],
+[AC_CHECK_TOOL(AR, ar, false)
+test -z "$AR" && AR=ar
+test -z "$AR_FLAGS" && AR_FLAGS=cru
+_LT_DECL([], [AR], [1], [The archiver])
+_LT_DECL([], [AR_FLAGS], [1])
+
+AC_CHECK_TOOL(STRIP, strip, :)
+test -z "$STRIP" && STRIP=:
+_LT_DECL([], [STRIP], [1], [A symbol stripping program])
+
+AC_CHECK_TOOL(RANLIB, ranlib, :)
+test -z "$RANLIB" && RANLIB=:
+_LT_DECL([], [RANLIB], [1],
+    [Commands used to install an old-style archive])
+
+# Determine commands to create old-style static archives.
+old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs'
+old_postinstall_cmds='chmod 644 $oldlib'
+old_postuninstall_cmds=
+
+if test -n "$RANLIB"; then
+  case $host_os in
+  openbsd*)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib"
+    ;;
+  *)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib"
+    ;;
+  esac
+  old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib"
+fi
+_LT_DECL([], [old_postinstall_cmds], [2])
+_LT_DECL([], [old_postuninstall_cmds], [2])
+_LT_TAGDECL([], [old_archive_cmds], [2],
+    [Commands used to build an old-style archive])
+])# _LT_CMD_OLD_ARCHIVE
+
+
+# _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+#		[OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE])
+# ----------------------------------------------------------------
+# Check whether the given compiler option works
+AC_DEFUN([_LT_COMPILER_OPTION],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_SED])dnl
+AC_CACHE_CHECK([$1], [$2],
+  [$2=no
+   m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4])
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+   lt_compiler_flag="$3"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   # The option is referenced via a variable to avoid confusing sed.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+   (eval "$lt_compile" 2>conftest.err)
+   ac_status=$?
+   cat conftest.err >&AS_MESSAGE_LOG_FD
+   echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+   if (exit $ac_status) && test -s "$ac_outfile"; then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings other than the usual output.
+     $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
+     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+       $2=yes
+     fi
+   fi
+   $RM conftest*
+])
+
+if test x"[$]$2" = xyes; then
+    m4_if([$5], , :, [$5])
+else
+    m4_if([$6], , :, [$6])
+fi
+])# _LT_COMPILER_OPTION
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], [])
+
+
+# _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+#                  [ACTION-SUCCESS], [ACTION-FAILURE])
+# ----------------------------------------------------
+# Check whether the given linker option works
+AC_DEFUN([_LT_LINKER_OPTION],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_SED])dnl
+AC_CACHE_CHECK([$1], [$2],
+  [$2=no
+   save_LDFLAGS="$LDFLAGS"
+   LDFLAGS="$LDFLAGS $3"
+   echo "$lt_simple_link_test_code" > conftest.$ac_ext
+   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+     # The linker can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     if test -s conftest.err; then
+       # Append any errors to the config.log.
+       cat conftest.err 1>&AS_MESSAGE_LOG_FD
+       $ECHO "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
+       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+       if diff conftest.exp conftest.er2 >/dev/null; then
+         $2=yes
+       fi
+     else
+       $2=yes
+     fi
+   fi
+   $RM -r conftest*
+   LDFLAGS="$save_LDFLAGS"
+])
+
+if test x"[$]$2" = xyes; then
+    m4_if([$4], , :, [$4])
+else
+    m4_if([$5], , :, [$5])
+fi
+])# _LT_LINKER_OPTION
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], [])
+
+
+# LT_CMD_MAX_LEN
+#---------------
+AC_DEFUN([LT_CMD_MAX_LEN],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+# find the maximum length of command line arguments
+AC_MSG_CHECKING([the maximum length of command line arguments])
+AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
+  i=0
+  teststring="ABCD"
+
+  case $build_os in
+  msdosdjgpp*)
+    # On DJGPP, this test can blow up pretty badly due to problems in libc
+    # (any single argument exceeding 2000 bytes causes a buffer overrun
+    # during glob expansion).  Even if it were fixed, the result of this
+    # check would be larger than it should be.
+    lt_cv_sys_max_cmd_len=12288;    # 12K is about right
+    ;;
+
+  gnu*)
+    # Under GNU Hurd, this test is not required because there is
+    # no limit to the length of command line arguments.
+    # Libtool will interpret -1 as no limit whatsoever
+    lt_cv_sys_max_cmd_len=-1;
+    ;;
+
+  cygwin* | mingw* | cegcc*)
+    # On Win9x/ME, this test blows up -- it succeeds, but takes
+    # about 5 minutes as the teststring grows exponentially.
+    # Worse, since 9x/ME are not pre-emptively multitasking,
+    # you end up with a "frozen" computer, even though with patience
+    # the test eventually succeeds (with a max line length of 256k).
+    # Instead, let's just punt: use the minimum linelength reported by
+    # all of the supported platforms: 8192 (on NT/2K/XP).
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  amigaos*)
+    # On AmigaOS with pdksh, this test takes hours, literally.
+    # So we just punt and use a minimum line length of 8192.
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
+    # This has been around since 386BSD, at least.  Likely further.
+    if test -x /sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
+    elif test -x /usr/sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
+    else
+      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
+    fi
+    # And add a safety zone
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    ;;
+
+  interix*)
+    # We know the value 262144 and hardcode it with a safety zone (like BSD)
+    lt_cv_sys_max_cmd_len=196608
+    ;;
+
+  osf*)
+    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
+    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
+    # nice to cause kernel panics so lets avoid the loop below.
+    # First set a reasonable default.
+    lt_cv_sys_max_cmd_len=16384
+    #
+    if test -x /sbin/sysconfig; then
+      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
+        *1*) lt_cv_sys_max_cmd_len=-1 ;;
+      esac
+    fi
+    ;;
+  sco3.2v5*)
+    lt_cv_sys_max_cmd_len=102400
+    ;;
+  sysv5* | sco5v6* | sysv4.2uw2*)
+    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
+    if test -n "$kargmax"; then
+      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[	 ]]//'`
+    else
+      lt_cv_sys_max_cmd_len=32768
+    fi
+    ;;
+  *)
+    lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
+    if test -n "$lt_cv_sys_max_cmd_len"; then
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    else
+      # Make teststring a little bigger before we do anything with it.
+      # a 1K string should be a reasonable start.
+      for i in 1 2 3 4 5 6 7 8 ; do
+        teststring=$teststring$teststring
+      done
+      SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
+      # If test is not a shell built-in, we'll probably end up computing a
+      # maximum length that is only half of the actual maximum length, but
+      # we can't tell.
+      while { test "X"`$SHELL [$]0 --fallback-echo "X$teststring$teststring" 2>/dev/null` \
+	         = "XX$teststring$teststring"; } >/dev/null 2>&1 &&
+	      test $i != 17 # 1/2 MB should be enough
+      do
+        i=`expr $i + 1`
+        teststring=$teststring$teststring
+      done
+      # Only check the string length outside the loop.
+      lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1`
+      teststring=
+      # Add a significant safety factor because C++ compilers can tack on
+      # massive amounts of additional arguments before passing them to the
+      # linker.  It appears as though 1/2 is a usable value.
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
+    fi
+    ;;
+  esac
+])
+if test -n $lt_cv_sys_max_cmd_len ; then
+  AC_MSG_RESULT($lt_cv_sys_max_cmd_len)
+else
+  AC_MSG_RESULT(none)
+fi
+max_cmd_len=$lt_cv_sys_max_cmd_len
+_LT_DECL([], [max_cmd_len], [0],
+    [What is the maximum length of a command?])
+])# LT_CMD_MAX_LEN
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], [])
+
+
+# _LT_HEADER_DLFCN
+# ----------------
+m4_defun([_LT_HEADER_DLFCN],
+[AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl
+])# _LT_HEADER_DLFCN
+
+
+# _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE,
+#                      ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING)
+# ----------------------------------------------------------------
+m4_defun([_LT_TRY_DLOPEN_SELF],
+[m4_require([_LT_HEADER_DLFCN])dnl
+if test "$cross_compiling" = yes; then :
+  [$4]
+else
+  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+  lt_status=$lt_dlunknown
+  cat > conftest.$ac_ext <<_LT_EOF
+[#line __oline__ "configure"
+#include "confdefs.h"
+
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef RTLD_GLOBAL
+#  define LT_DLGLOBAL		RTLD_GLOBAL
+#else
+#  ifdef DL_GLOBAL
+#    define LT_DLGLOBAL		DL_GLOBAL
+#  else
+#    define LT_DLGLOBAL		0
+#  endif
+#endif
+
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+   find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+#  ifdef RTLD_LAZY
+#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
+#  else
+#    ifdef DL_LAZY
+#      define LT_DLLAZY_OR_NOW		DL_LAZY
+#    else
+#      ifdef RTLD_NOW
+#        define LT_DLLAZY_OR_NOW	RTLD_NOW
+#      else
+#        ifdef DL_NOW
+#          define LT_DLLAZY_OR_NOW	DL_NOW
+#        else
+#          define LT_DLLAZY_OR_NOW	0
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
+
+void fnord() { int i=42;}
+int main ()
+{
+  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+  int status = $lt_dlunknown;
+
+  if (self)
+    {
+      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
+      else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
+      /* dlclose (self); */
+    }
+  else
+    puts (dlerror ());
+
+  return status;
+}]
+_LT_EOF
+  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
+    (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
+    lt_status=$?
+    case x$lt_status in
+      x$lt_dlno_uscore) $1 ;;
+      x$lt_dlneed_uscore) $2 ;;
+      x$lt_dlunknown|x*) $3 ;;
+    esac
+  else :
+    # compilation failed
+    $3
+  fi
+fi
+rm -fr conftest*
+])# _LT_TRY_DLOPEN_SELF
+
+
+# LT_SYS_DLOPEN_SELF
+# ------------------
+AC_DEFUN([LT_SYS_DLOPEN_SELF],
+[m4_require([_LT_HEADER_DLFCN])dnl
+if test "x$enable_dlopen" != xyes; then
+  enable_dlopen=unknown
+  enable_dlopen_self=unknown
+  enable_dlopen_self_static=unknown
+else
+  lt_cv_dlopen=no
+  lt_cv_dlopen_libs=
+
+  case $host_os in
+  beos*)
+    lt_cv_dlopen="load_add_on"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ;;
+
+  mingw* | pw32* | cegcc*)
+    lt_cv_dlopen="LoadLibrary"
+    lt_cv_dlopen_libs=
+    ;;
+
+  cygwin*)
+    lt_cv_dlopen="dlopen"
+    lt_cv_dlopen_libs=
+    ;;
+
+  darwin*)
+  # if libdl is installed we need to link against it
+    AC_CHECK_LIB([dl], [dlopen],
+		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[
+    lt_cv_dlopen="dyld"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ])
+    ;;
+
+  *)
+    AC_CHECK_FUNC([shl_load],
+	  [lt_cv_dlopen="shl_load"],
+      [AC_CHECK_LIB([dld], [shl_load],
+	    [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"],
+	[AC_CHECK_FUNC([dlopen],
+	      [lt_cv_dlopen="dlopen"],
+	  [AC_CHECK_LIB([dl], [dlopen],
+		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],
+	    [AC_CHECK_LIB([svld], [dlopen],
+		  [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"],
+	      [AC_CHECK_LIB([dld], [dld_link],
+		    [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"])
+	      ])
+	    ])
+	  ])
+	])
+      ])
+    ;;
+  esac
+
+  if test "x$lt_cv_dlopen" != xno; then
+    enable_dlopen=yes
+  else
+    enable_dlopen=no
+  fi
+
+  case $lt_cv_dlopen in
+  dlopen)
+    save_CPPFLAGS="$CPPFLAGS"
+    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
+
+    save_LDFLAGS="$LDFLAGS"
+    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
+
+    save_LIBS="$LIBS"
+    LIBS="$lt_cv_dlopen_libs $LIBS"
+
+    AC_CACHE_CHECK([whether a program can dlopen itself],
+	  lt_cv_dlopen_self, [dnl
+	  _LT_TRY_DLOPEN_SELF(
+	    lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes,
+	    lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross)
+    ])
+
+    if test "x$lt_cv_dlopen_self" = xyes; then
+      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
+      AC_CACHE_CHECK([whether a statically linked program can dlopen itself],
+	  lt_cv_dlopen_self_static, [dnl
+	  _LT_TRY_DLOPEN_SELF(
+	    lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes,
+	    lt_cv_dlopen_self_static=no,  lt_cv_dlopen_self_static=cross)
+      ])
+    fi
+
+    CPPFLAGS="$save_CPPFLAGS"
+    LDFLAGS="$save_LDFLAGS"
+    LIBS="$save_LIBS"
+    ;;
+  esac
+
+  case $lt_cv_dlopen_self in
+  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
+  *) enable_dlopen_self=unknown ;;
+  esac
+
+  case $lt_cv_dlopen_self_static in
+  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
+  *) enable_dlopen_self_static=unknown ;;
+  esac
+fi
+_LT_DECL([dlopen_support], [enable_dlopen], [0],
+	 [Whether dlopen is supported])
+_LT_DECL([dlopen_self], [enable_dlopen_self], [0],
+	 [Whether dlopen of programs is supported])
+_LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0],
+	 [Whether dlopen of statically linked programs is supported])
+])# LT_SYS_DLOPEN_SELF
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], [])
+
+
+# _LT_COMPILER_C_O([TAGNAME])
+# ---------------------------
+# Check to see if options -c and -o are simultaneously supported by compiler.
+# This macro does not hard code the compiler like AC_PROG_CC_C_O.
+m4_defun([_LT_COMPILER_C_O],
+[m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext],
+  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)],
+  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no
+   $RM -r conftest 2>/dev/null
+   mkdir conftest
+   cd conftest
+   mkdir out
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+   lt_compiler_flag="-o out/conftest2.$ac_objext"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+   (eval "$lt_compile" 2>out/conftest.err)
+   ac_status=$?
+   cat out/conftest.err >&AS_MESSAGE_LOG_FD
+   echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+   if (exit $ac_status) && test -s out/conftest2.$ac_objext
+   then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
+     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+       _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+     fi
+   fi
+   chmod u+w . 2>&AS_MESSAGE_LOG_FD
+   $RM conftest*
+   # SGI C++ compiler will create directory out/ii_files/ for
+   # template instantiation
+   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
+   $RM out/* && rmdir out
+   cd ..
+   $RM -r conftest
+   $RM conftest*
+])
+_LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1],
+	[Does compiler simultaneously support -c and -o options?])
+])# _LT_COMPILER_C_O
+
+
+# _LT_COMPILER_FILE_LOCKS([TAGNAME])
+# ----------------------------------
+# Check to see if we can do hard links to lock some files if needed
+m4_defun([_LT_COMPILER_FILE_LOCKS],
+[m4_require([_LT_ENABLE_LOCK])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+_LT_COMPILER_C_O([$1])
+
+hard_links="nottested"
+if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then
+  # do not overwrite the value of need_locks provided by the user
+  AC_MSG_CHECKING([if we can lock with hard links])
+  hard_links=yes
+  $RM conftest*
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  touch conftest.a
+  ln conftest.a conftest.b 2>&5 || hard_links=no
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  AC_MSG_RESULT([$hard_links])
+  if test "$hard_links" = no; then
+    AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe])
+    need_locks=warn
+  fi
+else
+  need_locks=no
+fi
+_LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?])
+])# _LT_COMPILER_FILE_LOCKS
+
+
+# _LT_CHECK_OBJDIR
+# ----------------
+m4_defun([_LT_CHECK_OBJDIR],
+[AC_CACHE_CHECK([for objdir], [lt_cv_objdir],
+[rm -f .libs 2>/dev/null
+mkdir .libs 2>/dev/null
+if test -d .libs; then
+  lt_cv_objdir=.libs
+else
+  # MS-DOS does not allow filenames that begin with a dot.
+  lt_cv_objdir=_libs
+fi
+rmdir .libs 2>/dev/null])
+objdir=$lt_cv_objdir
+_LT_DECL([], [objdir], [0],
+         [The name of the directory that contains temporary libtool files])dnl
+m4_pattern_allow([LT_OBJDIR])dnl
+AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/",
+  [Define to the sub-directory in which libtool stores uninstalled libraries.])
+])# _LT_CHECK_OBJDIR
+
+
+# _LT_LINKER_HARDCODE_LIBPATH([TAGNAME])
+# --------------------------------------
+# Check hardcoding attributes.
+m4_defun([_LT_LINKER_HARDCODE_LIBPATH],
+[AC_MSG_CHECKING([how to hardcode library paths into programs])
+_LT_TAGVAR(hardcode_action, $1)=
+if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" ||
+   test -n "$_LT_TAGVAR(runpath_var, $1)" ||
+   test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then
+
+  # We can hardcode non-existent directories.
+  if test "$_LT_TAGVAR(hardcode_direct, $1)" != no &&
+     # If the only mechanism to avoid hardcoding is shlibpath_var, we
+     # have to relink, otherwise we might link with an installed library
+     # when we should be linking with a yet-to-be-installed one
+     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no &&
+     test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then
+    # Linking always hardcodes the temporary library directory.
+    _LT_TAGVAR(hardcode_action, $1)=relink
+  else
+    # We can link without hardcoding, and we can hardcode nonexisting dirs.
+    _LT_TAGVAR(hardcode_action, $1)=immediate
+  fi
+else
+  # We cannot hardcode anything, or else we can only hardcode existing
+  # directories.
+  _LT_TAGVAR(hardcode_action, $1)=unsupported
+fi
+AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)])
+
+if test "$_LT_TAGVAR(hardcode_action, $1)" = relink ||
+   test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then
+  # Fast installation is not supported
+  enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+     test "$enable_shared" = no; then
+  # Fast installation is not necessary
+  enable_fast_install=needless
+fi
+_LT_TAGDECL([], [hardcode_action], [0],
+    [How to hardcode a shared library path into an executable])
+])# _LT_LINKER_HARDCODE_LIBPATH
+
+
+# _LT_CMD_STRIPLIB
+# ----------------
+m4_defun([_LT_CMD_STRIPLIB],
+[m4_require([_LT_DECL_EGREP])
+striplib=
+old_striplib=
+AC_MSG_CHECKING([whether stripping libraries is possible])
+if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
+  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
+  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
+  AC_MSG_RESULT([yes])
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+  case $host_os in
+  darwin*)
+    if test -n "$STRIP" ; then
+      striplib="$STRIP -x"
+      old_striplib="$STRIP -S"
+      AC_MSG_RESULT([yes])
+    else
+      AC_MSG_RESULT([no])
+    fi
+    ;;
+  *)
+    AC_MSG_RESULT([no])
+    ;;
+  esac
+fi
+_LT_DECL([], [old_striplib], [1], [Commands to strip libraries])
+_LT_DECL([], [striplib], [1])
+])# _LT_CMD_STRIPLIB
+
+
+# _LT_SYS_DYNAMIC_LINKER([TAG])
+# -----------------------------
+# PORTME Fill in your ld.so characteristics
+m4_defun([_LT_SYS_DYNAMIC_LINKER],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_OBJDUMP])dnl
+m4_require([_LT_DECL_SED])dnl
+AC_MSG_CHECKING([dynamic linker characteristics])
+m4_if([$1],
+	[], [
+if test "$GCC" = yes; then
+  case $host_os in
+    darwin*) lt_awk_arg="/^libraries:/,/LR/" ;;
+    *) lt_awk_arg="/^libraries:/" ;;
+  esac
+  lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+  if $ECHO "$lt_search_path_spec" | $GREP ';' >/dev/null ; then
+    # if the path contains ";" then we assume it to be the separator
+    # otherwise default to the standard path separator (i.e. ":") - it is
+    # assumed that no part of a normal pathname contains ";" but that should
+    # okay in the real world where ";" in dirpaths is itself problematic.
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED -e 's/;/ /g'`
+  else
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED  -e "s/$PATH_SEPARATOR/ /g"`
+  fi
+  # Ok, now we have the path, separated by spaces, we can step through it
+  # and add multilib dir if necessary.
+  lt_tmp_lt_search_path_spec=
+  lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
+  for lt_sys_path in $lt_search_path_spec; do
+    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
+      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir"
+    else
+      test -d "$lt_sys_path" && \
+	lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path"
+    fi
+  done
+  lt_search_path_spec=`$ECHO $lt_tmp_lt_search_path_spec | awk '
+BEGIN {RS=" "; FS="/|\n";} {
+  lt_foo="";
+  lt_count=0;
+  for (lt_i = NF; lt_i > 0; lt_i--) {
+    if ($lt_i != "" && $lt_i != ".") {
+      if ($lt_i == "..") {
+        lt_count++;
+      } else {
+        if (lt_count == 0) {
+          lt_foo="/" $lt_i lt_foo;
+        } else {
+          lt_count--;
+        }
+      }
+    }
+  }
+  if (lt_foo != "") { lt_freq[[lt_foo]]++; }
+  if (lt_freq[[lt_foo]] == 1) { print lt_foo; }
+}'`
+  sys_lib_search_path_spec=`$ECHO $lt_search_path_spec`
+else
+  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi])
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+  shlibpath_var=LIBPATH
+
+  # AIX 3 has no versioning support, so we append a major version to the name.
+  soname_spec='${libname}${release}${shared_ext}$major'
+  ;;
+
+aix[[4-9]]*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  hardcode_into_libs=yes
+  if test "$host_cpu" = ia64; then
+    # AIX 5 supports IA64
+    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+    shlibpath_var=LD_LIBRARY_PATH
+  else
+    # With GCC up to 2.95.x, collect2 would create an import file
+    # for dependence libraries.  The import file would start with
+    # the line `#! .'.  This would cause the generated library to
+    # depend on `.', always an invalid library.  This was fixed in
+    # development snapshots of GCC prior to 3.0.
+    case $host_os in
+      aix4 | aix4.[[01]] | aix4.[[01]].*)
+      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+	   echo ' yes '
+	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
+	:
+      else
+	can_build_shared=no
+      fi
+      ;;
+    esac
+    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+    # soname into executable. Probably we can add versioning support to
+    # collect2, so additional links can be useful in future.
+    if test "$aix_use_runtimelinking" = yes; then
+      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+      # instead of lib<name>.a to let people know that these are not
+      # typical AIX shared libraries.
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    else
+      # We preserve .a as extension for shared libraries through AIX4.2
+      # and later when we are not doing run time linking.
+      library_names_spec='${libname}${release}.a $libname.a'
+      soname_spec='${libname}${release}${shared_ext}$major'
+    fi
+    shlibpath_var=LIBPATH
+  fi
+  ;;
+
+amigaos*)
+  case $host_cpu in
+  powerpc)
+    # Since July 2007 AmigaOS4 officially supports .so libraries.
+    # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    ;;
+  m68k)
+    library_names_spec='$libname.ixlibrary $libname.a'
+    # Create ${libname}_ixlibrary.a entries in /sys/libs.
+    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$ECHO "X$lib" | $Xsed -e '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+    ;;
+  esac
+  ;;
+
+beos*)
+  library_names_spec='${libname}${shared_ext}'
+  dynamic_linker="$host_os ld.so"
+  shlibpath_var=LIBRARY_PATH
+  ;;
+
+bsdi[[45]]*)
+  version_type=linux
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+  # the default ld.so.conf also contains /usr/contrib/lib and
+  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+  # libtool to hard-code these into programs
+  ;;
+
+cygwin* | mingw* | pw32* | cegcc*)
+  version_type=windows
+  shrext_cmds=".dll"
+  need_version=no
+  need_lib_prefix=no
+
+  case $GCC,$host_os in
+  yes,cygwin* | yes,mingw* | yes,pw32* | yes,cegcc*)
+    library_names_spec='$libname.dll.a'
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname~
+      chmod a+x \$dldir/$dlname~
+      if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
+        eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
+      fi'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=yes
+
+    case $host_os in
+    cygwin*)
+      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib"
+      ;;
+    mingw* | cegcc*)
+      # MinGW DLLs use traditional 'lib' prefix
+      soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      sys_lib_search_path_spec=`$CC -print-search-dirs | $GREP "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+      if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then
+        # It is most probably a Windows format PATH printed by
+        # mingw gcc, but we are running on Cygwin. Gcc prints its search
+        # path with ; separators, and with drive letters. We can handle the
+        # drive letters (cygwin fileutils understands them), so leave them,
+        # especially as we might pass files found there to a mingw objdump,
+        # which wouldn't understand a cygwinified path. Ahh.
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+      else
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED  -e "s/$PATH_SEPARATOR/ /g"`
+      fi
+      ;;
+    pw32*)
+      # pw32 DLLs use 'pw' prefix rather than 'lib'
+      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      ;;
+    esac
+    ;;
+
+  *)
+    library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib'
+    ;;
+  esac
+  dynamic_linker='Win32 ld.exe'
+  # FIXME: first we should search . and the directory the executable is in
+  shlibpath_var=PATH
+  ;;
+
+darwin* | rhapsody*)
+  dynamic_linker="$host_os dyld"
+  version_type=darwin
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+  soname_spec='${libname}${release}${major}$shared_ext'
+  shlibpath_overrides_runpath=yes
+  shlibpath_var=DYLD_LIBRARY_PATH
+  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+m4_if([$1], [],[
+  sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"])
+  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+  ;;
+
+dgux*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+freebsd1*)
+  dynamic_linker=no
+  ;;
+
+freebsd* | dragonfly*)
+  # DragonFly does not have aout.  When/if they implement a new
+  # versioning mechanism, adjust this.
+  if test -x /usr/bin/objformat; then
+    objformat=`/usr/bin/objformat`
+  else
+    case $host_os in
+    freebsd[[123]]*) objformat=aout ;;
+    *) objformat=elf ;;
+    esac
+  fi
+  version_type=freebsd-$objformat
+  case $version_type in
+    freebsd-elf*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+      need_version=no
+      need_lib_prefix=no
+      ;;
+    freebsd-*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+      need_version=yes
+      ;;
+  esac
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_os in
+  freebsd2*)
+    shlibpath_overrides_runpath=yes
+    ;;
+  freebsd3.[[01]]* | freebsdelf3.[[01]]*)
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \
+  freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1)
+    shlibpath_overrides_runpath=no
+    hardcode_into_libs=yes
+    ;;
+  *) # from 4.6 on, and DragonFly
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  esac
+  ;;
+
+gnu*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  hardcode_into_libs=yes
+  ;;
+
+hpux9* | hpux10* | hpux11*)
+  # Give a soname corresponding to the major version so that dld.sl refuses to
+  # link against other versions.
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  case $host_cpu in
+  ia64*)
+    shrext_cmds='.so'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.so"
+    shlibpath_var=LD_LIBRARY_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    if test "X$HPUX_IA64_MODE" = X32; then
+      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+    else
+      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+    fi
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  hppa*64*)
+    shrext_cmds='.sl'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  *)
+    shrext_cmds='.sl'
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=SHLIB_PATH
+    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    ;;
+  esac
+  # HP-UX runs *really* slowly unless shared libraries are mode 555.
+  postinstall_cmds='chmod 555 $lib'
+  ;;
+
+interix[[3-9]]*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+irix5* | irix6* | nonstopux*)
+  case $host_os in
+    nonstopux*) version_type=nonstopux ;;
+    *)
+	if test "$lt_cv_prog_gnu_ld" = yes; then
+		version_type=linux
+	else
+		version_type=irix
+	fi ;;
+  esac
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+  case $host_os in
+  irix5* | nonstopux*)
+    libsuff= shlibsuff=
+    ;;
+  *)
+    case $LD in # libtool.m4 will add one of these switches to LD
+    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+      libsuff= shlibsuff= libmagic=32-bit;;
+    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+      libsuff=32 shlibsuff=N32 libmagic=N32;;
+    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+      libsuff=64 shlibsuff=64 libmagic=64-bit;;
+    *) libsuff= shlibsuff= libmagic=never-match;;
+    esac
+    ;;
+  esac
+  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+  shlibpath_overrides_runpath=no
+  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+  hardcode_into_libs=yes
+  ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+  dynamic_linker=no
+  ;;
+
+# This must be Linux ELF.
+linux* | k*bsd*-gnu)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  # Some binutils ld are patched to set DT_RUNPATH
+  save_LDFLAGS=$LDFLAGS
+  save_libdir=$libdir
+  eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \
+       LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\""
+  AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+    [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null],
+       [shlibpath_overrides_runpath=yes])])
+  LDFLAGS=$save_LDFLAGS
+  libdir=$save_libdir
+
+  # This implies no fast_install, which is unacceptable.
+  # Some rework will be needed to allow for fast_install
+  # before this can be enabled.
+  hardcode_into_libs=yes
+
+  # Append ld.so.conf contents to the search path
+  if test -f /etc/ld.so.conf; then
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
+  fi
+
+  # We used to test for /lib/ld.so.1 and disable shared libraries on
+  # powerpc, because MkLinux only supported shared libraries with the
+  # GNU dynamic linker.  Since this was broken with cross compilers,
+  # most powerpc-linux boxes support dynamic linking these days and
+  # people can always --disable-shared, the test was removed, and we
+  # assume the GNU/Linux dynamic linker is in use.
+  dynamic_linker='GNU/Linux ld.so'
+  ;;
+
+netbsd*)
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+    dynamic_linker='NetBSD (a.out) ld.so'
+  else
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    dynamic_linker='NetBSD ld.elf_so'
+  fi
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  ;;
+
+newsos6)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  ;;
+
+*nto* | *qnx*)
+  version_type=qnx
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='ldqnx.so'
+  ;;
+
+openbsd*)
+  version_type=sunos
+  sys_lib_dlsearch_path_spec="/usr/lib"
+  need_lib_prefix=no
+  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+  case $host_os in
+    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
+    *)				need_version=no  ;;
+  esac
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    case $host_os in
+      openbsd2.[[89]] | openbsd2.[[89]].*)
+	shlibpath_overrides_runpath=no
+	;;
+      *)
+	shlibpath_overrides_runpath=yes
+	;;
+      esac
+  else
+    shlibpath_overrides_runpath=yes
+  fi
+  ;;
+
+os2*)
+  libname_spec='$name'
+  shrext_cmds=".dll"
+  need_lib_prefix=no
+  library_names_spec='$libname${shared_ext} $libname.a'
+  dynamic_linker='OS/2 ld.exe'
+  shlibpath_var=LIBPATH
+  ;;
+
+osf3* | osf4* | osf5*)
+  version_type=osf
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+  ;;
+
+rdos*)
+  dynamic_linker=no
+  ;;
+
+solaris*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  # ldd complains unless libraries are executable
+  postinstall_cmds='chmod +x $lib'
+  ;;
+
+sunos4*)
+  version_type=sunos
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  if test "$with_gnu_ld" = yes; then
+    need_lib_prefix=no
+  fi
+  need_version=yes
+  ;;
+
+sysv4 | sysv4.3*)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_vendor in
+    sni)
+      shlibpath_overrides_runpath=no
+      need_lib_prefix=no
+      runpath_var=LD_RUN_PATH
+      ;;
+    siemens)
+      need_lib_prefix=no
+      ;;
+    motorola)
+      need_lib_prefix=no
+      need_version=no
+      shlibpath_overrides_runpath=no
+      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+      ;;
+  esac
+  ;;
+
+sysv4*MP*)
+  if test -d /usr/nec ;then
+    version_type=linux
+    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+    soname_spec='$libname${shared_ext}.$major'
+    shlibpath_var=LD_LIBRARY_PATH
+  fi
+  ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  version_type=freebsd-elf
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  if test "$with_gnu_ld" = yes; then
+    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+  else
+    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+    case $host_os in
+      sco3.2v5*)
+        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+	;;
+    esac
+  fi
+  sys_lib_dlsearch_path_spec='/usr/lib'
+  ;;
+
+tpf*)
+  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+uts4*)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+*)
+  dynamic_linker=no
+  ;;
+esac
+AC_MSG_RESULT([$dynamic_linker])
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
+if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
+  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
+fi
+if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
+  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
+fi
+
+_LT_DECL([], [variables_saved_for_relink], [1],
+    [Variables whose values should be saved in libtool wrapper scripts and
+    restored at link time])
+_LT_DECL([], [need_lib_prefix], [0],
+    [Do we need the "lib" prefix for modules?])
+_LT_DECL([], [need_version], [0], [Do we need a version for libraries?])
+_LT_DECL([], [version_type], [0], [Library versioning type])
+_LT_DECL([], [runpath_var], [0],  [Shared library runtime path variable])
+_LT_DECL([], [shlibpath_var], [0],[Shared library path variable])
+_LT_DECL([], [shlibpath_overrides_runpath], [0],
+    [Is shlibpath searched before the hard-coded library search path?])
+_LT_DECL([], [libname_spec], [1], [Format of library name prefix])
+_LT_DECL([], [library_names_spec], [1],
+    [[List of archive names.  First name is the real one, the rest are links.
+    The last name is the one that the linker finds with -lNAME]])
+_LT_DECL([], [soname_spec], [1],
+    [[The coded name of the library, if different from the real name]])
+_LT_DECL([], [postinstall_cmds], [2],
+    [Command to use after installation of a shared archive])
+_LT_DECL([], [postuninstall_cmds], [2],
+    [Command to use after uninstallation of a shared archive])
+_LT_DECL([], [finish_cmds], [2],
+    [Commands used to finish a libtool library installation in a directory])
+_LT_DECL([], [finish_eval], [1],
+    [[As "finish_cmds", except a single script fragment to be evaled but
+    not shown]])
+_LT_DECL([], [hardcode_into_libs], [0],
+    [Whether we should hardcode library paths into libraries])
+_LT_DECL([], [sys_lib_search_path_spec], [2],
+    [Compile-time system search path for libraries])
+_LT_DECL([], [sys_lib_dlsearch_path_spec], [2],
+    [Run-time system search path for libraries])
+])# _LT_SYS_DYNAMIC_LINKER
+
+
+# _LT_PATH_TOOL_PREFIX(TOOL)
+# --------------------------
+# find a file program which can recognize shared library
+AC_DEFUN([_LT_PATH_TOOL_PREFIX],
+[m4_require([_LT_DECL_EGREP])dnl
+AC_MSG_CHECKING([for $1])
+AC_CACHE_VAL(lt_cv_path_MAGIC_CMD,
+[case $MAGIC_CMD in
+[[\\/*] |  ?:[\\/]*])
+  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+  ;;
+*)
+  lt_save_MAGIC_CMD="$MAGIC_CMD"
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+dnl $ac_dummy forces splitting on constant user-supplied paths.
+dnl POSIX.2 word splitting is done only on the output of word expansions,
+dnl not every word.  This closes a longstanding sh security hole.
+  ac_dummy="m4_if([$2], , $PATH, [$2])"
+  for ac_dir in $ac_dummy; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f $ac_dir/$1; then
+      lt_cv_path_MAGIC_CMD="$ac_dir/$1"
+      if test -n "$file_magic_test_file"; then
+	case $deplibs_check_method in
+	"file_magic "*)
+	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
+	    $EGREP "$file_magic_regex" > /dev/null; then
+	    :
+	  else
+	    cat <<_LT_EOF 1>&2
+
+*** Warning: the command libtool uses to detect shared libraries,
+*** $file_magic_cmd, produces output that libtool cannot recognize.
+*** The result is that libtool may fail to recognize shared libraries
+*** as such.  This will affect the creation of libtool libraries that
+*** depend on shared libraries, but programs linked with such libtool
+*** libraries will work regardless of this problem.  Nevertheless, you
+*** may want to report the problem to your system manager and/or to
+*** bug-libtool@gnu.org
+
+_LT_EOF
+	  fi ;;
+	esac
+      fi
+      break
+    fi
+  done
+  IFS="$lt_save_ifs"
+  MAGIC_CMD="$lt_save_MAGIC_CMD"
+  ;;
+esac])
+MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+if test -n "$MAGIC_CMD"; then
+  AC_MSG_RESULT($MAGIC_CMD)
+else
+  AC_MSG_RESULT(no)
+fi
+_LT_DECL([], [MAGIC_CMD], [0],
+	 [Used to examine libraries when file_magic_cmd begins with "file"])dnl
+])# _LT_PATH_TOOL_PREFIX
+
+# Old name:
+AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], [])
+
+
+# _LT_PATH_MAGIC
+# --------------
+# find a file program which can recognize a shared library
+m4_defun([_LT_PATH_MAGIC],
+[_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH)
+if test -z "$lt_cv_path_MAGIC_CMD"; then
+  if test -n "$ac_tool_prefix"; then
+    _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH)
+  else
+    MAGIC_CMD=:
+  fi
+fi
+])# _LT_PATH_MAGIC
+
+
+# LT_PATH_LD
+# ----------
+# find the pathname to the GNU or non-GNU linker
+AC_DEFUN([LT_PATH_LD],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_DECL_EGREP])dnl
+
+AC_ARG_WITH([gnu-ld],
+    [AS_HELP_STRING([--with-gnu-ld],
+	[assume the C compiler uses GNU ld @<:@default=no@:>@])],
+    [test "$withval" = no || with_gnu_ld=yes],
+    [with_gnu_ld=no])dnl
+
+ac_prog=ld
+if test "$GCC" = yes; then
+  # Check if gcc -print-prog-name=ld gives a path.
+  AC_MSG_CHECKING([for ld used by $CC])
+  case $host in
+  *-*-mingw*)
+    # gcc leaves a trailing carriage return which upsets mingw
+    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+  *)
+    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+  esac
+  case $ac_prog in
+    # Accept absolute paths.
+    [[\\/]]* | ?:[[\\/]]*)
+      re_direlt='/[[^/]][[^/]]*/\.\./'
+      # Canonicalize the pathname of ld
+      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
+      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
+	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
+      done
+      test -z "$LD" && LD="$ac_prog"
+      ;;
+  "")
+    # If it fails, then pretend we aren't using GCC.
+    ac_prog=ld
+    ;;
+  *)
+    # If it is relative, then search for the first ld in PATH.
+    with_gnu_ld=unknown
+    ;;
+  esac
+elif test "$with_gnu_ld" = yes; then
+  AC_MSG_CHECKING([for GNU ld])
+else
+  AC_MSG_CHECKING([for non-GNU ld])
+fi
+AC_CACHE_VAL(lt_cv_path_LD,
+[if test -z "$LD"; then
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  for ac_dir in $PATH; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+      lt_cv_path_LD="$ac_dir/$ac_prog"
+      # Check to see if the program is GNU ld.  I'd rather use --version,
+      # but apparently some variants of GNU ld only accept -v.
+      # Break only if it was the GNU/non-GNU ld that we prefer.
+      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
+      *GNU* | *'with BFD'*)
+	test "$with_gnu_ld" != no && break
+	;;
+      *)
+	test "$with_gnu_ld" != yes && break
+	;;
+      esac
+    fi
+  done
+  IFS="$lt_save_ifs"
+else
+  lt_cv_path_LD="$LD" # Let the user override the test with a path.
+fi])
+LD="$lt_cv_path_LD"
+if test -n "$LD"; then
+  AC_MSG_RESULT($LD)
+else
+  AC_MSG_RESULT(no)
+fi
+test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
+_LT_PATH_LD_GNU
+AC_SUBST([LD])
+
+_LT_TAGDECL([], [LD], [1], [The linker used to build libraries])
+])# LT_PATH_LD
+
+# Old names:
+AU_ALIAS([AM_PROG_LD], [LT_PATH_LD])
+AU_ALIAS([AC_PROG_LD], [LT_PATH_LD])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_PROG_LD], [])
+dnl AC_DEFUN([AC_PROG_LD], [])
+
+
+# _LT_PATH_LD_GNU
+#- --------------
+m4_defun([_LT_PATH_LD_GNU],
+[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], lt_cv_prog_gnu_ld,
+[# I'd rather use --version here, but apparently some GNU lds only accept -v.
+case `$LD -v 2>&1 </dev/null` in
+*GNU* | *'with BFD'*)
+  lt_cv_prog_gnu_ld=yes
+  ;;
+*)
+  lt_cv_prog_gnu_ld=no
+  ;;
+esac])
+with_gnu_ld=$lt_cv_prog_gnu_ld
+])# _LT_PATH_LD_GNU
+
+
+# _LT_CMD_RELOAD
+# --------------
+# find reload flag for linker
+#   -- PORTME Some linkers may need a different reload flag.
+m4_defun([_LT_CMD_RELOAD],
+[AC_CACHE_CHECK([for $LD option to reload object files],
+  lt_cv_ld_reload_flag,
+  [lt_cv_ld_reload_flag='-r'])
+reload_flag=$lt_cv_ld_reload_flag
+case $reload_flag in
+"" | " "*) ;;
+*) reload_flag=" $reload_flag" ;;
+esac
+reload_cmds='$LD$reload_flag -o $output$reload_objs'
+case $host_os in
+  darwin*)
+    if test "$GCC" = yes; then
+      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
+    else
+      reload_cmds='$LD$reload_flag -o $output$reload_objs'
+    fi
+    ;;
+esac
+_LT_DECL([], [reload_flag], [1], [How to create reloadable object files])dnl
+_LT_DECL([], [reload_cmds], [2])dnl
+])# _LT_CMD_RELOAD
+
+
+# _LT_CHECK_MAGIC_METHOD
+# ----------------------
+# how to check for library dependencies
+#  -- PORTME fill in with the dynamic library characteristics
+m4_defun([_LT_CHECK_MAGIC_METHOD],
+[m4_require([_LT_DECL_EGREP])
+m4_require([_LT_DECL_OBJDUMP])
+AC_CACHE_CHECK([how to recognize dependent libraries],
+lt_cv_deplibs_check_method,
+[lt_cv_file_magic_cmd='$MAGIC_CMD'
+lt_cv_file_magic_test_file=
+lt_cv_deplibs_check_method='unknown'
+# Need to set the preceding variable on all platforms that support
+# interlibrary dependencies.
+# 'none' -- dependencies not supported.
+# `unknown' -- same as none, but documents that we really don't know.
+# 'pass_all' -- all dependencies passed with no checks.
+# 'test_compile' -- check by making test program.
+# 'file_magic [[regex]]' -- check by looking for files in library path
+# which responds to the $file_magic_cmd with a given extended regex.
+# If you have `file' or equivalent on your system and you're not sure
+# whether `pass_all' will *always* work, you probably want this one.
+
+case $host_os in
+aix[[4-9]]*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+beos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+bsdi[[45]]*)
+  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)'
+  lt_cv_file_magic_cmd='/usr/bin/file -L'
+  lt_cv_file_magic_test_file=/shlib/libc.so
+  ;;
+
+cygwin*)
+  # func_win32_libid is a shell function defined in ltmain.sh
+  lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+  lt_cv_file_magic_cmd='func_win32_libid'
+  ;;
+
+mingw* | pw32*)
+  # Base MSYS/MinGW do not provide the 'file' command needed by
+  # func_win32_libid shell function, so use a weaker test based on 'objdump',
+  # unless we find 'file', for example because we are cross-compiling.
+  if ( file / ) >/dev/null 2>&1; then
+    lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+    lt_cv_file_magic_cmd='func_win32_libid'
+  else
+    lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?'
+    lt_cv_file_magic_cmd='$OBJDUMP -f'
+  fi
+  ;;
+
+cegcc)
+  # use the weaker test based on 'objdump'. See mingw*.
+  lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
+  lt_cv_file_magic_cmd='$OBJDUMP -f'
+  ;;
+
+darwin* | rhapsody*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+freebsd* | dragonfly*)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    case $host_cpu in
+    i*86 )
+      # Not sure whether the presence of OpenBSD here was a mistake.
+      # Let's accept both of them until this is cleared up.
+      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library'
+      lt_cv_file_magic_cmd=/usr/bin/file
+      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
+      ;;
+    esac
+  else
+    lt_cv_deplibs_check_method=pass_all
+  fi
+  ;;
+
+gnu*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+hpux10.20* | hpux11*)
+  lt_cv_file_magic_cmd=/usr/bin/file
+  case $host_cpu in
+  ia64*)
+    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64'
+    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
+    ;;
+  hppa*64*)
+    [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]']
+    lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
+    ;;
+  *)
+    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]].[[0-9]]) shared library'
+    lt_cv_file_magic_test_file=/usr/lib/libc.sl
+    ;;
+  esac
+  ;;
+
+interix[[3-9]]*)
+  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
+  lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$'
+  ;;
+
+irix5* | irix6* | nonstopux*)
+  case $LD in
+  *-32|*"-32 ") libmagic=32-bit;;
+  *-n32|*"-n32 ") libmagic=N32;;
+  *-64|*"-64 ") libmagic=64-bit;;
+  *) libmagic=never-match;;
+  esac
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+# This must be Linux ELF.
+linux* | k*bsd*-gnu)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+netbsd*)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+  else
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$'
+  fi
+  ;;
+
+newos6*)
+  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)'
+  lt_cv_file_magic_cmd=/usr/bin/file
+  lt_cv_file_magic_test_file=/usr/lib/libnls.so
+  ;;
+
+*nto* | *qnx*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+openbsd*)
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$'
+  else
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+  fi
+  ;;
+
+osf3* | osf4* | osf5*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+rdos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+solaris*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+sysv4 | sysv4.3*)
+  case $host_vendor in
+  motorola)
+    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]'
+    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
+    ;;
+  ncr)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  sequent)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )'
+    ;;
+  sni)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib"
+    lt_cv_file_magic_test_file=/lib/libc.so
+    ;;
+  siemens)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  pc)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  esac
+  ;;
+
+tpf*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+esac
+])
+file_magic_cmd=$lt_cv_file_magic_cmd
+deplibs_check_method=$lt_cv_deplibs_check_method
+test -z "$deplibs_check_method" && deplibs_check_method=unknown
+
+_LT_DECL([], [deplibs_check_method], [1],
+    [Method to check whether dependent libraries are shared objects])
+_LT_DECL([], [file_magic_cmd], [1],
+    [Command to use when deplibs_check_method == "file_magic"])
+])# _LT_CHECK_MAGIC_METHOD
+
+
+# LT_PATH_NM
+# ----------
+# find the pathname to a BSD- or MS-compatible name lister
+AC_DEFUN([LT_PATH_NM],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM,
+[if test -n "$NM"; then
+  # Let the user override the test.
+  lt_cv_path_NM="$NM"
+else
+  lt_nm_to_check="${ac_tool_prefix}nm"
+  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
+    lt_nm_to_check="$lt_nm_to_check nm"
+  fi
+  for lt_tmp_nm in $lt_nm_to_check; do
+    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
+      IFS="$lt_save_ifs"
+      test -z "$ac_dir" && ac_dir=.
+      tmp_nm="$ac_dir/$lt_tmp_nm"
+      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+	# Check to see if the nm accepts a BSD-compat flag.
+	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
+	#   nm: unknown option "B" ignored
+	# Tru64's nm complains that /dev/null is an invalid object file
+	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
+	*/dev/null* | *'Invalid file or object type'*)
+	  lt_cv_path_NM="$tmp_nm -B"
+	  break
+	  ;;
+	*)
+	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
+	  */dev/null*)
+	    lt_cv_path_NM="$tmp_nm -p"
+	    break
+	    ;;
+	  *)
+	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
+	    continue # so that we can try to find one that supports BSD flags
+	    ;;
+	  esac
+	  ;;
+	esac
+      fi
+    done
+    IFS="$lt_save_ifs"
+  done
+  : ${lt_cv_path_NM=no}
+fi])
+if test "$lt_cv_path_NM" != "no"; then
+  NM="$lt_cv_path_NM"
+else
+  # Didn't find any BSD compatible name lister, look for dumpbin.
+  AC_CHECK_TOOLS(DUMPBIN, ["dumpbin -symbols" "link -dump -symbols"], :)
+  AC_SUBST([DUMPBIN])
+  if test "$DUMPBIN" != ":"; then
+    NM="$DUMPBIN"
+  fi
+fi
+test -z "$NM" && NM=nm
+AC_SUBST([NM])
+_LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl
+
+AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface],
+  [lt_cv_nm_interface="BSD nm"
+  echo "int some_variable = 0;" > conftest.$ac_ext
+  (eval echo "\"\$as_me:__oline__: $ac_compile\"" >&AS_MESSAGE_LOG_FD)
+  (eval "$ac_compile" 2>conftest.err)
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  (eval echo "\"\$as_me:__oline__: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD)
+  (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  (eval echo "\"\$as_me:__oline__: output\"" >&AS_MESSAGE_LOG_FD)
+  cat conftest.out >&AS_MESSAGE_LOG_FD
+  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
+    lt_cv_nm_interface="MS dumpbin"
+  fi
+  rm -f conftest*])
+])# LT_PATH_NM
+
+# Old names:
+AU_ALIAS([AM_PROG_NM], [LT_PATH_NM])
+AU_ALIAS([AC_PROG_NM], [LT_PATH_NM])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_PROG_NM], [])
+dnl AC_DEFUN([AC_PROG_NM], [])
+
+
+# LT_LIB_M
+# --------
+# check for math library
+AC_DEFUN([LT_LIB_M],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+LIBM=
+case $host in
+*-*-beos* | *-*-cygwin* | *-*-pw32* | *-*-darwin*)
+  # These system don't have libm, or don't need it
+  ;;
+*-ncr-sysv4.3*)
+  AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw")
+  AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm")
+  ;;
+*)
+  AC_CHECK_LIB(m, cos, LIBM="-lm")
+  ;;
+esac
+AC_SUBST([LIBM])
+])# LT_LIB_M
+
+# Old name:
+AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_CHECK_LIBM], [])
+
+
+# _LT_COMPILER_NO_RTTI([TAGNAME])
+# -------------------------------
+m4_defun([_LT_COMPILER_NO_RTTI],
+[m4_require([_LT_TAG_COMPILER])dnl
+
+_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+
+if test "$GCC" = yes; then
+  _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
+
+  _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions],
+    lt_cv_prog_compiler_rtti_exceptions,
+    [-fno-rtti -fno-exceptions], [],
+    [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"])
+fi
+_LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1],
+	[Compiler flag to turn off builtin functions])
+])# _LT_COMPILER_NO_RTTI
+
+
+# _LT_CMD_GLOBAL_SYMBOLS
+# ----------------------
+m4_defun([_LT_CMD_GLOBAL_SYMBOLS],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+AC_REQUIRE([LT_PATH_LD])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+
+# Check for command to grab the raw symbol name followed by C symbol from nm.
+AC_MSG_CHECKING([command to parse $NM output from $compiler object])
+AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe],
+[
+# These are sane defaults that work on at least a few old systems.
+# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
+
+# Character class describing NM global symbol codes.
+symcode='[[BCDEGRST]]'
+
+# Regexp to match symbols that can be accessed directly from C.
+sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)'
+
+# Define system-specific variables.
+case $host_os in
+aix*)
+  symcode='[[BCDT]]'
+  ;;
+cygwin* | mingw* | pw32* | cegcc*)
+  symcode='[[ABCDGISTW]]'
+  ;;
+hpux*)
+  if test "$host_cpu" = ia64; then
+    symcode='[[ABCDEGRST]]'
+  fi
+  ;;
+irix* | nonstopux*)
+  symcode='[[BCDEGRST]]'
+  ;;
+osf*)
+  symcode='[[BCDEGQRST]]'
+  ;;
+solaris*)
+  symcode='[[BDRT]]'
+  ;;
+sco3.2v5*)
+  symcode='[[DT]]'
+  ;;
+sysv4.2uw2*)
+  symcode='[[DT]]'
+  ;;
+sysv5* | sco5v6* | unixware* | OpenUNIX*)
+  symcode='[[ABDT]]'
+  ;;
+sysv4)
+  symcode='[[DFNSTU]]'
+  ;;
+esac
+
+# If we're using GNU nm, then use its standard symbol codes.
+case `$NM -V 2>&1` in
+*GNU* | *'with BFD'*)
+  symcode='[[ABCDGIRSTW]]' ;;
+esac
+
+# Transform an extracted symbol line into a proper C declaration.
+# Some systems (esp. on ia64) link data and code symbols differently,
+# so use this general approach.
+lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+
+# Transform an extracted symbol line into symbol name and symbol address
+lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p'"
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\) $/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"lib\2\", (void *) \&\2},/p'"
+
+# Handle CRLF in mingw tool chain
+opt_cr=
+case $build_os in
+mingw*)
+  opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp
+  ;;
+esac
+
+# Try without a prefix underscore, then with it.
+for ac_symprfx in "" "_"; do
+
+  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
+  symxfrm="\\1 $ac_symprfx\\2 \\2"
+
+  # Write the raw and C identifiers.
+  if test "$lt_cv_nm_interface" = "MS dumpbin"; then
+    # Fake it for dumpbin and say T for any non-static function
+    # and D for any global variable.
+    # Also find C++ and __fastcall symbols from MSVC++,
+    # which start with @ or ?.
+    lt_cv_sys_global_symbol_pipe="$AWK ['"\
+"     {last_section=section; section=\$ 3};"\
+"     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
+"     \$ 0!~/External *\|/{next};"\
+"     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
+"     {if(hide[section]) next};"\
+"     {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\
+"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
+"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
+"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\
+"     ' prfx=^$ac_symprfx]"
+  else
+    lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[	 ]]\($symcode$symcode*\)[[	 ]][[	 ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
+  fi
+
+  # Check to see that the pipe works correctly.
+  pipe_works=no
+
+  rm -f conftest*
+  cat > conftest.$ac_ext <<_LT_EOF
+#ifdef __cplusplus
+extern "C" {
+#endif
+char nm_test_var;
+void nm_test_func(void);
+void nm_test_func(void){}
+#ifdef __cplusplus
+}
+#endif
+int main(){nm_test_var='a';nm_test_func();return(0);}
+_LT_EOF
+
+  if AC_TRY_EVAL(ac_compile); then
+    # Now try to grab the symbols.
+    nlist=conftest.nm
+    if AC_TRY_EVAL(NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) && test -s "$nlist"; then
+      # Try sorting and uniquifying the output.
+      if sort "$nlist" | uniq > "$nlist"T; then
+	mv -f "$nlist"T "$nlist"
+      else
+	rm -f "$nlist"T
+      fi
+
+      # Make sure that we snagged all the symbols we need.
+      if $GREP ' nm_test_var$' "$nlist" >/dev/null; then
+	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
+	  cat <<_LT_EOF > conftest.$ac_ext
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+_LT_EOF
+	  # Now generate the symbol file.
+	  eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext'
+
+	  cat <<_LT_EOF >> conftest.$ac_ext
+
+/* The mapping between symbol names and symbols.  */
+const struct {
+  const char *name;
+  void       *address;
+}
+lt__PROGRAM__LTX_preloaded_symbols[[]] =
+{
+  { "@PROGRAM@", (void *) 0 },
+_LT_EOF
+	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
+	  cat <<\_LT_EOF >> conftest.$ac_ext
+  {0, (void *) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+  return lt__PROGRAM__LTX_preloaded_symbols;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+_LT_EOF
+	  # Now try linking the two files.
+	  mv conftest.$ac_objext conftstm.$ac_objext
+	  lt_save_LIBS="$LIBS"
+	  lt_save_CFLAGS="$CFLAGS"
+	  LIBS="conftstm.$ac_objext"
+	  CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
+	  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then
+	    pipe_works=yes
+	  fi
+	  LIBS="$lt_save_LIBS"
+	  CFLAGS="$lt_save_CFLAGS"
+	else
+	  echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD
+	fi
+      else
+	echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD
+      fi
+    else
+      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
+    fi
+  else
+    echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD
+    cat conftest.$ac_ext >&5
+  fi
+  rm -rf conftest* conftst*
+
+  # Do not use the global_symbol_pipe unless it works.
+  if test "$pipe_works" = yes; then
+    break
+  else
+    lt_cv_sys_global_symbol_pipe=
+  fi
+done
+])
+if test -z "$lt_cv_sys_global_symbol_pipe"; then
+  lt_cv_sys_global_symbol_to_cdecl=
+fi
+if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
+  AC_MSG_RESULT(failed)
+else
+  AC_MSG_RESULT(ok)
+fi
+
+_LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1],
+    [Take the output of nm and produce a listing of raw symbols and C names])
+_LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1],
+    [Transform the output of nm in a proper C declaration])
+_LT_DECL([global_symbol_to_c_name_address],
+    [lt_cv_sys_global_symbol_to_c_name_address], [1],
+    [Transform the output of nm in a C name address pair])
+_LT_DECL([global_symbol_to_c_name_address_lib_prefix],
+    [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1],
+    [Transform the output of nm in a C name address pair when lib prefix is needed])
+]) # _LT_CMD_GLOBAL_SYMBOLS
+
+
+# _LT_COMPILER_PIC([TAGNAME])
+# ---------------------------
+m4_defun([_LT_COMPILER_PIC],
+[m4_require([_LT_TAG_COMPILER])dnl
+_LT_TAGVAR(lt_prog_compiler_wl, $1)=
+_LT_TAGVAR(lt_prog_compiler_pic, $1)=
+_LT_TAGVAR(lt_prog_compiler_static, $1)=
+
+AC_MSG_CHECKING([for $compiler option to produce PIC])
+m4_if([$1], [CXX], [
+  # C++ specific cases for pic, static, wl, etc.
+  if test "$GXX" = yes; then
+    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+    case $host_os in
+    aix*)
+      # All AIX code is PIC.
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+        ;;
+      m68k)
+            # FIXME: we need at least 68020 code to build shared libraries, but
+            # adding the `-m68020' flag to GCC prevents building anything better,
+            # like `-m68040'.
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+        ;;
+      esac
+      ;;
+
+    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      # PIC is the default for these OSes.
+      ;;
+    mingw* | cygwin* | os2* | pw32* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      # Although the cygwin gcc ignores -fPIC, still need this for old-style
+      # (--disable-auto-import) libraries
+      m4_if([$1], [GCJ], [],
+	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+      ;;
+    *djgpp*)
+      # DJGPP does not support shared libraries at all
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+      ;;
+    interix[[3-9]]*)
+      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+      # Instead, we relocate shared libraries at runtime.
+      ;;
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+      fi
+      ;;
+    hpux*)
+      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
+      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
+      # sets the default TLS model and affects inlining.
+      case $host_cpu in
+      hppa*64*)
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	;;
+      esac
+      ;;
+    *qnx* | *nto*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+    *)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+      ;;
+    esac
+  else
+    case $host_os in
+      aix[[4-9]]*)
+	# All AIX code is PIC.
+	if test "$host_cpu" = ia64; then
+	  # AIX 5 now supports IA64 processor
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	else
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+	fi
+	;;
+      chorus*)
+	case $cc_basename in
+	cxch68*)
+	  # Green Hills C++ Compiler
+	  # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
+	  ;;
+	esac
+	;;
+      dgux*)
+	case $cc_basename in
+	  ec++*)
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    ;;
+	  ghcx*)
+	    # Green Hills C++ Compiler
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      freebsd* | dragonfly*)
+	# FreeBSD uses GNU C++
+	;;
+      hpux9* | hpux10* | hpux11*)
+	case $cc_basename in
+	  CC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+	    if test "$host_cpu" != ia64; then
+	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+	    fi
+	    ;;
+	  aCC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+	    case $host_cpu in
+	    hppa*64*|ia64*)
+	      # +Z the default
+	      ;;
+	    *)
+	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+	      ;;
+	    esac
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      interix*)
+	# This is c89, which is MS Visual C++ (no shared libs)
+	# Anyone wants to do a port?
+	;;
+      irix5* | irix6* | nonstopux*)
+	case $cc_basename in
+	  CC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+	    # CC pic flag -KPIC is the default.
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      linux* | k*bsd*-gnu)
+	case $cc_basename in
+	  KCC*)
+	    # KAI C++ Compiler
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	    ;;
+	  ecpc* )
+	    # old Intel C++ for x86_64 which still supported -KPIC.
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+	    ;;
+	  icpc* )
+	    # Intel C++, used to be incompatible with GCC.
+	    # ICC 10 doesn't accept -KPIC any more.
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+	    ;;
+	  pgCC* | pgcpp*)
+	    # Portland Group C++ compiler
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    ;;
+	  cxx*)
+	    # Compaq C++
+	    # Make sure the PIC flag is empty.  It appears that all Alpha
+	    # Linux and Compaq Tru64 Unix objects are PIC.
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+	    ;;
+	  xlc* | xlC*)
+	    # IBM XL 8.0 on PPC
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
+	    ;;
+	  *)
+	    case `$CC -V 2>&1 | sed 5q` in
+	    *Sun\ C*)
+	      # Sun C++ 5.9
+	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+	      ;;
+	    esac
+	    ;;
+	esac
+	;;
+      lynxos*)
+	;;
+      m88k*)
+	;;
+      mvs*)
+	case $cc_basename in
+	  cxx*)
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      netbsd*)
+	;;
+      *qnx* | *nto*)
+        # QNX uses GNU C++, but need to define -shared option too, otherwise
+        # it will coredump.
+        _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+        ;;
+      osf3* | osf4* | osf5*)
+	case $cc_basename in
+	  KCC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+	    ;;
+	  RCC*)
+	    # Rational C++ 2.4.1
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    ;;
+	  cxx*)
+	    # Digital/Compaq C++
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    # Make sure the PIC flag is empty.  It appears that all Alpha
+	    # Linux and Compaq Tru64 Unix objects are PIC.
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      psos*)
+	;;
+      solaris*)
+	case $cc_basename in
+	  CC*)
+	    # Sun C++ 4.2, 5.x and Centerline C++
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+	    ;;
+	  gcx*)
+	    # Green Hills C++ Compiler
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      sunos4*)
+	case $cc_basename in
+	  CC*)
+	    # Sun C++ 4.x
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    ;;
+	  lcc*)
+	    # Lucid
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+	case $cc_basename in
+	  CC*)
+	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	    ;;
+	esac
+	;;
+      tandem*)
+	case $cc_basename in
+	  NCC*)
+	    # NonStop-UX NCC 3.20
+	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	    ;;
+	  *)
+	    ;;
+	esac
+	;;
+      vxworks*)
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+	;;
+    esac
+  fi
+],
+[
+  if test "$GCC" = yes; then
+    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+    case $host_os in
+      aix*)
+      # All AIX code is PIC.
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+        ;;
+      m68k)
+            # FIXME: we need at least 68020 code to build shared libraries, but
+            # adding the `-m68020' flag to GCC prevents building anything better,
+            # like `-m68040'.
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+        ;;
+      esac
+      ;;
+
+    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      # PIC is the default for these OSes.
+      ;;
+
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      # Although the cygwin gcc ignores -fPIC, still need this for old-style
+      # (--disable-auto-import) libraries
+      m4_if([$1], [GCJ], [],
+	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+      ;;
+
+    hpux*)
+      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
+      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
+      # sets the default TLS model and affects inlining.
+      case $host_cpu in
+      hppa*64*)
+	# +Z the default
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	;;
+      esac
+      ;;
+
+    interix[[3-9]]*)
+      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+      # Instead, we relocate shared libraries at runtime.
+      ;;
+
+    msdosdjgpp*)
+      # Just because we use GCC doesn't mean we suddenly get shared libraries
+      # on systems that don't support them.
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      enable_shared=no
+      ;;
+
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+      fi
+      ;;
+
+    *)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+      ;;
+    esac
+  else
+    # PORTME Check for flag to pass linker flags through the system compiler.
+    case $host_os in
+    aix*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      if test "$host_cpu" = ia64; then
+	# AIX 5 now supports IA64 processor
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      else
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+      fi
+      ;;
+
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      m4_if([$1], [GCJ], [],
+	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+
+    hpux9* | hpux10* | hpux11*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+      # not for PA HP-UX.
+      case $host_cpu in
+      hppa*64*|ia64*)
+	# +Z the default
+	;;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+	;;
+      esac
+      # Is there a better lt_prog_compiler_static that works with the bundled CC?
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+      ;;
+
+    irix5* | irix6* | nonstopux*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # PIC (with -KPIC) is the default.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    linux* | k*bsd*-gnu)
+      case $cc_basename in
+      # old Intel for x86_64 which still supported -KPIC.
+      ecc*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+        ;;
+      # icc used to be incompatible with GCC.
+      # ICC 10 doesn't accept -KPIC any more.
+      icc* | ifort*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+        ;;
+      # Lahey Fortran 8.1.
+      lf95*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='--static'
+	;;
+      pgcc* | pgf77* | pgf90* | pgf95*)
+        # Portland Group compilers (*not* the Pentium gcc compiler,
+	# which looks to be a dead project)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+        ;;
+      ccc*)
+        _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+        # All Alpha code is PIC.
+        _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+        ;;
+      xl*)
+	# IBM XL C 8.0/Fortran 10.1 on PPC
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
+	;;
+      *)
+	case `$CC -V 2>&1 | sed 5q` in
+	*Sun\ C*)
+	  # Sun C 5.9
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	  ;;
+	*Sun\ F*)
+	  # Sun Fortran 8.3 passes all unrecognized flags to the linker
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)=''
+	  ;;
+	esac
+	;;
+      esac
+      ;;
+
+    newsos6)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+
+    osf3* | osf4* | osf5*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # All OSF/1 code is PIC.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    rdos*)
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    solaris*)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      case $cc_basename in
+      f77* | f90* | f95*)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';;
+      *)
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';;
+      esac
+      ;;
+
+    sunos4*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    sysv4 | sysv4.2uw2* | sysv4.3*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec ;then
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    unicos*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      ;;
+
+    uts4*)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    *)
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      ;;
+    esac
+  fi
+])
+case $host_os in
+  # For platforms which do not support PIC, -DPIC is meaningless:
+  *djgpp*)
+    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+    ;;
+  *)
+    _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])"
+    ;;
+esac
+AC_MSG_RESULT([$_LT_TAGVAR(lt_prog_compiler_pic, $1)])
+_LT_TAGDECL([wl], [lt_prog_compiler_wl], [1],
+	[How to pass a linker flag through the compiler])
+
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
+  _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works],
+    [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)],
+    [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [],
+    [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in
+     "" | " "*) ;;
+     *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;;
+     esac],
+    [_LT_TAGVAR(lt_prog_compiler_pic, $1)=
+     _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no])
+fi
+_LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1],
+	[Additional compiler flags for building library objects])
+
+#
+# Check to make sure the static flag actually works.
+#
+wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\"
+_LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works],
+  _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1),
+  $lt_tmp_static_flag,
+  [],
+  [_LT_TAGVAR(lt_prog_compiler_static, $1)=])
+_LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1],
+	[Compiler flag to prevent dynamic linking])
+])# _LT_COMPILER_PIC
+
+
+# _LT_LINKER_SHLIBS([TAGNAME])
+# ----------------------------
+# See if the linker supports building shared libraries.
+m4_defun([_LT_LINKER_SHLIBS],
+[AC_REQUIRE([LT_PATH_LD])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+m4_if([$1], [CXX], [
+  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  case $host_os in
+  aix[[4-9]]*)
+    # If we're using GNU nm, then we don't want the "-C" option.
+    # -C means demangle to AIX nm, but means don't demangle with GNU nm
+    if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+    else
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+    fi
+    ;;
+  pw32*)
+    _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds"
+  ;;
+  cygwin* | mingw* | cegcc*)
+    _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;/^.*[[ ]]__nm__/s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
+  ;;
+  *)
+    _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  ;;
+  esac
+  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
+], [
+  runpath_var=
+  _LT_TAGVAR(allow_undefined_flag, $1)=
+  _LT_TAGVAR(always_export_symbols, $1)=no
+  _LT_TAGVAR(archive_cmds, $1)=
+  _LT_TAGVAR(archive_expsym_cmds, $1)=
+  _LT_TAGVAR(compiler_needs_object, $1)=no
+  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+  _LT_TAGVAR(export_dynamic_flag_spec, $1)=
+  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  _LT_TAGVAR(hardcode_automatic, $1)=no
+  _LT_TAGVAR(hardcode_direct, $1)=no
+  _LT_TAGVAR(hardcode_direct_absolute, $1)=no
+  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+  _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+  _LT_TAGVAR(hardcode_libdir_separator, $1)=
+  _LT_TAGVAR(hardcode_minus_L, $1)=no
+  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+  _LT_TAGVAR(inherit_rpath, $1)=no
+  _LT_TAGVAR(link_all_deplibs, $1)=unknown
+  _LT_TAGVAR(module_cmds, $1)=
+  _LT_TAGVAR(module_expsym_cmds, $1)=
+  _LT_TAGVAR(old_archive_from_new_cmds, $1)=
+  _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)=
+  _LT_TAGVAR(thread_safe_flag_spec, $1)=
+  _LT_TAGVAR(whole_archive_flag_spec, $1)=
+  # include_expsyms should be a list of space-separated symbols to be *always*
+  # included in the symbol list
+  _LT_TAGVAR(include_expsyms, $1)=
+  # exclude_expsyms can be an extended regexp of symbols to exclude
+  # it will be wrapped by ` (' and `)$', so one must not match beginning or
+  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
+  # as well as any symbol that contains `d'.
+  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
+  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
+  # platforms (ab)use it in PIC code, but their linkers get confused if
+  # the symbol is explicitly referenced.  Since portable code cannot
+  # rely on this symbol name, it's probably fine to never include it in
+  # preloaded symbol tables.
+  # Exclude shared library initialization/finalization symbols.
+dnl Note also adjust exclude_expsyms for C++ above.
+  extract_expsyms_cmds=
+
+  case $host_os in
+  cygwin* | mingw* | pw32* | cegcc*)
+    # FIXME: the MSVC++ port hasn't been tested in a loooong time
+    # When not using gcc, we currently assume that we are using
+    # Microsoft Visual C++.
+    if test "$GCC" != yes; then
+      with_gnu_ld=no
+    fi
+    ;;
+  interix*)
+    # we just hope/assume this is gcc and not c89 (= MSVC++)
+    with_gnu_ld=yes
+    ;;
+  openbsd*)
+    with_gnu_ld=no
+    ;;
+  esac
+
+  _LT_TAGVAR(ld_shlibs, $1)=yes
+  if test "$with_gnu_ld" = yes; then
+    # If archive_cmds runs LD, not CC, wlarc should be empty
+    wlarc='${wl}'
+
+    # Set some defaults for GNU ld with shared library support. These
+    # are reset later if shared libraries are not supported. Putting them
+    # here allows them to be overridden if necessary.
+    runpath_var=LD_RUN_PATH
+    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+    # ancient GNU ld didn't support --whole-archive et. al.
+    if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
+      _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+    else
+      _LT_TAGVAR(whole_archive_flag_spec, $1)=
+    fi
+    supports_anon_versioning=no
+    case `$LD -v 2>&1` in
+      *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
+      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+      *\ 2.11.*) ;; # other 2.11 versions
+      *) supports_anon_versioning=yes ;;
+    esac
+
+    # See if GNU ld supports shared libraries.
+    case $host_os in
+    aix[[3-9]]*)
+      # On AIX/PPC, the GNU linker is very broken
+      if test "$host_cpu" != ia64; then
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: the GNU linker, at least up to release 2.9.1, is reported
+*** to be unable to reliably create shared libraries on AIX.
+*** Therefore, libtool is disabling shared libraries support.  If you
+*** really care for shared libraries, you may want to modify your PATH
+*** so that a non-GNU linker is found, and then restart.
+
+_LT_EOF
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            _LT_TAGVAR(archive_expsym_cmds, $1)=''
+        ;;
+      m68k)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes
+        ;;
+      esac
+      ;;
+
+    beos*)
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	# Joseph Beckenbach <jrb3@best.com> says some releases of gcc
+	# support --undefined.  This deserves some investigation.  FIXME
+	_LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    cygwin* | mingw* | pw32* | cegcc*)
+      # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+      # as there is no search path for DLLs.
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(always_export_symbols, $1)=no
+      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols'
+
+      if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	# If the export-symbols file already is a .def file (1st line
+	# is EXPORTS), use it as is; otherwise, prepend...
+	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	  cp $export_symbols $output_objdir/$soname.def;
+	else
+	  echo EXPORTS > $output_objdir/$soname.def;
+	  cat $export_symbols >> $output_objdir/$soname.def;
+	fi~
+	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    interix[[3-9]]*)
+      _LT_TAGVAR(hardcode_direct, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+      # Instead, shared libraries are loaded at an image base (0x10000000 by
+      # default) and relocated if they conflict, which is a slow very memory
+      # consuming and fragmenting process.  To avoid this, we pick a random,
+      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      ;;
+
+    gnu* | linux* | tpf* | k*bsd*-gnu)
+      tmp_diet=no
+      if test "$host_os" = linux-dietlibc; then
+	case $cc_basename in
+	  diet\ *) tmp_diet=yes;;	# linux-dietlibc with static linking (!diet-dyn)
+	esac
+      fi
+      if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \
+	 && test "$tmp_diet" = no
+      then
+	tmp_addflag=
+	tmp_sharedflag='-shared'
+	case $cc_basename,$host_cpu in
+        pgcc*)				# Portland Group C compiler
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+	  tmp_addflag=' $pic_flag'
+	  ;;
+	pgf77* | pgf90* | pgf95*)	# Portland Group f77 and f90 compilers
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+	  tmp_addflag=' $pic_flag -Mnomain' ;;
+	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
+	  tmp_addflag=' -i_dynamic' ;;
+	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
+	  tmp_addflag=' -i_dynamic -nofor_main' ;;
+	ifc* | ifort*)			# Intel Fortran compiler
+	  tmp_addflag=' -nofor_main' ;;
+	lf95*)				# Lahey Fortran 8.1
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)=
+	  tmp_sharedflag='--shared' ;;
+	xl[[cC]]*)			# IBM XL C 8.0 on PPC (deal with xlf below)
+	  tmp_sharedflag='-qmkshrobj'
+	  tmp_addflag= ;;
+	esac
+	case `$CC -V 2>&1 | sed 5q` in
+	*Sun\ C*)			# Sun C 5.9
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(compiler_needs_object, $1)=yes
+	  tmp_sharedflag='-G' ;;
+	*Sun\ F*)			# Sun Fortran 8.3
+	  tmp_sharedflag='-G' ;;
+	esac
+	_LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+
+        if test "x$supports_anon_versioning" = xyes; then
+          _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+	    cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+	    echo "local: *; };" >> $output_objdir/$libname.ver~
+	    $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+        fi
+
+	case $cc_basename in
+	xlf*)
+	  # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+	  _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='-rpath $libdir'
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $compiler_flags -soname $soname -o $lib'
+	  if test "x$supports_anon_versioning" = xyes; then
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+	      cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+	      echo "local: *; };" >> $output_objdir/$libname.ver~
+	      $LD -shared $libobjs $deplibs $compiler_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
+	  fi
+	  ;;
+	esac
+      else
+        _LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    netbsd*)
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
+	wlarc=
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      fi
+      ;;
+
+    solaris*)
+      if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: The releases 2.8.* of the GNU linker cannot reliably
+*** create shared libraries on Solaris systems.  Therefore, libtool
+*** is disabling shared libraries support.  We urge you to upgrade GNU
+*** binutils to release 2.9.1 or newer.  Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+      elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
+      case `$LD -v 2>&1` in
+        *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*)
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	cat <<_LT_EOF 1>&2
+
+*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
+*** reliably create shared libraries on SCO systems.  Therefore, libtool
+*** is disabling shared libraries support.  We urge you to upgrade GNU
+*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+	;;
+	*)
+	  # For security reasons, it is highly recommended that you always
+	  # use absolute paths for naming shared libraries, and exclude the
+	  # DT_RUNPATH tag from executables and libraries.  But doing so
+	  # requires that you compile everything twice, which is a pain.
+	  if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	  else
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	  fi
+	;;
+      esac
+      ;;
+
+    sunos4*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      wlarc=
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *)
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+    esac
+
+    if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then
+      runpath_var=
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)=
+      _LT_TAGVAR(whole_archive_flag_spec, $1)=
+    fi
+  else
+    # PORTME fill in a description of your system's linker (not GNU ld)
+    case $host_os in
+    aix3*)
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(always_export_symbols, $1)=yes
+      _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
+      # Note: this linker hardcodes the directories in LIBPATH if there
+      # are no directories specified by -L.
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+	# Neither direct hardcoding nor static linking is supported with a
+	# broken collect2.
+	_LT_TAGVAR(hardcode_direct, $1)=unsupported
+      fi
+      ;;
+
+    aix[[4-9]]*)
+      if test "$host_cpu" = ia64; then
+	# On IA64, the linker does run time linking by default, so we don't
+	# have to do anything special.
+	aix_use_runtimelinking=no
+	exp_sym_flag='-Bexport'
+	no_entry_flag=""
+      else
+	# If we're using GNU nm, then we don't want the "-C" option.
+	# -C means demangle to AIX nm, but means don't demangle with GNU nm
+	if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
+	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	else
+	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	fi
+	aix_use_runtimelinking=no
+
+	# Test if we are trying to use run time linking or normal
+	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
+	# need to do runtime linking.
+	case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
+	  for ld_flag in $LDFLAGS; do
+	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+	    aix_use_runtimelinking=yes
+	    break
+	  fi
+	  done
+	  ;;
+	esac
+
+	exp_sym_flag='-bexport'
+	no_entry_flag='-bnoentry'
+      fi
+
+      # When large executables or shared objects are built, AIX ld can
+      # have problems creating the table of contents.  If linking a library
+      # or program results in "error TOC overflow" add -mminimal-toc to
+      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
+      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+      _LT_TAGVAR(archive_cmds, $1)=''
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
+
+      if test "$GCC" = yes; then
+	case $host_os in aix4.[[012]]|aix4.[[012]].*)
+	# We only want to do this on AIX 4.2 and lower, the check
+	# below for broken collect2 doesn't work under 4.3+
+	  collect2name=`${CC} -print-prog-name=collect2`
+	  if test -f "$collect2name" &&
+	   strings "$collect2name" | $GREP resolve_lib_name >/dev/null
+	  then
+	  # We have reworked collect2
+	  :
+	  else
+	  # We have old collect2
+	  _LT_TAGVAR(hardcode_direct, $1)=unsupported
+	  # It fails to find uninstalled libraries when the uninstalled
+	  # path is not listed in the libpath.  Setting hardcode_minus_L
+	  # to unsupported forces relinking
+	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	  _LT_TAGVAR(hardcode_libdir_separator, $1)=
+	  fi
+	  ;;
+	esac
+	shared_flag='-shared'
+	if test "$aix_use_runtimelinking" = yes; then
+	  shared_flag="$shared_flag "'${wl}-G'
+	fi
+      else
+	# not using gcc
+	if test "$host_cpu" = ia64; then
+	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+	# chokes on -Wl,-G. The following line is correct:
+	  shared_flag='-G'
+	else
+	  if test "$aix_use_runtimelinking" = yes; then
+	    shared_flag='${wl}-G'
+	  else
+	    shared_flag='${wl}-bM:SRE'
+	  fi
+	fi
+      fi
+
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
+      # It seems that -bexpall does not export symbols beginning with
+      # underscore (_), so it is better to generate a list of symbols to export.
+      _LT_TAGVAR(always_export_symbols, $1)=yes
+      if test "$aix_use_runtimelinking" = yes; then
+	# Warning - without using the other runtime loading flags (-brtl),
+	# -berok will link without error, but may produce a broken library.
+	_LT_TAGVAR(allow_undefined_flag, $1)='-berok'
+        # Determine the default libpath from the value encoded in an
+        # empty executable.
+        _LT_SYS_MODULE_PATH_AIX
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+      else
+	if test "$host_cpu" = ia64; then
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+	  _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+	else
+	 # Determine the default libpath from the value encoded in an
+	 # empty executable.
+	 _LT_SYS_MODULE_PATH_AIX
+	 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+	  # Warning - without using the other run time loading flags,
+	  # -berok will link without error, but may produce a broken library.
+	  _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+	  _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+	  # Exported symbols can be pulled into shared objects from archives
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+	  # This is similar to how AIX traditionally builds its shared libraries.
+	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	fi
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            _LT_TAGVAR(archive_expsym_cmds, $1)=''
+        ;;
+      m68k)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes
+        ;;
+      esac
+      ;;
+
+    bsdi[[45]]*)
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic
+      ;;
+
+    cygwin* | mingw* | pw32* | cegcc*)
+      # When not using gcc, we currently assume that we are using
+      # Microsoft Visual C++.
+      # hardcode_libdir_flag_spec is actually meaningless, as there is
+      # no search path for DLLs.
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      # Tell ltmain to make .lib files, not .a files.
+      libext=lib
+      # Tell ltmain to make .dll files, not .so files.
+      shrext_cmds=".dll"
+      # FIXME: Setting linknames here is a bad hack.
+      _LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `$ECHO "X$deplibs" | $Xsed -e '\''s/ -lc$//'\''` -link -dll~linknames='
+      # The linker will automatically build a .lib file if we build a DLL.
+      _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+      # FIXME: Should let the user specify the lib program.
+      _LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs'
+      _LT_TAGVAR(fix_srcfile_path, $1)='`cygpath -w "$srcfile"`'
+      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+      ;;
+
+    darwin* | rhapsody*)
+      _LT_DARWIN_LINKER_FEATURES($1)
+      ;;
+
+    dgux*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    freebsd1*)
+      _LT_TAGVAR(ld_shlibs, $1)=no
+      ;;
+
+    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
+    # support.  Future versions do this automatically, but an explicit c++rt0.o
+    # does not break anything, and helps significantly (at the cost of a little
+    # extra space).
+    freebsd2.2*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
+    freebsd2*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
+    freebsd* | dragonfly*)
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared -o $lib $libobjs $deplibs $compiler_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    hpux9*)
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+
+      # hardcode_minus_L: Not really in the search PATH,
+      # but as the default location of the library.
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+      ;;
+
+    hpux10*)
+      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
+      fi
+      if test "$with_gnu_ld" = no; then
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir'
+	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
+	_LT_TAGVAR(hardcode_direct, $1)=yes
+	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	# hardcode_minus_L: Not really in the search PATH,
+	# but as the default location of the library.
+	_LT_TAGVAR(hardcode_minus_L, $1)=yes
+      fi
+      ;;
+
+    hpux11*)
+      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+	case $host_cpu in
+	hppa*64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	ia64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	esac
+      else
+	case $host_cpu in
+	hppa*64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	ia64*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	esac
+      fi
+      if test "$with_gnu_ld" = no; then
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	case $host_cpu in
+	hppa*64*|ia64*)
+	  _LT_TAGVAR(hardcode_direct, $1)=no
+	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	  ;;
+	*)
+	  _LT_TAGVAR(hardcode_direct, $1)=yes
+	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+
+	  # hardcode_minus_L: Not really in the search PATH,
+	  # but as the default location of the library.
+	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
+	  ;;
+	esac
+      fi
+      ;;
+
+    irix5* | irix6* | nonstopux*)
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	# Try to use the -exported_symbol ld option, if it does not
+	# work, assume that -exports_file does not work either and
+	# implicitly export all symbols.
+        save_LDFLAGS="$LDFLAGS"
+        LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
+        AC_LINK_IFELSE(int foo(void) {},
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
+        )
+        LDFLAGS="$save_LDFLAGS"
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(inherit_rpath, $1)=yes
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
+    netbsd*)
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags'      # ELF
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    newsos6)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *nto* | *qnx*)
+      ;;
+
+    openbsd*)
+      if test -f /usr/libexec/ld.so; then
+	_LT_TAGVAR(hardcode_direct, $1)=yes
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	else
+	  case $host_os in
+	   openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*)
+	     _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	     ;;
+	   *)
+	     _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	     ;;
+	  esac
+	fi
+      else
+	_LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    os2*)
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$ECHO DATA >> $output_objdir/$libname.def~$ECHO " SINGLE NONSHARED" >> $output_objdir/$libname.def~$ECHO EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
+      _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
+      ;;
+
+    osf3*)
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+      else
+	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      ;;
+
+    osf4* | osf5*)	# as osf3* with the addition of -msym flag
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      else
+	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~
+	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'
+
+	# Both c and cxx compiler support -rpath directly
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      ;;
+
+    solaris*)
+      _LT_TAGVAR(no_undefined_flag, $1)=' -z defs'
+      if test "$GCC" = yes; then
+	wlarc='${wl}'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $CC -shared ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+      else
+	case `$CC -V 2>&1` in
+	*"Compilers 5.0"*)
+	  wlarc=''
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
+	  ;;
+	*)
+	  wlarc='${wl}'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+	  ;;
+	esac
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      case $host_os in
+      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+      *)
+	# The compiler driver will combine and reorder linker options,
+	# but understands `-z linker_flag'.  GCC discards it without `$wl',
+	# but is careful enough not to reorder.
+	# Supported since Solaris 2.6 (maybe 2.5.1?)
+	if test "$GCC" = yes; then
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+	else
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
+	fi
+	;;
+      esac
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
+    sunos4*)
+      if test "x$host_vendor" = xsequent; then
+	# Use $CC to link under sequent, because it throws in some extra .o
+	# files that make .init and .fini sections work.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    sysv4)
+      case $host_vendor in
+	sni)
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true???
+	;;
+	siemens)
+	  ## LD is ld it makes a PLAMLIB
+	  ## CC just makes a GrossModule.
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs'
+	  _LT_TAGVAR(hardcode_direct, $1)=no
+        ;;
+	motorola)
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie
+	;;
+      esac
+      runpath_var='LD_RUN_PATH'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    sysv4.3*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec; then
+	_LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	runpath_var=LD_RUN_PATH
+	hardcode_runpath_var=yes
+	_LT_TAGVAR(ld_shlibs, $1)=yes
+      fi
+      ;;
+
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      runpath_var='LD_RUN_PATH'
+
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      fi
+      ;;
+
+    sysv5* | sco3.2v5* | sco5v6*)
+      # Note: We can NOT use -z defs as we might desire, because we do not
+      # link with -lc, and that would cause any symbols used from libc to
+      # always be unresolved, which means just about no library would
+      # ever link correctly.  If we're not using GNU ld we use -z text
+      # though, which does catch some bad symbols but isn't as heavy-handed
+      # as -z defs.
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+      runpath_var='LD_RUN_PATH'
+
+      if test "$GCC" = yes; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      fi
+      ;;
+
+    uts4*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *)
+      _LT_TAGVAR(ld_shlibs, $1)=no
+      ;;
+    esac
+
+    if test x$host_vendor = xsni; then
+      case $host in
+      sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym'
+	;;
+      esac
+    fi
+  fi
+])
+AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
+test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+_LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld
+
+_LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl
+_LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl
+_LT_DECL([], [extract_expsyms_cmds], [2],
+    [The commands to extract the exported symbol list from a shared archive])
+
+#
+# Do we need to explicitly link libc?
+#
+case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in
+x|xyes)
+  # Assume -lc should be added
+  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+
+  if test "$enable_shared" = yes && test "$GCC" = yes; then
+    case $_LT_TAGVAR(archive_cmds, $1) in
+    *'~'*)
+      # FIXME: we may have to deal with multi-command sequences.
+      ;;
+    '$CC '*)
+      # Test whether the compiler implicitly links with -lc since on some
+      # systems, -lgcc has to come before -lc. If gcc already passes -lc
+      # to ld, don't add -lc before -lgcc.
+      AC_MSG_CHECKING([whether -lc should be explicitly linked in])
+      $RM conftest*
+      echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+      if AC_TRY_EVAL(ac_compile) 2>conftest.err; then
+        soname=conftest
+        lib=conftest
+        libobjs=conftest.$ac_objext
+        deplibs=
+        wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1)
+	pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1)
+        compiler_flags=-v
+        linker_flags=-v
+        verstring=
+        output_objdir=.
+        libname=conftest
+        lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1)
+        _LT_TAGVAR(allow_undefined_flag, $1)=
+        if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1)
+        then
+	  _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+        else
+	  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+        fi
+        _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag
+      else
+        cat conftest.err 1>&5
+      fi
+      $RM conftest*
+      AC_MSG_RESULT([$_LT_TAGVAR(archive_cmds_need_lc, $1)])
+      ;;
+    esac
+  fi
+  ;;
+esac
+
+_LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0],
+    [Whether or not to add -lc for building shared libraries])
+_LT_TAGDECL([allow_libtool_libs_with_static_runtimes],
+    [enable_shared_with_static_runtimes], [0],
+    [Whether or not to disallow shared libs when runtime libs are static])
+_LT_TAGDECL([], [export_dynamic_flag_spec], [1],
+    [Compiler flag to allow reflexive dlopens])
+_LT_TAGDECL([], [whole_archive_flag_spec], [1],
+    [Compiler flag to generate shared objects directly from archives])
+_LT_TAGDECL([], [compiler_needs_object], [1],
+    [Whether the compiler copes with passing no objects directly])
+_LT_TAGDECL([], [old_archive_from_new_cmds], [2],
+    [Create an old-style archive from a shared archive])
+_LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2],
+    [Create a temporary old-style archive to link instead of a shared archive])
+_LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive])
+_LT_TAGDECL([], [archive_expsym_cmds], [2])
+_LT_TAGDECL([], [module_cmds], [2],
+    [Commands used to build a loadable module if different from building
+    a shared archive.])
+_LT_TAGDECL([], [module_expsym_cmds], [2])
+_LT_TAGDECL([], [with_gnu_ld], [1],
+    [Whether we are building with GNU ld or not])
+_LT_TAGDECL([], [allow_undefined_flag], [1],
+    [Flag that allows shared libraries with undefined symbols to be built])
+_LT_TAGDECL([], [no_undefined_flag], [1],
+    [Flag that enforces no undefined symbols])
+_LT_TAGDECL([], [hardcode_libdir_flag_spec], [1],
+    [Flag to hardcode $libdir into a binary during linking.
+    This must work even if $libdir does not exist])
+_LT_TAGDECL([], [hardcode_libdir_flag_spec_ld], [1],
+    [[If ld is used when linking, flag to hardcode $libdir into a binary
+    during linking.  This must work even if $libdir does not exist]])
+_LT_TAGDECL([], [hardcode_libdir_separator], [1],
+    [Whether we need a single "-rpath" flag with a separated argument])
+_LT_TAGDECL([], [hardcode_direct], [0],
+    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
+    DIR into the resulting binary])
+_LT_TAGDECL([], [hardcode_direct_absolute], [0],
+    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
+    DIR into the resulting binary and the resulting library dependency is
+    "absolute", i.e impossible to change by setting ${shlibpath_var} if the
+    library is relocated])
+_LT_TAGDECL([], [hardcode_minus_L], [0],
+    [Set to "yes" if using the -LDIR flag during linking hardcodes DIR
+    into the resulting binary])
+_LT_TAGDECL([], [hardcode_shlibpath_var], [0],
+    [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR
+    into the resulting binary])
+_LT_TAGDECL([], [hardcode_automatic], [0],
+    [Set to "yes" if building a shared library automatically hardcodes DIR
+    into the library and all subsequent libraries and executables linked
+    against it])
+_LT_TAGDECL([], [inherit_rpath], [0],
+    [Set to yes if linker adds runtime paths of dependent libraries
+    to runtime path list])
+_LT_TAGDECL([], [link_all_deplibs], [0],
+    [Whether libtool must link a program against all its dependency libraries])
+_LT_TAGDECL([], [fix_srcfile_path], [1],
+    [Fix the shell variable $srcfile for the compiler])
+_LT_TAGDECL([], [always_export_symbols], [0],
+    [Set to "yes" if exported symbols are required])
+_LT_TAGDECL([], [export_symbols_cmds], [2],
+    [The commands to list exported symbols])
+_LT_TAGDECL([], [exclude_expsyms], [1],
+    [Symbols that should not be listed in the preloaded symbols])
+_LT_TAGDECL([], [include_expsyms], [1],
+    [Symbols that must always be exported])
+_LT_TAGDECL([], [prelink_cmds], [2],
+    [Commands necessary for linking programs (against libraries) with templates])
+_LT_TAGDECL([], [file_list_spec], [1],
+    [Specify filename containing input files])
+dnl FIXME: Not yet implemented
+dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1],
+dnl    [Compiler flag to generate thread safe objects])
+])# _LT_LINKER_SHLIBS
+
+
+# _LT_LANG_C_CONFIG([TAG])
+# ------------------------
+# Ensure that the configuration variables for a C compiler are suitably
+# defined.  These variables are subsequently used by _LT_CONFIG to write
+# the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_C_CONFIG],
+[m4_require([_LT_DECL_EGREP])dnl
+lt_save_CC="$CC"
+AC_LANG_PUSH(C)
+
+# Source file extension for C test sources.
+ac_ext=c
+
+# Object file extension for compiled C test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="int some_variable = 0;"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='int main(){return(0);}'
+
+_LT_TAG_COMPILER
+# Save the default compiler, since it gets overwritten when the other
+# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP.
+compiler_DEFAULT=$CC
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_SYS_DYNAMIC_LINKER($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+  LT_SYS_DLOPEN_SELF
+  _LT_CMD_STRIPLIB
+
+  # Report which library types will actually be built
+  AC_MSG_CHECKING([if libtool supports shared libraries])
+  AC_MSG_RESULT([$can_build_shared])
+
+  AC_MSG_CHECKING([whether to build shared libraries])
+  test "$can_build_shared" = "no" && enable_shared=no
+
+  # On AIX, shared libraries and static libraries use the same namespace, and
+  # are all built from PIC.
+  case $host_os in
+  aix3*)
+    test "$enable_shared" = yes && enable_static=no
+    if test -n "$RANLIB"; then
+      archive_cmds="$archive_cmds~\$RANLIB \$lib"
+      postinstall_cmds='$RANLIB $lib'
+    fi
+    ;;
+
+  aix[[4-9]]*)
+    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+      test "$enable_shared" = yes && enable_static=no
+    fi
+    ;;
+  esac
+  AC_MSG_RESULT([$enable_shared])
+
+  AC_MSG_CHECKING([whether to build static libraries])
+  # Make sure either enable_shared or enable_static is yes.
+  test "$enable_shared" = yes || enable_static=yes
+  AC_MSG_RESULT([$enable_static])
+
+  _LT_CONFIG($1)
+fi
+AC_LANG_POP
+CC="$lt_save_CC"
+])# _LT_LANG_C_CONFIG
+
+
+# _LT_PROG_CXX
+# ------------
+# Since AC_PROG_CXX is broken, in that it returns g++ if there is no c++
+# compiler, we have our own version here.
+m4_defun([_LT_PROG_CXX],
+[
+pushdef([AC_MSG_ERROR], [_lt_caught_CXX_error=yes])
+AC_PROG_CXX
+if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
+    ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
+    (test "X$CXX" != "Xg++"))) ; then
+  AC_PROG_CXXCPP
+else
+  _lt_caught_CXX_error=yes
+fi
+popdef([AC_MSG_ERROR])
+])# _LT_PROG_CXX
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([_LT_PROG_CXX], [])
+
+
+# _LT_LANG_CXX_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for a C++ compiler are suitably
+# defined.  These variables are subsequently used by _LT_CONFIG to write
+# the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_CXX_CONFIG],
+[AC_REQUIRE([_LT_PROG_CXX])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_EGREP])dnl
+
+AC_LANG_PUSH(C++)
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(compiler_needs_object, $1)=no
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for C++ test sources.
+ac_ext=cpp
+
+# Object file extension for compiled C++ test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the CXX compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_caught_CXX_error" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="int some_variable = 0;"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }'
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC=$CC
+  lt_save_LD=$LD
+  lt_save_GCC=$GCC
+  GCC=$GXX
+  lt_save_with_gnu_ld=$with_gnu_ld
+  lt_save_path_LD=$lt_cv_path_LD
+  if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
+    lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
+  else
+    $as_unset lt_cv_prog_gnu_ld
+  fi
+  if test -n "${lt_cv_path_LDCXX+set}"; then
+    lt_cv_path_LD=$lt_cv_path_LDCXX
+  else
+    $as_unset lt_cv_path_LD
+  fi
+  test -z "${LDCXX+set}" || LD=$LDCXX
+  CC=${CXX-"c++"}
+  compiler=$CC
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+
+  if test -n "$compiler"; then
+    # We don't want -fno-exception when compiling C++ code, so set the
+    # no_builtin_flag separately
+    if test "$GXX" = yes; then
+      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
+    else
+      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+    fi
+
+    if test "$GXX" = yes; then
+      # Set up default GNU C++ configuration
+
+      LT_PATH_LD
+
+      # Check if GNU C++ uses GNU ld as the underlying linker, since the
+      # archiving commands below assume that GNU ld is being used.
+      if test "$with_gnu_ld" = yes; then
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+        # If archive_cmds runs LD, not CC, wlarc should be empty
+        # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
+        #     investigate it a little bit more. (MM)
+        wlarc='${wl}'
+
+        # ancient GNU ld didn't support --whole-archive et. al.
+        if eval "`$CC -print-prog-name=ld` --help 2>&1" |
+	  $GREP 'no-whole-archive' > /dev/null; then
+          _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+        else
+          _LT_TAGVAR(whole_archive_flag_spec, $1)=
+        fi
+      else
+        with_gnu_ld=no
+        wlarc=
+
+        # A generic and very simple default shared library creation
+        # command for GNU C++ for the case where it uses the native
+        # linker, instead of GNU ld.  If possible, this setting should
+        # overridden to take advantage of the native linker features on
+        # the platform it is being used on.
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+      fi
+
+      # Commands to make compiler produce verbose output that lists
+      # what "hidden" libraries, object files and flags are used when
+      # linking a shared library.
+      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
+
+    else
+      GXX=no
+      with_gnu_ld=no
+      wlarc=
+    fi
+
+    # PORTME: fill in a description of your system's C++ link characteristics
+    AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+    _LT_TAGVAR(ld_shlibs, $1)=yes
+    case $host_os in
+      aix3*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+      aix[[4-9]]*)
+        if test "$host_cpu" = ia64; then
+          # On IA64, the linker does run time linking by default, so we don't
+          # have to do anything special.
+          aix_use_runtimelinking=no
+          exp_sym_flag='-Bexport'
+          no_entry_flag=""
+        else
+          aix_use_runtimelinking=no
+
+          # Test if we are trying to use run time linking or normal
+          # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+          # need to do runtime linking.
+          case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
+	    for ld_flag in $LDFLAGS; do
+	      case $ld_flag in
+	      *-brtl*)
+	        aix_use_runtimelinking=yes
+	        break
+	        ;;
+	      esac
+	    done
+	    ;;
+          esac
+
+          exp_sym_flag='-bexport'
+          no_entry_flag='-bnoentry'
+        fi
+
+        # When large executables or shared objects are built, AIX ld can
+        # have problems creating the table of contents.  If linking a library
+        # or program results in "error TOC overflow" add -mminimal-toc to
+        # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
+        # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+        _LT_TAGVAR(archive_cmds, $1)=''
+        _LT_TAGVAR(hardcode_direct, $1)=yes
+        _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+        _LT_TAGVAR(link_all_deplibs, $1)=yes
+        _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
+
+        if test "$GXX" = yes; then
+          case $host_os in aix4.[[012]]|aix4.[[012]].*)
+          # We only want to do this on AIX 4.2 and lower, the check
+          # below for broken collect2 doesn't work under 4.3+
+	  collect2name=`${CC} -print-prog-name=collect2`
+	  if test -f "$collect2name" &&
+	     strings "$collect2name" | $GREP resolve_lib_name >/dev/null
+	  then
+	    # We have reworked collect2
+	    :
+	  else
+	    # We have old collect2
+	    _LT_TAGVAR(hardcode_direct, $1)=unsupported
+	    # It fails to find uninstalled libraries when the uninstalled
+	    # path is not listed in the libpath.  Setting hardcode_minus_L
+	    # to unsupported forces relinking
+	    _LT_TAGVAR(hardcode_minus_L, $1)=yes
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=
+	  fi
+          esac
+          shared_flag='-shared'
+	  if test "$aix_use_runtimelinking" = yes; then
+	    shared_flag="$shared_flag "'${wl}-G'
+	  fi
+        else
+          # not using gcc
+          if test "$host_cpu" = ia64; then
+	  # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+	  # chokes on -Wl,-G. The following line is correct:
+	  shared_flag='-G'
+          else
+	    if test "$aix_use_runtimelinking" = yes; then
+	      shared_flag='${wl}-G'
+	    else
+	      shared_flag='${wl}-bM:SRE'
+	    fi
+          fi
+        fi
+
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
+        # It seems that -bexpall does not export symbols beginning with
+        # underscore (_), so it is better to generate a list of symbols to
+	# export.
+        _LT_TAGVAR(always_export_symbols, $1)=yes
+        if test "$aix_use_runtimelinking" = yes; then
+          # Warning - without using the other runtime loading flags (-brtl),
+          # -berok will link without error, but may produce a broken library.
+          _LT_TAGVAR(allow_undefined_flag, $1)='-berok'
+          # Determine the default libpath from the value encoded in an empty
+          # executable.
+          _LT_SYS_MODULE_PATH_AIX
+          _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+        else
+          if test "$host_cpu" = ia64; then
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+	    _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+          else
+	    # Determine the default libpath from the value encoded in an
+	    # empty executable.
+	    _LT_SYS_MODULE_PATH_AIX
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+	    # Warning - without using the other run time loading flags,
+	    # -berok will link without error, but may produce a broken library.
+	    _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+	    _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+	    # Exported symbols can be pulled into shared objects from archives
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	    _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+	    # This is similar to how AIX traditionally builds its shared
+	    # libraries.
+	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+          fi
+        fi
+        ;;
+
+      beos*)
+	if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	  # Joseph Beckenbach <jrb3@best.com> says some releases of gcc
+	  # support --undefined.  This deserves some investigation.  FIXME
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	else
+	  _LT_TAGVAR(ld_shlibs, $1)=no
+	fi
+	;;
+
+      chorus*)
+        case $cc_basename in
+          *)
+	  # FIXME: insert proper C++ library support
+	  _LT_TAGVAR(ld_shlibs, $1)=no
+	  ;;
+        esac
+        ;;
+
+      cygwin* | mingw* | pw32* | cegcc*)
+        # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+        # as there is no search path for DLLs.
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+        _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+        _LT_TAGVAR(always_export_symbols, $1)=no
+        _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+
+        if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+          # If the export-symbols file already is a .def file (1st line
+          # is EXPORTS), use it as is; otherwise, prepend...
+          _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	    cp $export_symbols $output_objdir/$soname.def;
+          else
+	    echo EXPORTS > $output_objdir/$soname.def;
+	    cat $export_symbols >> $output_objdir/$soname.def;
+          fi~
+          $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+        else
+          _LT_TAGVAR(ld_shlibs, $1)=no
+        fi
+        ;;
+      darwin* | rhapsody*)
+        _LT_DARWIN_LINKER_FEATURES($1)
+	;;
+
+      dgux*)
+        case $cc_basename in
+          ec++*)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          ghcx*)
+	    # Green Hills C++ Compiler
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+        esac
+        ;;
+
+      freebsd[[12]]*)
+        # C++ shared libraries reported to be fairly broken before
+	# switch to ELF
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      freebsd-elf*)
+        _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+        ;;
+
+      freebsd* | dragonfly*)
+        # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
+        # conventions
+        _LT_TAGVAR(ld_shlibs, $1)=yes
+        ;;
+
+      gnu*)
+        ;;
+
+      hpux9*)
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+        _LT_TAGVAR(hardcode_direct, $1)=yes
+        _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+				             # but as the default
+				             # location of the library.
+
+        case $cc_basename in
+          CC*)
+            # FIXME: insert proper C++ library support
+            _LT_TAGVAR(ld_shlibs, $1)=no
+            ;;
+          aCC*)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            # Commands to make compiler produce verbose output that lists
+            # what "hidden" libraries, object files and flags are used when
+            # linking a shared library.
+            #
+            # There doesn't appear to be a way to prevent this compiler from
+            # explicitly linking system object files so we need to strip them
+            # from the output so that they don't get included in the library
+            # dependencies.
+            output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+            ;;
+          *)
+            if test "$GXX" = yes; then
+              _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            else
+              # FIXME: insert proper C++ library support
+              _LT_TAGVAR(ld_shlibs, $1)=no
+            fi
+            ;;
+        esac
+        ;;
+
+      hpux10*|hpux11*)
+        if test $with_gnu_ld = no; then
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+	  _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+          case $host_cpu in
+            hppa*64*|ia64*)
+              ;;
+            *)
+	      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+              ;;
+          esac
+        fi
+        case $host_cpu in
+          hppa*64*|ia64*)
+            _LT_TAGVAR(hardcode_direct, $1)=no
+            _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+            ;;
+          *)
+            _LT_TAGVAR(hardcode_direct, $1)=yes
+            _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+					         # but as the default
+					         # location of the library.
+            ;;
+        esac
+
+        case $cc_basename in
+          CC*)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          aCC*)
+	    case $host_cpu in
+	      hppa*64*)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	      ia64*)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	      *)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        ;;
+	    esac
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+	    ;;
+          *)
+	    if test "$GXX" = yes; then
+	      if test $with_gnu_ld = no; then
+	        case $host_cpu in
+	          hppa*64*)
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	          ia64*)
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	          *)
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            ;;
+	        esac
+	      fi
+	    else
+	      # FIXME: insert proper C++ library support
+	      _LT_TAGVAR(ld_shlibs, $1)=no
+	    fi
+	    ;;
+        esac
+        ;;
+
+      interix[[3-9]]*)
+	_LT_TAGVAR(hardcode_direct, $1)=no
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	# Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+	# Instead, shared libraries are loaded at an image base (0x10000000 by
+	# default) and relocated if they conflict, which is a slow very memory
+	# consuming and fragmenting process.  To avoid this, we pick a random,
+	# 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+	# time.  Moving up from 0x10000000 also allows more sbrk(2) space.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+	;;
+      irix5* | irix6*)
+        case $cc_basename in
+          CC*)
+	    # SGI C++
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -ar", where "CC" is the IRIX C++ compiler.  This is
+	    # necessary to make sure instantiated templates are included
+	    # in the archive.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs'
+	    ;;
+          *)
+	    if test "$GXX" = yes; then
+	      if test "$with_gnu_ld" = no; then
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	      else
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` -o $lib'
+	      fi
+	    fi
+	    _LT_TAGVAR(link_all_deplibs, $1)=yes
+	    ;;
+        esac
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+        _LT_TAGVAR(inherit_rpath, $1)=yes
+        ;;
+
+      linux* | k*bsd*-gnu)
+        case $cc_basename in
+          KCC*)
+	    # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+	    # KCC will only create a shared library if the output file
+	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
+	    # to its proper name (with version) after linking.
+	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -Bstatic", where "CC" is the KAI C++ compiler.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
+	    ;;
+	  icpc* | ecpc* )
+	    # Intel C++
+	    with_gnu_ld=yes
+	    # version 8.0 and above of icpc choke on multiply defined symbols
+	    # if we add $predep_objects and $postdep_objects, however 7.1 and
+	    # earlier do not add the objects themselves.
+	    case `$CC -V 2>&1` in
+	      *"Version 7."*)
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+		;;
+	      *)  # Version 8.0 or newer
+	        tmp_idyn=
+	        case $host_cpu in
+		  ia64*) tmp_idyn=' -i_dynamic';;
+		esac
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+		;;
+	    esac
+	    _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	    ;;
+          pgCC* | pgcpp*)
+            # Portland Group C++ compiler
+	    case `$CC -V` in
+	    *pgCC\ [[1-5]]* | *pgcpp\ [[1-5]]*)
+	      _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~
+		compile_command="$compile_command `find $tpldir -name \*.o | $NL2SP`"'
+	      _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~
+		$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | $NL2SP`~
+		$RANLIB $oldlib'
+	      _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~
+		rm -rf $tpldir~
+		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+	      ;;
+	    *) # Version 6 will use weak symbols
+	      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+	      ;;
+	    esac
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+            ;;
+	  cxx*)
+	    # Compaq C++
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
+
+	    runpath_var=LD_RUN_PATH
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`$ECHO "X$templist" | $Xsed -e "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+	    ;;
+	  xl*)
+	    # IBM XL 8.0 on PPC, with GNU ld
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	    if test "x$supports_anon_versioning" = xyes; then
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+		cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+		echo "local: *; };" >> $output_objdir/$libname.ver~
+		$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+	    fi
+	    ;;
+	  *)
+	    case `$CC -V 2>&1 | sed 5q` in
+	    *Sun\ C*)
+	      # Sun C++ 5.9
+	      _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
+	      _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols'
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+	      _LT_TAGVAR(compiler_needs_object, $1)=yes
+
+	      # Not sure whether something based on
+	      # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1
+	      # would be better.
+	      output_verbose_link_cmd='echo'
+
+	      # Archives containing C++ object files must be created using
+	      # "CC -xar", where "CC" is the Sun C++ compiler.  This is
+	      # necessary to make sure instantiated templates are included
+	      # in the archive.
+	      _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
+	      ;;
+	    esac
+	    ;;
+	esac
+	;;
+
+      lynxos*)
+        # FIXME: insert proper C++ library support
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	;;
+
+      m88k*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+	;;
+
+      mvs*)
+        case $cc_basename in
+          cxx*)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+	  *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+	esac
+	;;
+
+      netbsd*)
+        if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable  -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags'
+	  wlarc=
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	  _LT_TAGVAR(hardcode_direct, $1)=yes
+	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	fi
+	# Workaround some broken pre-1.5 toolchains
+	output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
+	;;
+
+      *nto* | *qnx*)
+        _LT_TAGVAR(ld_shlibs, $1)=yes
+	;;
+
+      openbsd2*)
+        # C++ shared libraries are fairly broken
+	_LT_TAGVAR(ld_shlibs, $1)=no
+	;;
+
+      openbsd*)
+	if test -f /usr/libexec/ld.so; then
+	  _LT_TAGVAR(hardcode_direct, $1)=yes
+	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+	  fi
+	  output_verbose_link_cmd=echo
+	else
+	  _LT_TAGVAR(ld_shlibs, $1)=no
+	fi
+	;;
+
+      osf3* | osf4* | osf5*)
+        case $cc_basename in
+          KCC*)
+	    # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+	    # KCC will only create a shared library if the output file
+	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
+	    # to its proper name (with version) after linking.
+	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	    # Archives containing C++ object files must be created using
+	    # the KAI C++ compiler.
+	    case $host in
+	      osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;;
+	      *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;;
+	    esac
+	    ;;
+          RCC*)
+	    # Rational C++ 2.4.1
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          cxx*)
+	    case $host in
+	      osf3*)
+	        _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && $ECHO "X${wl}-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+		;;
+	      *)
+	        _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+	        _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
+	          echo "-hidden">> $lib.exp~
+	          $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp  `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~
+	          $RM $lib.exp'
+	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+		;;
+	    esac
+
+	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	    # Commands to make compiler produce verbose output that lists
+	    # what "hidden" libraries, object files and flags are used when
+	    # linking a shared library.
+	    #
+	    # There doesn't appear to be a way to prevent this compiler from
+	    # explicitly linking system object files so we need to strip them
+	    # from the output so that they don't get included in the library
+	    # dependencies.
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`$ECHO "X$templist" | $Xsed -e "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+	    ;;
+	  *)
+	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+	      _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	      case $host in
+	        osf3*)
+	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+		  ;;
+	        *)
+	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+		  ;;
+	      esac
+
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+	      # Commands to make compiler produce verbose output that lists
+	      # what "hidden" libraries, object files and flags are used when
+	      # linking a shared library.
+	      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
+
+	    else
+	      # FIXME: insert proper C++ library support
+	      _LT_TAGVAR(ld_shlibs, $1)=no
+	    fi
+	    ;;
+        esac
+        ;;
+
+      psos*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      sunos4*)
+        case $cc_basename in
+          CC*)
+	    # Sun C++ 4.x
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          lcc*)
+	    # Lucid
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+        esac
+        ;;
+
+      solaris*)
+        case $cc_basename in
+          CC*)
+	    # Sun C++ 4.2, 5.x and Centerline C++
+            _LT_TAGVAR(archive_cmds_need_lc,$1)=yes
+	    _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag}  -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	      $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+	    _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	    case $host_os in
+	      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+	      *)
+		# The compiler driver will combine and reorder linker options,
+		# but understands `-z linker_flag'.
+	        # Supported since Solaris 2.6 (maybe 2.5.1?)
+		_LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
+	        ;;
+	    esac
+	    _LT_TAGVAR(link_all_deplibs, $1)=yes
+
+	    output_verbose_link_cmd='echo'
+
+	    # Archives containing C++ object files must be created using
+	    # "CC -xar", where "CC" is the Sun C++ compiler.  This is
+	    # necessary to make sure instantiated templates are included
+	    # in the archive.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
+	    ;;
+          gcx*)
+	    # Green Hills C++ Compiler
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+
+	    # The C++ compiler must be used to create the archive.
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
+	    ;;
+          *)
+	    # GNU C++ compiler with Solaris linker
+	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+	      _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs'
+	      if $CC --version | $GREP -v '^2\.7' > /dev/null; then
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+		  $CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	        # Commands to make compiler produce verbose output that lists
+	        # what "hidden" libraries, object files and flags are used when
+	        # linking a shared library.
+	        output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
+	      else
+	        # g++ 2.7 appears to require `-G' NOT `-shared' on this
+	        # platform.
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+		  $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+	        # Commands to make compiler produce verbose output that lists
+	        # what "hidden" libraries, object files and flags are used when
+	        # linking a shared library.
+	        output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
+	      fi
+
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir'
+	      case $host_os in
+		solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+		*)
+		  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+		  ;;
+	      esac
+	    fi
+	    ;;
+        esac
+        ;;
+
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      runpath_var='LD_RUN_PATH'
+
+      case $cc_basename in
+        CC*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+	*)
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  ;;
+      esac
+      ;;
+
+      sysv5* | sco3.2v5* | sco5v6*)
+	# Note: We can NOT use -z defs as we might desire, because we do not
+	# link with -lc, and that would cause any symbols used from libc to
+	# always be unresolved, which means just about no library would
+	# ever link correctly.  If we're not using GNU ld we use -z text
+	# though, which does catch some bad symbols but isn't as heavy-handed
+	# as -z defs.
+	_LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+	_LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+	_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
+	_LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+	_LT_TAGVAR(link_all_deplibs, $1)=yes
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+	runpath_var='LD_RUN_PATH'
+
+	case $cc_basename in
+          CC*)
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    ;;
+	  *)
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    ;;
+	esac
+      ;;
+
+      tandem*)
+        case $cc_basename in
+          NCC*)
+	    # NonStop-UX NCC 3.20
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+          *)
+	    # FIXME: insert proper C++ library support
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	    ;;
+        esac
+        ;;
+
+      vxworks*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      *)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+    esac
+
+    AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
+    test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+    _LT_TAGVAR(GCC, $1)="$GXX"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_SYS_HIDDEN_LIBDEPS($1)
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  CC=$lt_save_CC
+  LDCXX=$LD
+  LD=$lt_save_LD
+  GCC=$lt_save_GCC
+  with_gnu_ld=$lt_save_with_gnu_ld
+  lt_cv_path_LDCXX=$lt_cv_path_LD
+  lt_cv_path_LD=$lt_save_path_LD
+  lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
+  lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
+fi # test "$_lt_caught_CXX_error" != yes
+
+AC_LANG_POP
+])# _LT_LANG_CXX_CONFIG
+
+
+# _LT_SYS_HIDDEN_LIBDEPS([TAGNAME])
+# ---------------------------------
+# Figure out "hidden" library dependencies from verbose
+# compiler output when linking a shared library.
+# Parse the compiler output and extract the necessary
+# objects, libraries and library flags.
+m4_defun([_LT_SYS_HIDDEN_LIBDEPS],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+# Dependencies to place before and after the object being linked:
+_LT_TAGVAR(predep_objects, $1)=
+_LT_TAGVAR(postdep_objects, $1)=
+_LT_TAGVAR(predeps, $1)=
+_LT_TAGVAR(postdeps, $1)=
+_LT_TAGVAR(compiler_lib_search_path, $1)=
+
+dnl we can't use the lt_simple_compile_test_code here,
+dnl because it contains code intended for an executable,
+dnl not a library.  It's possible we should let each
+dnl tag define a new lt_????_link_test_code variable,
+dnl but it's only used here...
+m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF
+int a;
+void foo (void) { a = 0; }
+_LT_EOF
+], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF
+class Foo
+{
+public:
+  Foo (void) { a = 0; }
+private:
+  int a;
+};
+_LT_EOF
+], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF
+      subroutine foo
+      implicit none
+      integer*4 a
+      a=0
+      return
+      end
+_LT_EOF
+], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF
+      subroutine foo
+      implicit none
+      integer a
+      a=0
+      return
+      end
+_LT_EOF
+], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF
+public class foo {
+  private int a;
+  public void bar (void) {
+    a = 0;
+  }
+};
+_LT_EOF
+])
+dnl Parse the compiler output and extract the necessary
+dnl objects, libraries and library flags.
+if AC_TRY_EVAL(ac_compile); then
+  # Parse the compiler output and extract the necessary
+  # objects, libraries and library flags.
+
+  # Sentinel used to keep track of whether or not we are before
+  # the conftest object file.
+  pre_test_object_deps_done=no
+
+  for p in `eval "$output_verbose_link_cmd"`; do
+    case $p in
+
+    -L* | -R* | -l*)
+       # Some compilers place space between "-{L,R}" and the path.
+       # Remove the space.
+       if test $p = "-L" ||
+          test $p = "-R"; then
+	 prev=$p
+	 continue
+       else
+	 prev=
+       fi
+
+       if test "$pre_test_object_deps_done" = no; then
+	 case $p in
+	 -L* | -R*)
+	   # Internal compiler library paths should come after those
+	   # provided the user.  The postdeps already come after the
+	   # user supplied libs so there is no need to process them.
+	   if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then
+	     _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}"
+	   else
+	     _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}"
+	   fi
+	   ;;
+	 # The "-l" case would never come before the object being
+	 # linked, so don't bother handling this case.
+	 esac
+       else
+	 if test -z "$_LT_TAGVAR(postdeps, $1)"; then
+	   _LT_TAGVAR(postdeps, $1)="${prev}${p}"
+	 else
+	   _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}"
+	 fi
+       fi
+       ;;
+
+    *.$objext)
+       # This assumes that the test object file only shows up
+       # once in the compiler output.
+       if test "$p" = "conftest.$objext"; then
+	 pre_test_object_deps_done=yes
+	 continue
+       fi
+
+       if test "$pre_test_object_deps_done" = no; then
+	 if test -z "$_LT_TAGVAR(predep_objects, $1)"; then
+	   _LT_TAGVAR(predep_objects, $1)="$p"
+	 else
+	   _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p"
+	 fi
+       else
+	 if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then
+	   _LT_TAGVAR(postdep_objects, $1)="$p"
+	 else
+	   _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p"
+	 fi
+       fi
+       ;;
+
+    *) ;; # Ignore the rest.
+
+    esac
+  done
+
+  # Clean up.
+  rm -f a.out a.exe
+else
+  echo "libtool.m4: error: problem compiling $1 test program"
+fi
+
+$RM -f confest.$objext
+
+# PORTME: override above test on systems where it is broken
+m4_if([$1], [CXX],
+[case $host_os in
+interix[[3-9]]*)
+  # Interix 3.5 installs completely hosed .la files for C++, so rather than
+  # hack all around it, let's just trust "g++" to DTRT.
+  _LT_TAGVAR(predep_objects,$1)=
+  _LT_TAGVAR(postdep_objects,$1)=
+  _LT_TAGVAR(postdeps,$1)=
+  ;;
+
+linux*)
+  case `$CC -V 2>&1 | sed 5q` in
+  *Sun\ C*)
+    # Sun C++ 5.9
+
+    # The more standards-conforming stlport4 library is
+    # incompatible with the Cstd library. Avoid specifying
+    # it if it's in CXXFLAGS. Ignore libCrun as
+    # -library=stlport4 depends on it.
+    case " $CXX $CXXFLAGS " in
+    *" -library=stlport4 "*)
+      solaris_use_stlport4=yes
+      ;;
+    esac
+
+    if test "$solaris_use_stlport4" != yes; then
+      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
+    fi
+    ;;
+  esac
+  ;;
+
+solaris*)
+  case $cc_basename in
+  CC*)
+    # The more standards-conforming stlport4 library is
+    # incompatible with the Cstd library. Avoid specifying
+    # it if it's in CXXFLAGS. Ignore libCrun as
+    # -library=stlport4 depends on it.
+    case " $CXX $CXXFLAGS " in
+    *" -library=stlport4 "*)
+      solaris_use_stlport4=yes
+      ;;
+    esac
+
+    # Adding this requires a known-good setup of shared libraries for
+    # Sun compiler versions before 5.6, else PIC objects from an old
+    # archive will be linked into the output, leading to subtle bugs.
+    if test "$solaris_use_stlport4" != yes; then
+      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
+    fi
+    ;;
+  esac
+  ;;
+esac
+])
+
+case " $_LT_TAGVAR(postdeps, $1) " in
+*" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;;
+esac
+ _LT_TAGVAR(compiler_lib_search_dirs, $1)=
+if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then
+ _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'`
+fi
+_LT_TAGDECL([], [compiler_lib_search_dirs], [1],
+    [The directories searched by this compiler when creating a shared library])
+_LT_TAGDECL([], [predep_objects], [1],
+    [Dependencies to place before and after the objects being linked to
+    create a shared library])
+_LT_TAGDECL([], [postdep_objects], [1])
+_LT_TAGDECL([], [predeps], [1])
+_LT_TAGDECL([], [postdeps], [1])
+_LT_TAGDECL([], [compiler_lib_search_path], [1],
+    [The library search path used internally by the compiler when linking
+    a shared library])
+])# _LT_SYS_HIDDEN_LIBDEPS
+
+
+# _LT_PROG_F77
+# ------------
+# Since AC_PROG_F77 is broken, in that it returns the empty string
+# if there is no fortran compiler, we have our own version here.
+m4_defun([_LT_PROG_F77],
+[
+pushdef([AC_MSG_ERROR], [_lt_disable_F77=yes])
+AC_PROG_F77
+if test -z "$F77" || test "X$F77" = "Xno"; then
+  _lt_disable_F77=yes
+fi
+popdef([AC_MSG_ERROR])
+])# _LT_PROG_F77
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([_LT_PROG_F77], [])
+
+
+# _LT_LANG_F77_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for a Fortran 77 compiler are
+# suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_F77_CONFIG],
+[AC_REQUIRE([_LT_PROG_F77])dnl
+AC_LANG_PUSH(Fortran 77)
+
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for f77 test sources.
+ac_ext=f
+
+# Object file extension for compiled f77 test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the F77 compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_disable_F77" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="\
+      subroutine t
+      return
+      end
+"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code="\
+      program t
+      end
+"
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC="$CC"
+  lt_save_GCC=$GCC
+  CC=${F77-"f77"}
+  compiler=$CC
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+  GCC=$G77
+  if test -n "$compiler"; then
+    AC_MSG_CHECKING([if libtool supports shared libraries])
+    AC_MSG_RESULT([$can_build_shared])
+
+    AC_MSG_CHECKING([whether to build shared libraries])
+    test "$can_build_shared" = "no" && enable_shared=no
+
+    # On AIX, shared libraries and static libraries use the same namespace, and
+    # are all built from PIC.
+    case $host_os in
+      aix3*)
+        test "$enable_shared" = yes && enable_static=no
+        if test -n "$RANLIB"; then
+          archive_cmds="$archive_cmds~\$RANLIB \$lib"
+          postinstall_cmds='$RANLIB $lib'
+        fi
+        ;;
+      aix[[4-9]]*)
+	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+	  test "$enable_shared" = yes && enable_static=no
+	fi
+        ;;
+    esac
+    AC_MSG_RESULT([$enable_shared])
+
+    AC_MSG_CHECKING([whether to build static libraries])
+    # Make sure either enable_shared or enable_static is yes.
+    test "$enable_shared" = yes || enable_static=yes
+    AC_MSG_RESULT([$enable_static])
+
+    _LT_TAGVAR(GCC, $1)="$G77"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  GCC=$lt_save_GCC
+  CC="$lt_save_CC"
+fi # test "$_lt_disable_F77" != yes
+
+AC_LANG_POP
+])# _LT_LANG_F77_CONFIG
+
+
+# _LT_PROG_FC
+# -----------
+# Since AC_PROG_FC is broken, in that it returns the empty string
+# if there is no fortran compiler, we have our own version here.
+m4_defun([_LT_PROG_FC],
+[
+pushdef([AC_MSG_ERROR], [_lt_disable_FC=yes])
+AC_PROG_FC
+if test -z "$FC" || test "X$FC" = "Xno"; then
+  _lt_disable_FC=yes
+fi
+popdef([AC_MSG_ERROR])
+])# _LT_PROG_FC
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([_LT_PROG_FC], [])
+
+
+# _LT_LANG_FC_CONFIG([TAG])
+# -------------------------
+# Ensure that the configuration variables for a Fortran compiler are
+# suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_FC_CONFIG],
+[AC_REQUIRE([_LT_PROG_FC])dnl
+AC_LANG_PUSH(Fortran)
+
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for fc test sources.
+ac_ext=${ac_fc_srcext-f}
+
+# Object file extension for compiled fc test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the FC compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_disable_FC" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="\
+      subroutine t
+      return
+      end
+"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code="\
+      program t
+      end
+"
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC="$CC"
+  lt_save_GCC=$GCC
+  CC=${FC-"f95"}
+  compiler=$CC
+  GCC=$ac_cv_fc_compiler_gnu
+
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+
+  if test -n "$compiler"; then
+    AC_MSG_CHECKING([if libtool supports shared libraries])
+    AC_MSG_RESULT([$can_build_shared])
+
+    AC_MSG_CHECKING([whether to build shared libraries])
+    test "$can_build_shared" = "no" && enable_shared=no
+
+    # On AIX, shared libraries and static libraries use the same namespace, and
+    # are all built from PIC.
+    case $host_os in
+      aix3*)
+        test "$enable_shared" = yes && enable_static=no
+        if test -n "$RANLIB"; then
+          archive_cmds="$archive_cmds~\$RANLIB \$lib"
+          postinstall_cmds='$RANLIB $lib'
+        fi
+        ;;
+      aix[[4-9]]*)
+	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+	  test "$enable_shared" = yes && enable_static=no
+	fi
+        ;;
+    esac
+    AC_MSG_RESULT([$enable_shared])
+
+    AC_MSG_CHECKING([whether to build static libraries])
+    # Make sure either enable_shared or enable_static is yes.
+    test "$enable_shared" = yes || enable_static=yes
+    AC_MSG_RESULT([$enable_static])
+
+    _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_SYS_HIDDEN_LIBDEPS($1)
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  GCC=$lt_save_GCC
+  CC="$lt_save_CC"
+fi # test "$_lt_disable_FC" != yes
+
+AC_LANG_POP
+])# _LT_LANG_FC_CONFIG
+
+
+# _LT_LANG_GCJ_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for the GNU Java Compiler compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_GCJ_CONFIG],
+[AC_REQUIRE([LT_PROG_GCJ])dnl
+AC_LANG_SAVE
+
+# Source file extension for Java test sources.
+ac_ext=java
+
+# Object file extension for compiled Java test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="class foo {}"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+lt_save_GCC=$GCC
+GCC=yes
+CC=${GCJ-"gcj"}
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_TAGVAR(LD, $1)="$LD"
+_LT_CC_BASENAME([$compiler])
+
+# GCJ did not exist at the time GCC didn't implicitly link libc in.
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+
+  _LT_CONFIG($1)
+fi
+
+AC_LANG_RESTORE
+
+GCC=$lt_save_GCC
+CC="$lt_save_CC"
+])# _LT_LANG_GCJ_CONFIG
+
+
+# _LT_LANG_RC_CONFIG([TAG])
+# -------------------------
+# Ensure that the configuration variables for the Windows resource compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_RC_CONFIG],
+[AC_REQUIRE([LT_PROG_RC])dnl
+AC_LANG_SAVE
+
+# Source file extension for RC test sources.
+ac_ext=rc
+
+# Object file extension for compiled RC test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }'
+
+# Code to be used in simple link tests
+lt_simple_link_test_code="$lt_simple_compile_test_code"
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+lt_save_GCC=$GCC
+GCC=
+CC=${RC-"windres"}
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_CC_BASENAME([$compiler])
+_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+
+if test -n "$compiler"; then
+  :
+  _LT_CONFIG($1)
+fi
+
+GCC=$lt_save_GCC
+AC_LANG_RESTORE
+CC="$lt_save_CC"
+])# _LT_LANG_RC_CONFIG
+
+
+# LT_PROG_GCJ
+# -----------
+AC_DEFUN([LT_PROG_GCJ],
+[m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ],
+  [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ],
+    [AC_CHECK_TOOL(GCJ, gcj,)
+      test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2"
+      AC_SUBST(GCJFLAGS)])])[]dnl
+])
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_GCJ], [])
+
+
+# LT_PROG_RC
+# ----------
+AC_DEFUN([LT_PROG_RC],
+[AC_CHECK_TOOL(RC, windres,)
+])
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_RC], [])
+
+
+# _LT_DECL_EGREP
+# --------------
+# If we don't have a new enough Autoconf to choose the best grep
+# available, choose the one first in the user's PATH.
+m4_defun([_LT_DECL_EGREP],
+[AC_REQUIRE([AC_PROG_EGREP])dnl
+AC_REQUIRE([AC_PROG_FGREP])dnl
+test -z "$GREP" && GREP=grep
+_LT_DECL([], [GREP], [1], [A grep program that handles long lines])
+_LT_DECL([], [EGREP], [1], [An ERE matcher])
+_LT_DECL([], [FGREP], [1], [A literal string matcher])
+dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too
+AC_SUBST([GREP])
+])
+
+
+# _LT_DECL_OBJDUMP
+# --------------
+# If we don't have a new enough Autoconf to choose the best objdump
+# available, choose the one first in the user's PATH.
+m4_defun([_LT_DECL_OBJDUMP],
+[AC_CHECK_TOOL(OBJDUMP, objdump, false)
+test -z "$OBJDUMP" && OBJDUMP=objdump
+_LT_DECL([], [OBJDUMP], [1], [An object symbol dumper])
+AC_SUBST([OBJDUMP])
+])
+
+
+# _LT_DECL_SED
+# ------------
+# Check for a fully-functional sed program, that truncates
+# as few characters as possible.  Prefer GNU sed if found.
+m4_defun([_LT_DECL_SED],
+[AC_PROG_SED
+test -z "$SED" && SED=sed
+Xsed="$SED -e 1s/^X//"
+_LT_DECL([], [SED], [1], [A sed program that does not truncate output])
+_LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"],
+    [Sed that helps us avoid accidentally triggering echo(1) options like -n])
+])# _LT_DECL_SED
+
+m4_ifndef([AC_PROG_SED], [
+############################################################
+# NOTE: This macro has been submitted for inclusion into   #
+#  GNU Autoconf as AC_PROG_SED.  When it is available in   #
+#  a released version of Autoconf we should remove this    #
+#  macro and use it instead.                               #
+############################################################
+
+m4_defun([AC_PROG_SED],
+[AC_MSG_CHECKING([for a sed that does not truncate output])
+AC_CACHE_VAL(lt_cv_path_SED,
+[# Loop through the user's path and test for sed and gsed.
+# Then use that list of sed's as ones to test for truncation.
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for lt_ac_prog in sed gsed; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
+        lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
+      fi
+    done
+  done
+done
+IFS=$as_save_IFS
+lt_ac_max=0
+lt_ac_count=0
+# Add /usr/xpg4/bin/sed as it is typically found on Solaris
+# along with /bin/sed that truncates output.
+for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
+  test ! -f $lt_ac_sed && continue
+  cat /dev/null > conftest.in
+  lt_ac_count=0
+  echo $ECHO_N "0123456789$ECHO_C" >conftest.in
+  # Check for GNU sed and select it if it is found.
+  if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
+    lt_cv_path_SED=$lt_ac_sed
+    break
+  fi
+  while true; do
+    cat conftest.in conftest.in >conftest.tmp
+    mv conftest.tmp conftest.in
+    cp conftest.in conftest.nl
+    echo >>conftest.nl
+    $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
+    cmp -s conftest.out conftest.nl || break
+    # 10000 chars as input seems more than enough
+    test $lt_ac_count -gt 10 && break
+    lt_ac_count=`expr $lt_ac_count + 1`
+    if test $lt_ac_count -gt $lt_ac_max; then
+      lt_ac_max=$lt_ac_count
+      lt_cv_path_SED=$lt_ac_sed
+    fi
+  done
+done
+])
+SED=$lt_cv_path_SED
+AC_SUBST([SED])
+AC_MSG_RESULT([$SED])
+])#AC_PROG_SED
+])#m4_ifndef
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_SED], [])
+
+
+# _LT_CHECK_SHELL_FEATURES
+# ------------------------
+# Find out whether the shell is Bourne or XSI compatible,
+# or has some other useful features.
+m4_defun([_LT_CHECK_SHELL_FEATURES],
+[AC_MSG_CHECKING([whether the shell understands some XSI constructs])
+# Try some XSI features
+xsi_shell=no
+( _lt_dummy="a/b/c"
+  test "${_lt_dummy##*/},${_lt_dummy%/*},"${_lt_dummy%"$_lt_dummy"}, \
+      = c,a/b,, \
+    && eval 'test $(( 1 + 1 )) -eq 2 \
+    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
+  && xsi_shell=yes
+AC_MSG_RESULT([$xsi_shell])
+_LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell'])
+
+AC_MSG_CHECKING([whether the shell understands "+="])
+lt_shell_append=no
+( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \
+    >/dev/null 2>&1 \
+  && lt_shell_append=yes
+AC_MSG_RESULT([$lt_shell_append])
+_LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append'])
+
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  lt_unset=unset
+else
+  lt_unset=false
+fi
+_LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl
+
+# test EBCDIC or ASCII
+case `echo X|tr X '\101'` in
+ A) # ASCII based system
+    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
+  lt_SP2NL='tr \040 \012'
+  lt_NL2SP='tr \015\012 \040\040'
+  ;;
+ *) # EBCDIC based system
+  lt_SP2NL='tr \100 \n'
+  lt_NL2SP='tr \r\n \100\100'
+  ;;
+esac
+_LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl
+_LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl
+])# _LT_CHECK_SHELL_FEATURES
+
+
+# _LT_PROG_XSI_SHELLFNS
+# ---------------------
+# Bourne and XSI compatible variants of some useful shell functions.
+m4_defun([_LT_PROG_XSI_SHELLFNS],
+[case $xsi_shell in
+  yes)
+    cat << \_LT_EOF >> "$cfgfile"
+
+# func_dirname file append nondir_replacement
+# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
+# otherwise set result to NONDIR_REPLACEMENT.
+func_dirname ()
+{
+  case ${1} in
+    */*) func_dirname_result="${1%/*}${2}" ;;
+    *  ) func_dirname_result="${3}" ;;
+  esac
+}
+
+# func_basename file
+func_basename ()
+{
+  func_basename_result="${1##*/}"
+}
+
+# func_dirname_and_basename file append nondir_replacement
+# perform func_basename and func_dirname in a single function
+# call:
+#   dirname:  Compute the dirname of FILE.  If nonempty,
+#             add APPEND to the result, otherwise set result
+#             to NONDIR_REPLACEMENT.
+#             value returned in "$func_dirname_result"
+#   basename: Compute filename of FILE.
+#             value retuned in "$func_basename_result"
+# Implementation must be kept synchronized with func_dirname
+# and func_basename. For efficiency, we do not delegate to
+# those functions but instead duplicate the functionality here.
+func_dirname_and_basename ()
+{
+  case ${1} in
+    */*) func_dirname_result="${1%/*}${2}" ;;
+    *  ) func_dirname_result="${3}" ;;
+  esac
+  func_basename_result="${1##*/}"
+}
+
+# func_stripname prefix suffix name
+# strip PREFIX and SUFFIX off of NAME.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+func_stripname ()
+{
+  # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are
+  # positional parameters, so assign one to ordinary parameter first.
+  func_stripname_result=${3}
+  func_stripname_result=${func_stripname_result#"${1}"}
+  func_stripname_result=${func_stripname_result%"${2}"}
+}
+
+# func_opt_split
+func_opt_split ()
+{
+  func_opt_split_opt=${1%%=*}
+  func_opt_split_arg=${1#*=}
+}
+
+# func_lo2o object
+func_lo2o ()
+{
+  case ${1} in
+    *.lo) func_lo2o_result=${1%.lo}.${objext} ;;
+    *)    func_lo2o_result=${1} ;;
+  esac
+}
+
+# func_xform libobj-or-source
+func_xform ()
+{
+  func_xform_result=${1%.*}.lo
+}
+
+# func_arith arithmetic-term...
+func_arith ()
+{
+  func_arith_result=$(( $[*] ))
+}
+
+# func_len string
+# STRING may not start with a hyphen.
+func_len ()
+{
+  func_len_result=${#1}
+}
+
+_LT_EOF
+    ;;
+  *) # Bourne compatible functions.
+    cat << \_LT_EOF >> "$cfgfile"
+
+# func_dirname file append nondir_replacement
+# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
+# otherwise set result to NONDIR_REPLACEMENT.
+func_dirname ()
+{
+  # Extract subdirectory from the argument.
+  func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"`
+  if test "X$func_dirname_result" = "X${1}"; then
+    func_dirname_result="${3}"
+  else
+    func_dirname_result="$func_dirname_result${2}"
+  fi
+}
+
+# func_basename file
+func_basename ()
+{
+  func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"`
+}
+
+dnl func_dirname_and_basename
+dnl A portable version of this function is already defined in general.m4sh
+dnl so there is no need for it here.
+
+# func_stripname prefix suffix name
+# strip PREFIX and SUFFIX off of NAME.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+# func_strip_suffix prefix name
+func_stripname ()
+{
+  case ${2} in
+    .*) func_stripname_result=`$ECHO "X${3}" \
+           | $Xsed -e "s%^${1}%%" -e "s%\\\\${2}\$%%"`;;
+    *)  func_stripname_result=`$ECHO "X${3}" \
+           | $Xsed -e "s%^${1}%%" -e "s%${2}\$%%"`;;
+  esac
+}
+
+# sed scripts:
+my_sed_long_opt='1s/^\(-[[^=]]*\)=.*/\1/;q'
+my_sed_long_arg='1s/^-[[^=]]*=//'
+
+# func_opt_split
+func_opt_split ()
+{
+  func_opt_split_opt=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_opt"`
+  func_opt_split_arg=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_arg"`
+}
+
+# func_lo2o object
+func_lo2o ()
+{
+  func_lo2o_result=`$ECHO "X${1}" | $Xsed -e "$lo2o"`
+}
+
+# func_xform libobj-or-source
+func_xform ()
+{
+  func_xform_result=`$ECHO "X${1}" | $Xsed -e 's/\.[[^.]]*$/.lo/'`
+}
+
+# func_arith arithmetic-term...
+func_arith ()
+{
+  func_arith_result=`expr "$[@]"`
+}
+
+# func_len string
+# STRING may not start with a hyphen.
+func_len ()
+{
+  func_len_result=`expr "$[1]" : ".*" 2>/dev/null || echo $max_cmd_len`
+}
+
+_LT_EOF
+esac
+
+case $lt_shell_append in
+  yes)
+    cat << \_LT_EOF >> "$cfgfile"
+
+# func_append var value
+# Append VALUE to the end of shell variable VAR.
+func_append ()
+{
+  eval "$[1]+=\$[2]"
+}
+_LT_EOF
+    ;;
+  *)
+    cat << \_LT_EOF >> "$cfgfile"
+
+# func_append var value
+# Append VALUE to the end of shell variable VAR.
+func_append ()
+{
+  eval "$[1]=\$$[1]\$[2]"
+}
+
+_LT_EOF
+    ;;
+  esac
+])
Index: /issm/trunk-jpl-damage/m4/ltoptions.m4
===================================================================
--- /issm/trunk-jpl-damage/m4/ltoptions.m4	(revision 11330)
+++ /issm/trunk-jpl-damage/m4/ltoptions.m4	(revision 11330)
@@ -0,0 +1,368 @@
+# Helper functions for option handling.                    -*- Autoconf -*-
+#
+#   Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
+#   Written by Gary V. Vaughan, 2004
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# serial 6 ltoptions.m4
+
+# This is to help aclocal find these macros, as it can't see m4_define.
+AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])])
+
+
+# _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME)
+# ------------------------------------------
+m4_define([_LT_MANGLE_OPTION],
+[[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])])
+
+
+# _LT_SET_OPTION(MACRO-NAME, OPTION-NAME)
+# ---------------------------------------
+# Set option OPTION-NAME for macro MACRO-NAME, and if there is a
+# matching handler defined, dispatch to it.  Other OPTION-NAMEs are
+# saved as a flag.
+m4_define([_LT_SET_OPTION],
+[m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl
+m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]),
+        _LT_MANGLE_DEFUN([$1], [$2]),
+    [m4_warning([Unknown $1 option `$2'])])[]dnl
+])
+
+
+# _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET])
+# ------------------------------------------------------------
+# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
+m4_define([_LT_IF_OPTION],
+[m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])])
+
+
+# _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET)
+# -------------------------------------------------------
+# Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME
+# are set.
+m4_define([_LT_UNLESS_OPTIONS],
+[m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
+	    [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option),
+		      [m4_define([$0_found])])])[]dnl
+m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3
+])[]dnl
+])
+
+
+# _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST)
+# ----------------------------------------
+# OPTION-LIST is a space-separated list of Libtool options associated
+# with MACRO-NAME.  If any OPTION has a matching handler declared with
+# LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about
+# the unknown option and exit.
+m4_defun([_LT_SET_OPTIONS],
+[# Set options
+m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
+    [_LT_SET_OPTION([$1], _LT_Option)])
+
+m4_if([$1],[LT_INIT],[
+  dnl
+  dnl Simply set some default values (i.e off) if boolean options were not
+  dnl specified:
+  _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no
+  ])
+  _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no
+  ])
+  dnl
+  dnl If no reference was made to various pairs of opposing options, then
+  dnl we run the default mode handler for the pair.  For example, if neither
+  dnl `shared' nor `disable-shared' was passed, we enable building of shared
+  dnl archives by default:
+  _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED])
+  _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC])
+  _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC])
+  _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install],
+  		   [_LT_ENABLE_FAST_INSTALL])
+  ])
+])# _LT_SET_OPTIONS
+
+
+## --------------------------------- ##
+## Macros to handle LT_INIT options. ##
+## --------------------------------- ##
+
+# _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME)
+# -----------------------------------------
+m4_define([_LT_MANGLE_DEFUN],
+[[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])])
+
+
+# LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE)
+# -----------------------------------------------
+m4_define([LT_OPTION_DEFINE],
+[m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl
+])# LT_OPTION_DEFINE
+
+
+# dlopen
+# ------
+LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes
+])
+
+AU_DEFUN([AC_LIBTOOL_DLOPEN],
+[_LT_SET_OPTION([LT_INIT], [dlopen])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you
+put the `dlopen' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], [])
+
+
+# win32-dll
+# ---------
+# Declare package support for building win32 dll's.
+LT_OPTION_DEFINE([LT_INIT], [win32-dll],
+[enable_win32_dll=yes
+
+case $host in
+*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-cegcc*)
+  AC_CHECK_TOOL(AS, as, false)
+  AC_CHECK_TOOL(DLLTOOL, dlltool, false)
+  AC_CHECK_TOOL(OBJDUMP, objdump, false)
+  ;;
+esac
+
+test -z "$AS" && AS=as
+_LT_DECL([], [AS],      [0], [Assembler program])dnl
+
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+_LT_DECL([], [DLLTOOL], [0], [DLL creation program])dnl
+
+test -z "$OBJDUMP" && OBJDUMP=objdump
+_LT_DECL([], [OBJDUMP], [0], [Object dumper program])dnl
+])# win32-dll
+
+AU_DEFUN([AC_LIBTOOL_WIN32_DLL],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+_LT_SET_OPTION([LT_INIT], [win32-dll])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you
+put the `win32-dll' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], [])
+
+
+# _LT_ENABLE_SHARED([DEFAULT])
+# ----------------------------
+# implement the --enable-shared flag, and supports the `shared' and
+# `disable-shared' LT_INIT options.
+# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+m4_define([_LT_ENABLE_SHARED],
+[m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl
+AC_ARG_ENABLE([shared],
+    [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@],
+	[build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])],
+    [p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_shared=yes ;;
+    no) enable_shared=no ;;
+    *)
+      enable_shared=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_shared=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [enable_shared=]_LT_ENABLE_SHARED_DEFAULT)
+
+    _LT_DECL([build_libtool_libs], [enable_shared], [0],
+	[Whether or not to build shared libraries])
+])# _LT_ENABLE_SHARED
+
+LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])])
+LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])])
+
+# Old names:
+AC_DEFUN([AC_ENABLE_SHARED],
+[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared])
+])
+
+AC_DEFUN([AC_DISABLE_SHARED],
+[_LT_SET_OPTION([LT_INIT], [disable-shared])
+])
+
+AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)])
+AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_ENABLE_SHARED], [])
+dnl AC_DEFUN([AM_DISABLE_SHARED], [])
+
+
+
+# _LT_ENABLE_STATIC([DEFAULT])
+# ----------------------------
+# implement the --enable-static flag, and support the `static' and
+# `disable-static' LT_INIT options.
+# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+m4_define([_LT_ENABLE_STATIC],
+[m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl
+AC_ARG_ENABLE([static],
+    [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@],
+	[build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])],
+    [p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_static=yes ;;
+    no) enable_static=no ;;
+    *)
+     enable_static=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_static=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [enable_static=]_LT_ENABLE_STATIC_DEFAULT)
+
+    _LT_DECL([build_old_libs], [enable_static], [0],
+	[Whether or not to build static libraries])
+])# _LT_ENABLE_STATIC
+
+LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])])
+LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])])
+
+# Old names:
+AC_DEFUN([AC_ENABLE_STATIC],
+[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static])
+])
+
+AC_DEFUN([AC_DISABLE_STATIC],
+[_LT_SET_OPTION([LT_INIT], [disable-static])
+])
+
+AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)])
+AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_ENABLE_STATIC], [])
+dnl AC_DEFUN([AM_DISABLE_STATIC], [])
+
+
+
+# _LT_ENABLE_FAST_INSTALL([DEFAULT])
+# ----------------------------------
+# implement the --enable-fast-install flag, and support the `fast-install'
+# and `disable-fast-install' LT_INIT options.
+# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+m4_define([_LT_ENABLE_FAST_INSTALL],
+[m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl
+AC_ARG_ENABLE([fast-install],
+    [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@],
+    [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])],
+    [p=${PACKAGE-default}
+    case $enableval in
+    yes) enable_fast_install=yes ;;
+    no) enable_fast_install=no ;;
+    *)
+      enable_fast_install=no
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS="$lt_save_ifs"
+	if test "X$pkg" = "X$p"; then
+	  enable_fast_install=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
+    [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT)
+
+_LT_DECL([fast_install], [enable_fast_install], [0],
+	 [Whether or not to optimize for fast installation])dnl
+])# _LT_ENABLE_FAST_INSTALL
+
+LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])])
+LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])])
+
+# Old names:
+AU_DEFUN([AC_ENABLE_FAST_INSTALL],
+[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you put
+the `fast-install' option into LT_INIT's first parameter.])
+])
+
+AU_DEFUN([AC_DISABLE_FAST_INSTALL],
+[_LT_SET_OPTION([LT_INIT], [disable-fast-install])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you put
+the `disable-fast-install' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], [])
+dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], [])
+
+
+# _LT_WITH_PIC([MODE])
+# --------------------
+# implement the --with-pic flag, and support the `pic-only' and `no-pic'
+# LT_INIT options.
+# MODE is either `yes' or `no'.  If omitted, it defaults to `both'.
+m4_define([_LT_WITH_PIC],
+[AC_ARG_WITH([pic],
+    [AS_HELP_STRING([--with-pic],
+	[try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
+    [pic_mode="$withval"],
+    [pic_mode=default])
+
+test -z "$pic_mode" && pic_mode=m4_default([$1], [default])
+
+_LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl
+])# _LT_WITH_PIC
+
+LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])])
+LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])])
+
+# Old name:
+AU_DEFUN([AC_LIBTOOL_PICMODE],
+[_LT_SET_OPTION([LT_INIT], [pic-only])
+AC_DIAGNOSE([obsolete],
+[$0: Remove this warning and the call to _LT_SET_OPTION when you
+put the `pic-only' option into LT_INIT's first parameter.])
+])
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_PICMODE], [])
+
+## ----------------- ##
+## LTDL_INIT Options ##
+## ----------------- ##
+
+m4_define([_LTDL_MODE], [])
+LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive],
+		 [m4_define([_LTDL_MODE], [nonrecursive])])
+LT_OPTION_DEFINE([LTDL_INIT], [recursive],
+		 [m4_define([_LTDL_MODE], [recursive])])
+LT_OPTION_DEFINE([LTDL_INIT], [subproject],
+		 [m4_define([_LTDL_MODE], [subproject])])
+
+m4_define([_LTDL_TYPE], [])
+LT_OPTION_DEFINE([LTDL_INIT], [installable],
+		 [m4_define([_LTDL_TYPE], [installable])])
+LT_OPTION_DEFINE([LTDL_INIT], [convenience],
+		 [m4_define([_LTDL_TYPE], [convenience])])
Index: /issm/trunk-jpl-damage/m4/ltsugar.m4
===================================================================
--- /issm/trunk-jpl-damage/m4/ltsugar.m4	(revision 11330)
+++ /issm/trunk-jpl-damage/m4/ltsugar.m4	(revision 11330)
@@ -0,0 +1,123 @@
+# ltsugar.m4 -- libtool m4 base layer.                         -*-Autoconf-*-
+#
+# Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
+# Written by Gary V. Vaughan, 2004
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# serial 6 ltsugar.m4
+
+# This is to help aclocal find these macros, as it can't see m4_define.
+AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])])
+
+
+# lt_join(SEP, ARG1, [ARG2...])
+# -----------------------------
+# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their
+# associated separator.
+# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier
+# versions in m4sugar had bugs.
+m4_define([lt_join],
+[m4_if([$#], [1], [],
+       [$#], [2], [[$2]],
+       [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])])
+m4_define([_lt_join],
+[m4_if([$#$2], [2], [],
+       [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])])
+
+
+# lt_car(LIST)
+# lt_cdr(LIST)
+# ------------
+# Manipulate m4 lists.
+# These macros are necessary as long as will still need to support
+# Autoconf-2.59 which quotes differently.
+m4_define([lt_car], [[$1]])
+m4_define([lt_cdr],
+[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])],
+       [$#], 1, [],
+       [m4_dquote(m4_shift($@))])])
+m4_define([lt_unquote], $1)
+
+
+# lt_append(MACRO-NAME, STRING, [SEPARATOR])
+# ------------------------------------------
+# Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'.
+# Note that neither SEPARATOR nor STRING are expanded; they are appended
+# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked).
+# No SEPARATOR is output if MACRO-NAME was previously undefined (different
+# than defined and empty).
+#
+# This macro is needed until we can rely on Autoconf 2.62, since earlier
+# versions of m4sugar mistakenly expanded SEPARATOR but not STRING.
+m4_define([lt_append],
+[m4_define([$1],
+	   m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])])
+
+
+
+# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...])
+# ----------------------------------------------------------
+# Produce a SEP delimited list of all paired combinations of elements of
+# PREFIX-LIST with SUFFIX1 through SUFFIXn.  Each element of the list
+# has the form PREFIXmINFIXSUFFIXn.
+# Needed until we can rely on m4_combine added in Autoconf 2.62.
+m4_define([lt_combine],
+[m4_if(m4_eval([$# > 3]), [1],
+       [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl
+[[m4_foreach([_Lt_prefix], [$2],
+	     [m4_foreach([_Lt_suffix],
+		]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[,
+	[_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])])
+
+
+# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ])
+# -----------------------------------------------------------------------
+# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited
+# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ.
+m4_define([lt_if_append_uniq],
+[m4_ifdef([$1],
+	  [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1],
+		 [lt_append([$1], [$2], [$3])$4],
+		 [$5])],
+	  [lt_append([$1], [$2], [$3])$4])])
+
+
+# lt_dict_add(DICT, KEY, VALUE)
+# -----------------------------
+m4_define([lt_dict_add],
+[m4_define([$1($2)], [$3])])
+
+
+# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE)
+# --------------------------------------------
+m4_define([lt_dict_add_subkey],
+[m4_define([$1($2:$3)], [$4])])
+
+
+# lt_dict_fetch(DICT, KEY, [SUBKEY])
+# ----------------------------------
+m4_define([lt_dict_fetch],
+[m4_ifval([$3],
+	m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]),
+    m4_ifdef([$1($2)], [m4_defn([$1($2)])]))])
+
+
+# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE])
+# -----------------------------------------------------------------
+m4_define([lt_if_dict_fetch],
+[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4],
+	[$5],
+    [$6])])
+
+
+# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...])
+# --------------------------------------------------------------
+m4_define([lt_dict_filter],
+[m4_if([$5], [], [],
+  [lt_join(m4_quote(m4_default([$4], [[, ]])),
+           lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]),
+		      [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl
+])
Index: /issm/trunk-jpl-damage/m4/ltversion.m4
===================================================================
--- /issm/trunk-jpl-damage/m4/ltversion.m4	(revision 11330)
+++ /issm/trunk-jpl-damage/m4/ltversion.m4	(revision 11330)
@@ -0,0 +1,23 @@
+# ltversion.m4 -- version numbers			-*- Autoconf -*-
+#
+#   Copyright (C) 2004 Free Software Foundation, Inc.
+#   Written by Scott James Remnant, 2004
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# Generated from ltversion.in.
+
+# serial 3017 ltversion.m4
+# This file is part of GNU Libtool
+
+m4_define([LT_PACKAGE_VERSION], [2.2.6b])
+m4_define([LT_PACKAGE_REVISION], [1.3017])
+
+AC_DEFUN([LTVERSION_VERSION],
+[macro_version='2.2.6b'
+macro_revision='1.3017'
+_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?])
+_LT_DECL(, macro_revision, 0)
+])
Index: /issm/trunk-jpl-damage/m4/lt~obsolete.m4
===================================================================
--- /issm/trunk-jpl-damage/m4/lt~obsolete.m4	(revision 11330)
+++ /issm/trunk-jpl-damage/m4/lt~obsolete.m4	(revision 11330)
@@ -0,0 +1,92 @@
+# lt~obsolete.m4 -- aclocal satisfying obsolete definitions.    -*-Autoconf-*-
+#
+#   Copyright (C) 2004, 2005, 2007 Free Software Foundation, Inc.
+#   Written by Scott James Remnant, 2004.
+#
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+
+# serial 4 lt~obsolete.m4
+
+# These exist entirely to fool aclocal when bootstrapping libtool.
+#
+# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN)
+# which have later been changed to m4_define as they aren't part of the
+# exported API, or moved to Autoconf or Automake where they belong.
+#
+# The trouble is, aclocal is a bit thick.  It'll see the old AC_DEFUN
+# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us
+# using a macro with the same name in our local m4/libtool.m4 it'll
+# pull the old libtool.m4 in (it doesn't see our shiny new m4_define
+# and doesn't know about Autoconf macros at all.)
+#
+# So we provide this file, which has a silly filename so it's always
+# included after everything else.  This provides aclocal with the
+# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything
+# because those macros already exist, or will be overwritten later.
+# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. 
+#
+# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here.
+# Yes, that means every name once taken will need to remain here until
+# we give up compatibility with versions before 1.7, at which point
+# we need to keep only those names which we still refer to.
+
+# This is to help aclocal find these macros, as it can't see m4_define.
+AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])])
+
+m4_ifndef([AC_LIBTOOL_LINKER_OPTION],	[AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])])
+m4_ifndef([AC_PROG_EGREP],		[AC_DEFUN([AC_PROG_EGREP])])
+m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])])
+m4_ifndef([_LT_AC_SHELL_INIT],		[AC_DEFUN([_LT_AC_SHELL_INIT])])
+m4_ifndef([_LT_AC_SYS_LIBPATH_AIX],	[AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])])
+m4_ifndef([_LT_PROG_LTMAIN],		[AC_DEFUN([_LT_PROG_LTMAIN])])
+m4_ifndef([_LT_AC_TAGVAR],		[AC_DEFUN([_LT_AC_TAGVAR])])
+m4_ifndef([AC_LTDL_ENABLE_INSTALL],	[AC_DEFUN([AC_LTDL_ENABLE_INSTALL])])
+m4_ifndef([AC_LTDL_PREOPEN],		[AC_DEFUN([AC_LTDL_PREOPEN])])
+m4_ifndef([_LT_AC_SYS_COMPILER],	[AC_DEFUN([_LT_AC_SYS_COMPILER])])
+m4_ifndef([_LT_AC_LOCK],		[AC_DEFUN([_LT_AC_LOCK])])
+m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE],	[AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])])
+m4_ifndef([_LT_AC_TRY_DLOPEN_SELF],	[AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])])
+m4_ifndef([AC_LIBTOOL_PROG_CC_C_O],	[AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])])
+m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])])
+m4_ifndef([AC_LIBTOOL_OBJDIR],		[AC_DEFUN([AC_LIBTOOL_OBJDIR])])
+m4_ifndef([AC_LTDL_OBJDIR],		[AC_DEFUN([AC_LTDL_OBJDIR])])
+m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])])
+m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP],	[AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])])
+m4_ifndef([AC_PATH_MAGIC],		[AC_DEFUN([AC_PATH_MAGIC])])
+m4_ifndef([AC_PROG_LD_GNU],		[AC_DEFUN([AC_PROG_LD_GNU])])
+m4_ifndef([AC_PROG_LD_RELOAD_FLAG],	[AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])])
+m4_ifndef([AC_DEPLIBS_CHECK_METHOD],	[AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])])
+m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])])
+m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])])
+m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])])
+m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS],	[AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])])
+m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP],	[AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])])
+m4_ifndef([LT_AC_PROG_EGREP],		[AC_DEFUN([LT_AC_PROG_EGREP])])
+m4_ifndef([LT_AC_PROG_SED],		[AC_DEFUN([LT_AC_PROG_SED])])
+m4_ifndef([_LT_CC_BASENAME],		[AC_DEFUN([_LT_CC_BASENAME])])
+m4_ifndef([_LT_COMPILER_BOILERPLATE],	[AC_DEFUN([_LT_COMPILER_BOILERPLATE])])
+m4_ifndef([_LT_LINKER_BOILERPLATE],	[AC_DEFUN([_LT_LINKER_BOILERPLATE])])
+m4_ifndef([_AC_PROG_LIBTOOL],		[AC_DEFUN([_AC_PROG_LIBTOOL])])
+m4_ifndef([AC_LIBTOOL_SETUP],		[AC_DEFUN([AC_LIBTOOL_SETUP])])
+m4_ifndef([_LT_AC_CHECK_DLFCN],		[AC_DEFUN([_LT_AC_CHECK_DLFCN])])
+m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER],	[AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])])
+m4_ifndef([_LT_AC_TAGCONFIG],		[AC_DEFUN([_LT_AC_TAGCONFIG])])
+m4_ifndef([AC_DISABLE_FAST_INSTALL],	[AC_DEFUN([AC_DISABLE_FAST_INSTALL])])
+m4_ifndef([_LT_AC_LANG_CXX],		[AC_DEFUN([_LT_AC_LANG_CXX])])
+m4_ifndef([_LT_AC_LANG_F77],		[AC_DEFUN([_LT_AC_LANG_F77])])
+m4_ifndef([_LT_AC_LANG_GCJ],		[AC_DEFUN([_LT_AC_LANG_GCJ])])
+m4_ifndef([AC_LIBTOOL_RC],		[AC_DEFUN([AC_LIBTOOL_RC])])
+m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])])
+m4_ifndef([_LT_AC_LANG_C_CONFIG],	[AC_DEFUN([_LT_AC_LANG_C_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])])
+m4_ifndef([_LT_AC_LANG_CXX_CONFIG],	[AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])])
+m4_ifndef([_LT_AC_LANG_F77_CONFIG],	[AC_DEFUN([_LT_AC_LANG_F77_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])])
+m4_ifndef([_LT_AC_LANG_GCJ_CONFIG],	[AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])])
+m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])])
+m4_ifndef([_LT_AC_LANG_RC_CONFIG],	[AC_DEFUN([_LT_AC_LANG_RC_CONFIG])])
+m4_ifndef([AC_LIBTOOL_CONFIG],		[AC_DEFUN([AC_LIBTOOL_CONFIG])])
+m4_ifndef([_LT_AC_FILE_LTDLL_C],	[AC_DEFUN([_LT_AC_FILE_LTDLL_C])])
Index: /issm/trunk-jpl-damage/m4/matlab.m4
===================================================================
--- /issm/trunk-jpl-damage/m4/matlab.m4	(revision 11330)
+++ /issm/trunk-jpl-damage/m4/matlab.m4	(revision 11330)
@@ -0,0 +1,1170 @@
+##### http://autoconf-archive.cryp.to/ax_cflags_warn_all.html
+#
+# SYNOPSIS
+#
+#   AX_CFLAGS_WARN_ALL [(shellvar [,default, [A/NA]])]
+#
+# DESCRIPTION
+#
+#   Try to find a compiler option that enables most reasonable
+#   warnings. This macro is directly derived from VL_PROG_CC_WARNINGS
+#   which is split up into two AX_CFLAGS_WARN_ALL and
+#   AX_CFLAGS_WARN_ALL_ANSI
+#
+#   For the GNU CC compiler it will be -Wall (and -ansi -pedantic) The
+#   result is added to the shellvar being CFLAGS by default.
+#
+#   Currently this macro knows about GCC, Solaris C compiler, Digital
+#   Unix C compiler, C for AIX Compiler, HP-UX C compiler, IRIX C
+#   compiler, NEC SX-5 (Super-UX 10) C compiler, and Cray J90 (Unicos
+#   10.0.0.8) C compiler.
+#
+#    - $1 shell-variable-to-add-to : CFLAGS
+#    - $2 add-value-if-not-found : nothing
+#    - $3 action-if-found : add value to shellvariable
+#    - $4 action-if-not-found : nothing
+#
+# LAST MODIFICATION
+#
+#   2006-12-12
+#
+# COPYLEFT
+#
+#   Copyright (c) 2006 Guido U. Draheim <guidod@gmx.de>
+#
+#   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.
+#
+#   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.
+#
+#   As a special exception, the respective Autoconf Macro's copyright
+#   owner gives unlimited permission to copy, distribute and modify the
+#   configure scripts that are the output of Autoconf when processing
+#   the Macro. You need not follow the terms of the GNU General Public
+#   License when using or distributing such scripts, even though
+#   portions of the text of the Macro appear in them. The GNU General
+#   Public License (GPL) does govern all other use of the material that
+#   constitutes the Autoconf Macro.
+#
+#   This special exception to the GPL applies to versions of the
+#   Autoconf Macro released by the Autoconf Macro Archive. When you
+#   make and distribute a modified version of the Autoconf Macro, you
+#   may extend this special exception to the GPL to apply to your
+#   modified version as well.
+
+AC_DEFUN([AX_CFLAGS_WARN_ALL],[dnl
+AS_VAR_PUSHDEF([FLAGS],[CFLAGS])dnl
+AS_VAR_PUSHDEF([VAR],[ac_cv_cflags_warn_all])dnl
+AC_CACHE_CHECK([m4_ifval($1,$1,FLAGS) for maximum warnings],
+VAR,[VAR="no, unknown"
+ AC_LANG_SAVE
+ AC_LANG_C
+ ac_save_[]FLAGS="$[]FLAGS"
+for ac_arg dnl
+in "-pedantic  % -Wall"       dnl   GCC
+   "-xstrconst % -v"          dnl Solaris C
+   "-std1      % -verbose -w0 -warnprotos" dnl Digital Unix
+   "-qlanglvl=ansi % -qsrcmsg -qinfo=all:noppt:noppc:noobs:nocnd" dnl AIX
+   "-ansi -ansiE % -fullwarn" dnl IRIX
+   "+ESlit     % +w1"         dnl HP-UX C
+   "-Xc        % -pvctl[,]fullmsg" dnl NEC SX-5 (Super-UX 10)
+   "-h conform % -h msglevel 2" dnl Cray C (Unicos)
+   #
+do FLAGS="$ac_save_[]FLAGS "`echo $ac_arg | sed -e 's,%%.*,,' -e 's,%,,'`
+   AC_TRY_COMPILE([],[return 0;],
+   [VAR=`echo $ac_arg | sed -e 's,.*% *,,'` ; break])
+done
+ FLAGS="$ac_save_[]FLAGS"
+ AC_LANG_RESTORE
+])
+case ".$VAR" in
+     .ok|.ok,*) m4_ifvaln($3,$3) ;;
+   .|.no|.no,*) m4_ifvaln($4,$4,[m4_ifval($2,[
+        AC_RUN_LOG([: m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $2"])
+                      m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $2"])]) ;;
+   *) m4_ifvaln($3,$3,[
+   if echo " $[]m4_ifval($1,$1,FLAGS) " | grep " $VAR " 2>&1 >/dev/null
+   then AC_RUN_LOG([: m4_ifval($1,$1,FLAGS) does contain $VAR])
+   else AC_RUN_LOG([: m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $VAR"])
+                      m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $VAR"
+   fi ]) ;;
+esac
+AS_VAR_POPDEF([VAR])dnl
+AS_VAR_POPDEF([FLAGS])dnl
+])
+
+dnl the only difference - the LANG selection... and the default FLAGS
+
+AC_DEFUN([AX_CXXFLAGS_WARN_ALL],[dnl
+AS_VAR_PUSHDEF([FLAGS],[CXXFLAGS])dnl
+AS_VAR_PUSHDEF([VAR],[ac_cv_cxxflags_warn_all])dnl
+AC_CACHE_CHECK([m4_ifval($1,$1,FLAGS) for maximum warnings],
+VAR,[VAR="no, unknown"
+ AC_LANG_SAVE
+ AC_LANG_CPLUSPLUS
+ ac_save_[]FLAGS="$[]FLAGS"
+for ac_arg dnl
+in "-pedantic  % -Wall"       dnl   GCC
+   "-xstrconst % -v"          dnl Solaris C
+   "-std1      % -verbose -w0 -warnprotos" dnl Digital Unix
+   "-qlanglvl=ansi % -qsrcmsg -qinfo=all:noppt:noppc:noobs:nocnd" dnl AIX
+   "-ansi -ansiE % -fullwarn" dnl IRIX
+   "+ESlit     % +w1"         dnl HP-UX C
+   "-Xc        % -pvctl[,]fullmsg" dnl NEC SX-5 (Super-UX 10)
+   "-h conform % -h msglevel 2" dnl Cray C (Unicos)
+   #
+do FLAGS="$ac_save_[]FLAGS "`echo $ac_arg | sed -e 's,%%.*,,' -e 's,%,,'`
+   AC_TRY_COMPILE([],[return 0;],
+   [VAR=`echo $ac_arg | sed -e 's,.*% *,,'` ; break])
+done
+ FLAGS="$ac_save_[]FLAGS"
+ AC_LANG_RESTORE
+])
+case ".$VAR" in
+     .ok|.ok,*) m4_ifvaln($3,$3) ;;
+   .|.no|.no,*) m4_ifvaln($4,$4,[m4_ifval($2,[
+        AC_RUN_LOG([: m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $2"])
+                      m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $2"])]) ;;
+   *) m4_ifvaln($3,$3,[
+   if echo " $[]m4_ifval($1,$1,FLAGS) " | grep " $VAR " 2>&1 >/dev/null
+   then AC_RUN_LOG([: m4_ifval($1,$1,FLAGS) does contain $VAR])
+   else AC_RUN_LOG([: m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $VAR"])
+                      m4_ifval($1,$1,FLAGS)="$m4_ifval($1,$1,FLAGS) $VAR"
+   fi ]) ;;
+esac
+AS_VAR_POPDEF([VAR])dnl
+AS_VAR_POPDEF([FLAGS])dnl
+])
+
+dnl  implementation tactics:
+dnl   the for-argument contains a list of options. The first part of
+dnl   these does only exist to detect the compiler - usually it is
+dnl   a global option to enable -ansi or -extrawarnings. All other
+dnl   compilers will fail about it. That was needed since a lot of
+dnl   compilers will give false positives for some option-syntax
+dnl   like -Woption or -Xoption as they think of it is a pass-through
+dnl   to later compile stages or something. The "%" is used as a
+dnl   delimimiter. A non-option comment can be given after "%%" marks
+dnl   which will be shown but not added to the respective C/CXXFLAGS.
+
+
+
+
+
+
+
+
+dnl matlabdir.m4 --- define Matlab directory names.
+dnl
+dnl Copyright (C) 2002, 2003 Ralph Schleicher
+dnl
+dnl This program is free software; you can redistribute it and/or
+dnl modify it under the terms of the GNU General Public License as
+dnl published by the Free Software Foundation; either version 2,
+dnl or (at your option) any later version.
+dnl
+dnl This program is distributed in the hope that it will be useful,
+dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+dnl GNU General Public License for more details.
+dnl
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; see the file COPYING.  If not, write to
+dnl the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+dnl Boston, MA 02111-1307, USA.
+dnl
+dnl As a special exception to the GNU General Public License, if
+dnl you distribute this file as part of a program that contains a
+dnl configuration script generated by GNU Autoconf, you may include
+dnl it under the same distribution terms that you use for the rest
+dnl of that program.
+dnl
+dnl Code:
+
+# AX_MATLAB_DIR
+# -------------
+# Define Matlab directory names.
+AC_DEFUN([AX_MATLAB_DIR],
+[dnl
+AC_PREREQ([2.50])
+AC_REQUIRE([AX_MATLAB_VERSION])
+AC_REQUIRE([AC_CANONICAL_HOST])
+ax_matlab_dir="\${datadir}/matlab"
+AC_ARG_WITH([matlab-dir], AC_HELP_STRING([--with-matlab-dir=ARG], [use ARG as the top-level installation directory for Matlab files [[$(datadir)/matlab]]]),
+[case $withval in
+  yes | no)
+    AC_MSG_ERROR([invalid value '$withval' for --with-matlab-dir])
+    ;;
+  *)
+    ax_matlab_dir=$withval
+    ;;
+esac])
+AC_MSG_CHECKING([for top-level installation directory for Matlab files])
+AC_MSG_RESULT([$ax_matlab_dir])
+matlabdir=$ax_matlab_dir
+AC_SUBST([matlabdir])
+matlabverdir="\${matlabdir}/$MATLAB_VERSION"
+AC_SUBST([matlabverdir])
+matlabarchdir="\${matlabverdir}/$host"
+AC_SUBST([matlabarchdir])
+matlabprivatedir="\${matlabdir}/private"
+AC_SUBST([matlabprivatedir])
+matlabprivateverdir="\${matlabverdir}/private"
+AC_SUBST([matlabprivateverdir])
+matlabprivatearchdir="\${matlabarchdir}/private"
+AC_SUBST([matlabprivatearchdir])
+])
+
+dnl matlabdir.m4 ends here
+
+dnl matlabver.m4 --- check for Matlab version number.
+dnl
+dnl Copyright (C) 2000--2003 Ralph Schleicher
+dnl
+dnl This program is free software; you can redistribute it and/or
+dnl modify it under the terms of the GNU General Public License as
+dnl published by the Free Software Foundation; either version 2,
+dnl or (at your option) any later version.
+dnl
+dnl This program is distributed in the hope that it will be useful,
+dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+dnl GNU General Public License for more details.
+dnl
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; see the file COPYING.  If not, write to
+dnl the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+dnl Boston, MA 02111-1307, USA.
+dnl
+dnl As a special exception to the GNU General Public License, if
+dnl you distribute this file as part of a program that contains a
+dnl configuration script generated by GNU Autoconf, you may include
+dnl it under the same distribution terms that you use for the rest
+dnl of that program.
+dnl
+dnl Code:
+
+# AX_MATLAB_VERSION
+# -----------------
+# Check for Matlab version number.
+AC_DEFUN([AX_MATLAB_VERSION],
+[dnl
+AC_PREREQ([2.50])
+AC_REQUIRE([AC_PROG_CC])
+AC_REQUIRE([AX_MATLAB])
+AC_CACHE_CHECK([for Matlab version], [ax_cv_matlab_version],
+[if test "${MATLAB_VERSION+set}" = set ; then
+    ax_cv_matlab_version=$MATLAB_VERSION
+else
+    ax_cv_matlab_version=
+    # Loop over all known architectures.  The final dot covers
+    # Matlab R11 and Matlab V4 for Windows.
+    for ax_arch in alpha glnxa64 glnx86 hp700 hpux ibm_rs sgi sol2 win32 mac maci . ; do
+        for ax_exec_name in matlab$EXEEXT MATLAB ; do
+		ax_matlab_exec=$MATLAB/bin/$ax_arch/${ax_exec_name}
+		if test -f $ax_matlab_exec ; then
+	    		# For Matlab R12, the version number is stored in a
+	    		# shared library.
+	    		ax_matlab_exec_2=`find $MATLAB/bin/$ax_arch -type f -name libmwservices\* -print 2> /dev/null`
+	    		if test -n "$ax_matlab_exec_2" ; then
+				ax_cv_matlab_version=`strings $ax_matlab_exec_2 2> /dev/null | egrep '^\|build_version_\|@<:@0-9@:>@+\.@<:@0-9@:>@+\.@<:@0-9@:>@+\.@<:@0-9@:>@+' | head -1 | sed 's/^|build_version_|\(@<:@0-9@:>@*\.@<:@0-9@:>@*\).*/\1/'`
+				if test -n "$ax_cv_matlab_version" ; then
+		    			break
+				fi
+	    		fi
+	    		# For Matlab R11 and Matlab V4, the version number
+	    		# is stored in the executable program.
+	    		ax_cv_matlab_version=`strings $ax_matlab_exec 2> /dev/null | egrep '^@<:@0-9@:>@+\.@<:@0-9@:>@+\.@<:@0-9@:>@+\.@<:@0-9@:>@+' | head -1 | sed 's/^\(@<:@0-9@:>@*\.@<:@0-9@:>@*\).*/\1/'`
+	    		if test -n "$ax_cv_matlab_version" ; then
+				break
+	    		fi
+				
+				# For Matlab R2008a and more, the version number is stored in .VERSION
+				if test -f "$MATLAB/.VERSION" ; then
+					ax_cv_matlab_version=`cat $MATLAB/.VERSION`
+					if test -n "$ax_cv_matlab_version" ; then
+					break
+					fi
+				fi
+
+				#Last  hope, find version in file stored in bin/util/mex/version.txt
+				#
+				ax_cv_matlab_version=`cat $MATLAB/bin/util/mex/version.txt`
+				if test -n "$ax_cv_matlab_version" ; then
+				break
+				fi
+		fi
+    	done
+	if test -n "$ax_cv_matlab_version" ; then
+		break
+	fi
+    done
+    if test -z "$ax_cv_matlab_version" ; then
+	ax_cv_matlab_version="not found"
+    fi
+fi])
+case $ax_cv_matlab_version in
+	@<:@1-9@:>@.@<:@0-9@:>@ | @<:@1-9@:>@@<:@0-9@:>@.@<:@0-9@:>@ | @<:@1-9@:>@.@<:@1-9@:>@@<:@0-9@:>@)
+	MATLAB_VERSION=$ax_cv_matlab_version
+	MATLAB_MAJOR=`echo $MATLAB_VERSION | sed -e 's/^\(@<:@0-9@:>@*\)\.@<:@0-9@:>@*.*/\1/'`
+	MATLAB_MINOR=`echo $MATLAB_VERSION | sed -e 's/^@<:@0-9@:>@*\.\(@<:@0-9@:>@*\).*/\1/'`
+	;;
+	R2007a)
+	MATLAB_VERSION=R2007a
+	MATLAB_MAJOR=7
+	MATLAB_MINOR=4
+	;;
+	R2008a)
+	MATLAB_VERSION=R2008a
+	MATLAB_MAJOR=7
+	MATLAB_MINOR=6
+	;;
+	R2009a)
+	MATLAB_VERSION=R2009a
+	MATLAB_MAJOR=7
+	MATLAB_MINOR=8
+	;;
+	R2010a)
+	MATLAB_VERSION=R2010a
+	MATLAB_MAJOR=7
+	MATLAB_MINOR=10
+	;;
+	R2010b)
+	MATLAB_VERSION=R2010b
+	MATLAB_MAJOR=7
+	MATLAB_MINOR=11
+	;;
+	R2011a)
+	MATLAB_VERSION=R2011a
+	MATLAB_MAJOR=7
+	MATLAB_MINOR=12
+	;;
+	R2011b)
+	MATLAB_VERSION=R2011b
+	MATLAB_MAJOR=7
+	MATLAB_MINOR=13
+	;;
+
+  *)
+    if test x$ax_enable_matlab = xyes ; then
+	AC_MSG_ERROR([can not determine Matlab version number])
+    fi
+    MATLAB_VERSION=
+    MATLAB_MAJOR=
+    MATLAB_MINOR=
+    ;;
+esac
+AC_SUBST([MATLAB_VERSION])
+AC_SUBST([MATLAB_MAJOR])
+AC_SUBST([MATLAB_MINOR])
+if test x$MATLAB_VERSION != x ; then
+    AC_DEFINE_UNQUOTED([MATLAB_MAJOR], [$MATLAB_MAJOR], [Define to the Matlab major version number.])
+    AC_DEFINE_UNQUOTED([MATLAB_MINOR], [$MATLAB_MINOR], [Define to the Matlab minor version number.])
+fi
+])
+
+# AX_REQUIRE_MATLAB_VERSION([MINIMUM-VERSION])
+# --------------------------------------------
+# Check if Matlab version number is sufficient.
+AC_DEFUN([AX_REQUIRE_MATLAB_VERSION],
+[dnl
+AC_PREREQ([2.50])
+AC_REQUIRE([AX_MATLAB_VERSION])
+if test x$MATLAB_VERSION = x ; then
+    AC_MSG_ERROR([can not determine Matlab version number])
+fi
+m4_if([$1], [], [],
+[AC_MSG_CHECKING([if Matlab version is sufficient])
+ax_version='$1'
+case $ax_version in
+  @<:@1-9@:>@ | @<:@1-9@:>@@<:@0-9@:>@)
+    ax_major=$ax_version
+    ax_minor=''
+    ;;
+  @<:@1-9@:>@.@<:@0-9@:>@ | @<:@1-9@:>@@<:@0-9@:>@.@<:@0-9@:>@)
+    ax_major=`echo $ax_version | sed 's/^\(@<:@0-9@:>@*\)\.@<:@0-9@:>@*.*/\1/'`
+    ax_minor=`echo $ax_version | sed 's/^@<:@0-9@:>@*\.\(@<:@0-9@:>@*\).*/\1/'`
+    ;;
+  *)
+    AC_MSG_RESULT([failure])
+    AC_MSG_NOTICE([report this bug to the responsible package maintainer])
+    AC_MSG_ERROR([invalid Matlab version number argument to AX_REQUIRE_MATLAB_VERSION])
+    ;;
+esac
+ax_ans=yes
+if test $MATLAB_MAJOR -eq $ax_major ; then
+    if test x$ax_minor != x && test $MATLAB_MINOR -lt $ax_minor ; then
+	ax_ans=no
+    fi
+elif test $MATLAB_MAJOR -lt $ax_major ; then
+    ax_ans=no
+fi
+AC_MSG_RESULT([$ax_ans])
+if test x$ax_ans = xno ; then
+    AC_MSG_ERROR([require Matlab version $ax_version or above])
+fi])
+])
+
+dnl matlabver.m4 ends here
+
+dnl matlab.m4 --- check for Matlab.
+dnl
+dnl Copyright (C) 2000--2003 Ralph Schleicher
+dnl
+dnl This program is free software; you can redistribute it and/or
+dnl modify it under the terms of the GNU General Public License as
+dnl published by the Free Software Foundation; either version 2,
+dnl or (at your option) any later version.
+dnl
+dnl This program is distributed in the hope that it will be useful,
+dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+dnl GNU General Public License for more details.
+dnl
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; see the file COPYING.  If not, write to
+dnl the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+dnl Boston, MA 02111-1307, USA.
+dnl
+dnl As a special exception to the GNU General Public License, if
+dnl you distribute this file as part of a program that contains a
+dnl configuration script generated by GNU Autoconf, you may include
+dnl it under the same distribution terms that you use for the rest
+dnl of that program.
+dnl
+dnl Code:
+
+# AX_MATLAB
+# ---------
+# Check for Matlab.
+AC_DEFUN([AX_MATLAB],
+[dnl
+AC_PREREQ([2.50])
+ax_enable_matlab=
+AC_ARG_WITH([matlab-dir], AC_HELP_STRING([--with-matlab-dir=ARG], [check for Matlab [[yes]]]),
+[case $withval in
+  yes | no)
+    # Explicitly enable or disable Matlab but determine
+    # Matlab prefix automatically.
+    ax_enable_matlab=$withval
+    ;;
+  *)
+    # Enable Matlab and use ARG as the Matlab prefix.
+    # ARG must be an existing directory.
+    ax_enable_matlab=yes
+    MATLAB=`cd "${withval-/}" > /dev/null 2>&1 && pwd`
+    if test -z "$MATLAB" ; then
+	AC_MSG_ERROR([invalid value '$withval' for --with-matlab])
+    fi
+    ;;
+esac])
+if test x$ax_enable_matlab != xno ; then
+AC_CACHE_CHECK([for Matlab prefix], [ax_cv_matlab],
+[if test "${MATLAB+set}" = set ; then
+    ax_cv_matlab=`cd "${MATLAB-/}" > /dev/null 2>&1 && pwd`
+else
+    ax_cv_matlab=
+    IFS=${IFS= 	} ; ax_ifs=$IFS ; IFS=:
+    for ax_dir in ${PATH-/opt/bin:/usr/local/bin:/usr/bin:/bin} ; do
+	if test -z "$ax_dir" ; then
+	    ax_dir=.
+	fi
+	if test -x "$ax_dir/matlab" ; then
+	    ax_dir=`echo "$ax_dir" | sed 's,/bin$,,'`
+	    # Directory sanity check.
+	    ax_cv_matlab=`cd "${ax_dir-/}" > /dev/null 2>&1 && pwd`
+	    if test -n "$ax_cv_matlab" ; then
+		break
+	    fi
+	fi
+    done
+    IFS=$ax_ifs
+fi
+if test -z "$ax_cv_matlab" ; then
+    ax_cv_matlab="not found"
+fi])
+if test "$ax_cv_matlab" = "not found" ; then
+    unset MATLAB
+else
+    # Strip trailing dashes.
+    MATLAB=`echo "$ax_cv_matlab" | sed 's,/*$,,'`
+fi
+AC_MSG_CHECKING([whether to enable Matlab support])
+if test x$ax_enable_matlab != xno ; then
+    if test "${MATLAB+set}" = set && test -d "$MATLAB/extern/include" ; then
+	ax_enable_matlab=yes
+    elif test x$ax_enable_matlab = x ; then
+	ax_enable_matlab=no
+    else
+	# Fail if Matlab was explicitly enabled.
+	AC_MSG_RESULT([failure])
+	AC_MSG_ERROR([check your Matlab setup])
+    fi
+fi
+AC_MSG_RESULT([$ax_enable_matlab])
+if test x$ax_enable_matlab = xyes ; then
+    AC_DEFINE([HAVE_MATLAB], [1], [Define if you have Matlab.])
+fi
+fi
+AC_SUBST([MATLAB])
+])
+
+# AX_REQUIRE_MATLAB
+# -----------------
+# Like AX_MATLAB but fail if Matlab support is disabled.
+AC_DEFUN([AX_REQUIRE_MATLAB],
+[dnl
+AC_PREREQ([2.50])
+AC_REQUIRE([AX_MATLAB])
+if test x$ax_enable_matlab = xno ; then
+    AC_MSG_ERROR([can not enable Matlab support])
+fi
+])
+
+# AX_MATLAB_CONDITIONAL
+# ---------------------
+# Define Matlab conditional for GNU Automake.
+AC_DEFUN([AX_MATLAB_CONDITIONAL],
+[dnl
+AC_PREREQ([2.50])
+AC_REQUIRE([AX_MATLAB])
+AM_CONDITIONAL([MATLAB], [test x$ax_enable_matlab = xyes])
+])
+
+dnl matlab.m4 ends here
+
+dnl mex.m4 --- check for mex(1) command.
+dnl
+dnl Copyright (C) 2000--2003 Ralph Schleicher
+dnl
+dnl This program is free software; you can redistribute it and/or
+dnl modify it under the terms of the GNU General Public License as
+dnl published by the Free Software Foundation; either version 2,
+dnl or (at your option) any later version.
+dnl
+dnl This program is distributed in the hope that it will be useful,
+dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+dnl GNU General Public License for more details.
+dnl
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; see the file COPYING.  If not, write to
+dnl the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+dnl Boston, MA 02111-1307, USA.
+dnl
+dnl As a special exception to the GNU General Public License, if
+dnl you distribute this file as part of a program that contains a
+dnl configuration script generated by GNU Autoconf, you may include
+dnl it under the same distribution terms that you use for the rest
+dnl of that program.
+dnl
+dnl Code:
+
+# AX_PATH_MEX
+# -----------
+# Check for mex(1) command.
+AC_DEFUN([AX_PATH_MEX],
+[dnl
+AC_PREREQ([2.50])
+AC_REQUIRE([AX_MATLAB])
+AC_REQUIRE([AX_MEX_OPTIONS])
+AC_REQUIRE([AC_CANONICAL_HOST])
+if test "${MEX+set}" != set ; then
+    case $host_os in
+      *cygwin* | *mingw32*)
+	ax_list='mextool mex mex.bat'
+	;;
+      *)
+	ax_list='mex'
+	;;
+    esac
+    AC_PATH_PROGS([MEX], $ax_list, mex, $MATLAB/bin:$PATH)
+fi
+AC_SUBST([MEX])
+if test "${MEXFLAGS+set}" != set ; then
+    MEXFLAGS=-O
+fi
+AC_SUBST([MEXFLAGS])
+if test "${MEXLDADD+set}" != set ; then
+    MEXLDADD=
+fi
+AC_SUBST([MEXLDADD])
+])
+
+dnl mex.m4 ends here
+
+dnl mexopt.m4 --- check for MEX options file.
+dnl
+dnl Copyright (C) 2001--2003 Ralph Schleicher
+dnl
+dnl This program is free software; you can redistribute it and/or
+dnl modify it under the terms of the GNU General Public License as
+dnl published by the Free Software Foundation; either version 2,
+dnl or (at your option) any later version.
+dnl
+dnl This program is distributed in the hope that it will be useful,
+dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+dnl GNU General Public License for more details.
+dnl
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; see the file COPYING.  If not, write to
+dnl the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+dnl Boston, MA 02111-1307, USA.
+dnl
+dnl As a special exception to the GNU General Public License, if
+dnl you distribute this file as part of a program that contains a
+dnl configuration script generated by GNU Autoconf, you may include
+dnl it under the same distribution terms that you use for the rest
+dnl of that program.
+dnl
+dnl Code:
+
+# AX_MEX_OPTIONS
+# --------------
+# Check for MEX options file.
+AC_DEFUN([AX_MEX_OPTIONS],
+[dnl
+AC_PREREQ([2.50])
+mex_options=yes
+AC_ARG_WITH([mex-options], AC_HELP_STRING([--with-mex-options=ARG], [use MEX options file ARG [[standard]]]),
+[mex_options=$withval])
+AC_MSG_CHECKING([for MEX options file handling])
+case $mex_options in
+  yes)
+    AC_MSG_RESULT([standard])
+    mexopts_sh=
+    ;;
+  no)
+    AC_MSG_RESULT([disabled])
+    mexopts_sh=$ac_aux_dir/noopts.sh
+    ;;
+  *)
+    AC_MSG_RESULT([enabled])
+    mexopts_sh=$mex_options
+    ;;
+esac
+if test -n "$mexopts_sh" ; then
+    AC_MSG_CHECKING([whether MEX options file exists])
+    if test -f "$mexopts_sh" ; then
+	AC_MSG_RESULT([yes])
+	# Canonicalize file name.
+	mexopts_sh_dir=`echo "$mexopts_sh" | sed 's,[[^/]]*$,,'`
+	mexopts_sh_dir=`cd "${mexopts_sh_dir-.}" && pwd`
+	mexopts_sh_name=`echo "$mexopts_sh" | sed 's,.*/,,'`
+	mexopts_sh="$mexopts_sh_dir/$mexopts_sh_name"
+    else
+	AC_MSG_RESULT([no])
+	AC_MSG_ERROR([$mexopts_sh: no such file])
+    fi
+    MEXOPTS="-f $mexopts_sh"
+else
+    MEXOPTS=
+fi
+AC_SUBST([mexopts_sh])
+AC_SUBST([MEXOPTS])
+])
+
+dnl mexopt.m4 ends here
+
+dnl mexext.m4 --- check for MEX-file suffix.
+dnl
+dnl Copyright (C) 2000--2003 Ralph Schleicher
+dnl
+dnl This program is free software; you can redistribute it and/or
+dnl modify it under the terms of the GNU General Public License as
+dnl published by the Free Software Foundation; either version 2,
+dnl or (at your option) any later version.
+dnl
+dnl This program is distributed in the hope that it will be useful,
+dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+dnl GNU General Public License for more details.
+dnl
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; see the file COPYING.  If not, write to
+dnl the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+dnl Boston, MA 02111-1307, USA.
+dnl
+dnl As a special exception to the GNU General Public License, if
+dnl you distribute this file as part of a program that contains a
+dnl configuration script generated by GNU Autoconf, you may include
+dnl it under the same distribution terms that you use for the rest
+dnl of that program.
+dnl
+dnl Code:
+
+# AX_MEXEXT
+# ---------
+# Check for MEX-file suffix.
+AC_DEFUN([AX_MEXEXT],
+[dnl
+AC_PREREQ([2.50])
+AC_REQUIRE([AX_PATH_MEX])
+AC_CACHE_CHECK([for MEX-file suffix], [ax_cv_mexext],
+[if test "${MEXEXT+set}" = set ; then
+    ax_cv_mexext="$MEXEXT"
+else
+    if test -x ${MATLAB}/bin/mexext ; then
+      ax_cv_mexext=`${MATLAB}/bin/mexext`
+    fi
+fi
+if test "x${ax_cv_mexext}" = "x" ; then
+    echo 'mexFunction () {}' > ax_c_test.c
+    $MEX $MEXOPTS $MEXFLAGS -output ax_c_test ax_c_test.c $MEXLDADD 2> /dev/null 1>&2
+    if test -f ax_c_test.dll ; then
+	ax_cv_mexext=dll
+    elif test -f ax_c_test.mex ; then
+	ax_cv_mexext=mex
+    elif test -f ax_c_test.mexaxp ; then
+	ax_cv_mexext=mexaxp
+    elif test -f ax_c_test.mexglx ; then
+	ax_cv_mexext=mexglx
+    elif test -f ax_c_test.mexa64 ; then
+	ax_cv_mexext=mexa64
+    elif test -f ax_c_test.mexmac ; then
+	ax_cv_mexext=mexmac
+    elif test -f ax_c_test.mexmaci ; then
+	ax_cv_mexext=mexmaci
+    elif test -f ax_c_test.mexhp7 ; then
+	ax_cv_mexext=mexhp7
+    elif test -f ax_c_test.mexhpux ; then
+	ax_cv_mexext=mexhpux
+    elif test -f ax_c_test.mexrs6 ; then
+	ax_cv_mexext=mexrs6
+    elif test -f ax_c_test.mexsg ; then
+	ax_cv_mexext=mexsg
+    elif test -f ax_c_test.mexsol ; then
+	ax_cv_mexext=mexsol
+    elif test -f ax_c_test.mexs64 ; then
+	ax_cv_mexext=mexs64
+    elif test -f ax_c_test.mexw32 ; then
+	ax_cv_mexext=mexw32
+    elif test -f ax_c_test.mexw64 ; then
+	ax_cv_mexext=mexw64
+    else
+	ax_cv_mexext=unknown
+    fi
+    rm -f ax_c_test*
+fi])
+MEXEXT="$ax_cv_mexext"
+AC_SUBST([MEXEXT])
+])
+
+# AX_DOT_MEXEXT
+# -------------
+# Check for MEX-file suffix with leading dot.
+AC_DEFUN([AX_DOT_MEXEXT],
+[dnl
+AC_REQUIRE([AX_MEXEXT])
+case $MEXEXT in
+  .*)
+    ;;
+  unknown)
+    ;;
+  *)
+    if test -n "$MEXEXT" ; then
+	MEXEXT=.$MEXEXT
+	AC_MSG_RESULT([setting MEX-file suffix to $MEXEXT])
+	AC_SUBST([MEXEXT])
+    fi
+    ;;
+esac
+])
+
+dnl mexext.m4 ends here
+
+dnl ccmex.m4 --- check how to compile c programs using mex
+dnl
+dnl Copyright (C) 2007 Duncan Brown
+dnl
+dnl This program is free software; you can redistribute it and/or
+dnl modify it under the terms of the GNU General Public License as
+dnl published by the Free Software Foundation; either version 2,
+dnl or (at your option) any later version.
+dnl
+dnl This program is distributed in the hope that it will be useful,
+dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+dnl GNU General Public License for more details.
+dnl
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; see the file COPYING.  If not, write to
+dnl the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+dnl Boston, MA 02111-1307, USA.
+dnl
+dnl As a special exception to the GNU General Public License, if
+dnl you distribute this file as part of a program that contains a
+dnl configuration script generated by GNU Autoconf, you may include
+dnl it under the same distribution terms that you use for the rest
+dnl of that program.
+dnl
+dnl Code:    
+
+# AX_CC_MEX
+# ------------
+# Check for the flags needed to build a file with mex
+AC_DEFUN([AX_CC_MEX],
+[dnl
+AC_REQUIRE([AX_PATH_MEX])
+AC_REQUIRE([AX_DOT_MEXEXT])
+AC_LANG([C])
+
+dnl Source code for the test matlab C program
+ac_mex_source='[#include "mex.h"
+void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { return; }]'
+
+dnl Check that the test C program can be compiled with mex
+ac_exeext_save=$ac_exeext
+ac_exeext=$MEXEXT
+ac_link_save=$ac_link
+ac_link='$MEX $MEXOPTS $MEXFLAGS -output conftest$ac_exeext conftest.$ac_ext $MEXLDADD >&AS_MESSAGE_LOG_FD'
+AC_MSG_CHECKING([if mex works])
+AC_LINK_IFELSE([AC_LANG_SOURCE($ac_mex_source)],
+[AC_MSG_RESULT([yes])],
+[AC_MSG_RESULT([no])])
+
+dnl Try to figure out how mex compiles a C program
+ax_cv_mex_version=
+ac_cv_mex_cppflags=
+ac_cv_mex_includes=
+ac_cv_mex_cflags=
+ac_cv_mex_libs=
+ac_cv_mex_ldflags=
+
+dnl Variable that will be subsituted
+MEX_VERSION_C=
+MEX_LDFLAGS=
+MEX_CPPFLAGS=
+MEX_INCLUDES=
+MEX_CFLAGS=
+MEX_LIBS=
+MEX_LDFLAGS=
+
+AC_MSG_CHECKING([if mex -n works])
+ac_save_MEXOPTS=$MEXOPTS
+MEXOPTS="-n $MEXOPTS"
+AC_LANG_CONFTEST([AC_LANG_SOURCE($ac_mex_source)])
+(eval echo $as_me:__oline__: \"$ac_link\") >&AS_MESSAGE_LOG_FD
+ac_cv_mex_n_output=`eval $ac_link AS_MESSAGE_LOG_FD>&1 2>&1`
+ac_cv_mex_n_result=$?
+echo "$ac_cv_mex_n_output" >&AS_MESSAGE_LOG_FD
+MEXOPTS=$ac_save_MEXOPTS
+rm -f conftest*
+ac_exeext=$ac_exeext_save
+ac_link=$ac_link_save
+
+if test $ac_cv_mex_n_result -eq 0 ; then
+  ac_cv_mex_working=yes
+  AC_MSG_RESULT([$ac_cv_mex_working])
+
+  dnl Save positional arguments (if any)
+  ac_save_positional="$[@]"
+
+  set X $ac_cv_mex_n_output
+  while test $[@%:@] != 1; do
+    shift
+      ac_arg=$[1]
+      case $ac_arg in
+        *mexversion.c)
+          ax_cv_mex_version=$ac_arg
+          ;;
+        -pthread)
+          _AC_LIST_MEMBER_IF($ac_arg, $ac_cv_mex_cppflags, ,
+            ac_cv_mex_cppflags="$ac_cv_mex_cppflags $ac_arg")
+          _AC_LIST_MEMBER_IF($ac_arg, $ac_cv_mex_cflags, ,
+            ac_cv_mex_cflags="$ac_cv_mex_cflags $ac_arg")
+          _AC_LIST_MEMBER_IF($ac_arg, $ac_cv_mex_ldflags, ,
+            ac_cv_mex_ldflags="$ac_cv_mex_ldflags $ac_arg")
+          ;;
+        -mt)
+          _AC_LIST_MEMBER_IF($ac_arg, $ac_cv_mex_cppflags, ,
+            ac_cv_mex_cppflags="$ac_cv_mex_cppflags $ac_arg")
+          _AC_LIST_MEMBER_IF($ac_arg, $ac_cv_mex_cflags, ,
+            ac_cv_mex_cflags="$ac_cv_mex_cflags $ac_arg")
+          _AC_LIST_MEMBER_IF($ac_arg, $ac_cv_mex_ldflags, ,
+            ac_cv_mex_ldflags="$ac_cv_mex_ldflags $ac_arg")
+          ;;
+        -ansi)
+          _AC_LIST_MEMBER_IF($ac_arg, $ac_cv_mex_cppflags, ,
+            ac_cv_mex_cppflags="$ac_cv_mex_cppflags $ac_arg")
+          ;;
+        -D*)
+          _AC_LIST_MEMBER_IF($ac_arg, $ac_cv_mex_cppflags, ,
+            ac_cv_mex_cppflags="$ac_cv_mex_cppflags $ac_arg")
+          ;;
+        -I*)
+          _AC_LIST_MEMBER_IF($ac_arg, $ac_cv_mex_includes, ,
+            ac_cv_mex_includes="$ac_cv_mex_includes $ac_arg")
+          ;;
+        -f* | -O* | -xO* | -xlibmil )
+          _AC_LIST_MEMBER_IF($ac_arg, $ac_cv_mex_cflags, ,
+            ac_cv_mex_cflags="$ac_cv_mex_cflags $ac_arg")
+          ;;
+        -l*)
+          _AC_LIST_MEMBER_IF($ac_arg, $ac_cv_mex_libs, ,
+            ac_cv_mex_libs="$ac_cv_mex_libs $ac_arg")
+          ;;
+        -L)
+          # When -L is seen by itself, it takes an argument
+          # We remove the space between option and argument and re-iterate
+          # unless we find an empty arg or a new option (starting with -)
+          case $[2] in
+             "" | -*);;
+             *)
+             ac_arg="$ac_arg$[2]"
+             shift; shift
+             set X $ac_arg "$[@]"
+             ;;
+           esac
+           ;;
+        -L* | -Wl,* | -shared | -bundle | -G)
+          _AC_LIST_MEMBER_IF($ac_arg, $ac_cv_mex_ldflags, ,
+            ac_cv_mex_ldflags="$ac_cv_mex_ldflags $ac_arg")
+          ;;
+        -undefined)
+          # the darwin linker undefined option takes and argument
+          ac_arg="$ac_arg $[2]"
+          shift
+          _AC_LIST_MEMBER_IF($ac_arg, $ac_cv_mex_ldflags, ,
+            ac_cv_mex_ldflags="$ac_cv_mex_ldflags $ac_arg")
+          ;;   
+          # ignore everything else
+      esac
+  done
+  
+  # restore positional arguments
+  set X $ac_save_positional; shift
+
+  MEX_VERSION_C=$ax_cv_mex_version
+
+  AC_MSG_CHECKING([for CPPFLAGS needed to build mex objects])
+  if test "x$ac_cv_mex_cppflags" = "x" ; then
+    AC_MSG_RESULT([none])
+  else
+    MEX_CPPFLAGS=`echo $ac_cv_mex_cppflags | sed 's/^[ \t]*//;s/[ \t]*$//'`
+    AC_MSG_RESULT([$MEX_CPPFLAGS])
+  fi
+  AC_MSG_CHECKING([for INCLUDES needed to build mex objects])
+  if test "x$ac_cv_mex_includes" = "x" ; then
+    AC_MSG_RESULT([none])
+  else
+    MEX_INCLUDES=`echo $ac_cv_mex_includes | sed 's/^[ \t]*//;s/[ \t]*$//'`
+    AC_MSG_RESULT([$MEX_INCLUDES])
+  fi
+  AC_MSG_CHECKING([for CFLAGS needed to build mex objects])
+  if test "x$ac_cv_mex_cflags" = "x" ; then
+    AC_MSG_RESULT([none])
+  else
+    MEX_CFLAGS=`echo $ac_cv_mex_cflags | sed 's/^[ \t]*//;s/[ \t]*$//'`
+    AC_MSG_RESULT([$MEX_CFLAGS])
+  fi
+  AC_MSG_CHECKING([for LIBS needed to build mex objects])
+  if test "x$ac_cv_mex_libs" = "x" ; then
+    AC_MSG_RESULT([none])
+  else
+    MEX_LIBS=`echo $ac_cv_mex_libs | sed 's/^[ \t]*//;s/[ \t]*$//'`
+    AC_MSG_RESULT([$MEX_LIBS])
+  fi
+  AC_MSG_CHECKING([for LDFLAGS needed to build mex objects])
+  if test "x$ac_cv_mex_ldflags" = "x" ; then
+    AC_MSG_RESULT([none])
+  else
+    MEX_LDFLAGS=`echo $ac_cv_mex_ldflags | sed 's/^[ \t]*//;s/[ \t]*$//'`
+    AC_MSG_RESULT([$MEX_LDFLAGS])
+  fi
+else
+  ac_cv_mex_working=no
+  AC_MSG_RESULT([$ac_cv_mex_working])
+fi
+
+AC_SUBST(MEX_VERSION_C)
+AC_SUBST(MEX_CPPFLAGS)
+AC_SUBST(MEX_INCLUDES)
+AC_SUBST(MEX_CFLAGS)
+AC_SUBST(MEX_LIBS)
+AC_SUBST(MEX_LDFLAGS)
+
+])
+
+# AX_MEX_CONDITIONAL
+# ---------------------
+# Define Matlab conditional for GNU Automake.
+AC_DEFUN([AX_MEX_CONDITIONAL],
+[dnl
+AC_PREREQ([2.50])
+AC_REQUIRE([AX_CC_MEX])
+AM_CONDITIONAL(MEX, test x$ac_cv_mex_working = xyes)
+AM_CONDITIONAL(MEX_VERSION_C, test x$ax_cv_mex_version != x)
+])
+
+dnl ccmex.m4 ends here
+
+# AX_MATLAB_SYS_ZLIB
+# ------------
+# Matlab preloads an old version of zlib which means that we cannot
+# just dynamically link against the libz.so found by the linker.
+# Instead we search for a working version of zlib in the system 
+# location and use that.
+AC_DEFUN([AX_MATLAB_SYS_ZLIB],
+[dnl
+AC_REQUIRE([AX_PATH_MEX])
+AC_LANG([C])
+
+ax_matlab_sys_zlib=
+
+if test x$ax_cv_mexext != xunknown && test x$ax_cv_mexext != x ; then
+  # Where should we search for libraries
+  ax_sys_lib_search_path="/lib /usr/lib /usr/local/lib"
+
+  # If this is a 64 bit link box look in the place where redhat keeps libs
+  if test x$ax_cv_mexext = xmexa64; then
+    ax_sys_lib_search_path="/lib64 /usr/lib64 /usr/local/lib64 $ax_sys_lib_search_path"
+  fi
+
+  # set the extension of the library we are looking for
+  if test x$ax_cv_mexext = xmexmac || test x$ax_cv_mexext = xmexmaci ; then
+    ax_zlib_lib_ext=".dylib"
+  else
+    ax_zlib_lib_ext=".a"
+  fi
+
+  for lib_path in $ax_sys_lib_search_path ; do
+    ax_matlab_search_zlib=$lib_path/libz$ax_zlib_lib_ext
+
+   AC_CHECK_FILE([$ax_matlab_search_zlib],
+     [
+       AC_MSG_CHECKING([for gzungetc in $ax_matlab_search_zlib])
+       ac_save_LIBS=$LIBS
+       LIBS="$ax_matlab_search_zlib $LIBS"
+       AC_LINK_IFELSE(
+         [ AC_LANG_PROGRAM( ,[[gzungetc();]]) ],
+         [ 
+           AC_MSG_RESULT([yes]) 
+           ax_matlab_sys_zlib=$ax_matlab_search_zlib
+         ],
+         [ AC_MSG_RESULT([no]) ]
+       )
+       LIBS=$ac_save_LIBS
+     ], )
+    
+    if test x$ax_matlab_sys_zlib != x ; then
+      break
+    fi
+  done
+fi
+
+MATLAB_SYS_ZIB=$ax_matlab_sys_zlib
+
+AC_SUBST([MATLAB_SYS_ZIB])
+
+])
+
+
+##### http://autoconf-archive.cryp.to/check_zlib.html
+#
+# SYNOPSIS
+#
+#   CHECK_ZLIB()
+#
+# DESCRIPTION
+#
+#   This macro searches for an installed zlib library. If nothing was
+#   specified when calling configure, it searches first in /usr/local
+#   and then in /usr. If the --with-zlib=DIR is specified, it will try
+#   to find it in DIR/include/zlib.h and DIR/lib/libz.a. If
+#   --without-zlib is specified, the library is not searched at all.
+#
+#   If either the header file (zlib.h) or the library (libz) is not
+#   found, the configuration exits on error, asking for a valid zlib
+#   installation directory or --without-zlib.
+#
+#   The macro defines the symbol HAVE_LIBZ if the library is found. You
+#   should use autoheader to include a definition for this symbol in a
+#   config.h file. Sample usage in a C/C++ source is as follows:
+#
+#     #ifdef HAVE_LIBZ
+#     #include <zlib.h>
+#     #endif /* HAVE_LIBZ */
+#
+# LAST MODIFICATION
+#
+#   2004-09-20
+#
+# COPYLEFT
+#
+#   Copyright (c) 2004 Loic Dachary <loic@senga.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 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, write to the Free Software
+#   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+#   02111-1307, USA.
+#
+#   As a special exception, the respective Autoconf Macro's copyright
+#   owner gives unlimited permission to copy, distribute and modify the
+#   configure scripts that are the output of Autoconf when processing
+#   the Macro. You need not follow the terms of the GNU General Public
+#   License when using or distributing such scripts, even though
+#   portions of the text of the Macro appear in them. The GNU General
+#   Public License (GPL) does govern all other use of the material that
+#   constitutes the Autoconf Macro.
+#
+#   This special exception to the GPL applies to versions of the
+#   Autoconf Macro released by the Autoconf Macro Archive. When you
+#   make and distribute a modified version of the Autoconf Macro, you
+#   may extend this special exception to the GPL to apply to your
+#   modified version as well.
+
+AC_DEFUN([CHECK_ZLIB], [
+AC_ARG_WITH([zlib], [AS_HELP_STRING([--with-zlib=DIR], [root directory path of zlib installation (defaults to /usr/local or /usr if not found in /usr/local), --without-zlib to disable zlib usage completely])], [], [with_zlib=yes])
+
+if test "x$with_zlib" != xno ; then
+  if test "x$with_zlib" != xyes ; then
+    ZLIB_HOME=$with_zlib
+  else
+    # default locations
+    ZLIB_HOME=/usr/local
+    if test ! -f "${ZLIB_HOME}/include/zlib.h"
+    then
+      ZLIB_HOME=/usr
+    fi
+  fi
+
+  ZLIB_OLD_LDFLAGS=$LDFLAGS
+  ZLIB_OLD_CPPFLAGS=$LDFLAGS
+  LDFLAGS="$LDFLAGS -L${ZLIB_HOME}/lib"
+  CPPFLAGS="$CPPFLAGS -I${ZLIB_HOME}/include"
+  AC_LANG_PUSH([C])
+  AC_CHECK_HEADERS([zlib.h])
+  AC_CHECK_LIB([z], [inflateEnd])
+  AC_LANG_POP([C])
+
+  if test "x$ac_cv_header_zlib_h" = "xyes" -a "x$ac_cv_lib_z_inflateEnd" = "xyes" ; then
+    AC_MSG_RESULT([zlib found in $ZLIB_HOME])
+    AC_SUBST([HAVE_LIBZ], [$ac_cv_lib_z_inflateEnd])
+  else
+    LDFLAGS="$ZLIB_OLD_LDFLAGS"
+    CPPFLAGS="$ZLIB_OLD_CPPFLAGS"
+    AC_MSG_ERROR(either specify a valid zlib installation with --with-zlib=DIR or disable zlib usage with --without-zlib)
+  fi
+fi])
Index: /issm/trunk-jpl-damage/missing
===================================================================
--- /issm/trunk-jpl-damage/missing	(revision 11330)
+++ /issm/trunk-jpl-damage/missing	(revision 11330)
@@ -0,0 +1,367 @@
+#! /bin/sh
+# Common stub for a few missing GNU programs while installing.
+
+scriptversion=2006-05-10.23
+
+# Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2005, 2006
+#   Free Software Foundation, Inc.
+# Originally by Fran,cois Pinard <pinard@iro.umontreal.ca>, 1996.
+
+# 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, 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, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301, USA.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+if test $# -eq 0; then
+  echo 1>&2 "Try \`$0 --help' for more information"
+  exit 1
+fi
+
+run=:
+sed_output='s/.* --output[ =]\([^ ]*\).*/\1/p'
+sed_minuso='s/.* -o \([^ ]*\).*/\1/p'
+
+# In the cases where this matters, `missing' is being run in the
+# srcdir already.
+if test -f configure.ac; then
+  configure_ac=configure.ac
+else
+  configure_ac=configure.in
+fi
+
+msg="missing on your system"
+
+case $1 in
+--run)
+  # Try to run requested program, and just exit if it succeeds.
+  run=
+  shift
+  "$@" && exit 0
+  # Exit code 63 means version mismatch.  This often happens
+  # when the user try to use an ancient version of a tool on
+  # a file that requires a minimum version.  In this case we
+  # we should proceed has if the program had been absent, or
+  # if --run hadn't been passed.
+  if test $? = 63; then
+    run=:
+    msg="probably too old"
+  fi
+  ;;
+
+  -h|--h|--he|--hel|--help)
+    echo "\
+$0 [OPTION]... PROGRAM [ARGUMENT]...
+
+Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an
+error status if there is no known handling for PROGRAM.
+
+Options:
+  -h, --help      display this help and exit
+  -v, --version   output version information and exit
+  --run           try to run the given command, and emulate it if it fails
+
+Supported PROGRAM values:
+  aclocal      touch file \`aclocal.m4'
+  autoconf     touch file \`configure'
+  autoheader   touch file \`config.h.in'
+  autom4te     touch the output file, or create a stub one
+  automake     touch all \`Makefile.in' files
+  bison        create \`y.tab.[ch]', if possible, from existing .[ch]
+  flex         create \`lex.yy.c', if possible, from existing .c
+  help2man     touch the output file
+  lex          create \`lex.yy.c', if possible, from existing .c
+  makeinfo     touch the output file
+  tar          try tar, gnutar, gtar, then tar without non-portable flags
+  yacc         create \`y.tab.[ch]', if possible, from existing .[ch]
+
+Send bug reports to <bug-automake@gnu.org>."
+    exit $?
+    ;;
+
+  -v|--v|--ve|--ver|--vers|--versi|--versio|--version)
+    echo "missing $scriptversion (GNU Automake)"
+    exit $?
+    ;;
+
+  -*)
+    echo 1>&2 "$0: Unknown \`$1' option"
+    echo 1>&2 "Try \`$0 --help' for more information"
+    exit 1
+    ;;
+
+esac
+
+# Now exit if we have it, but it failed.  Also exit now if we
+# don't have it and --version was passed (most likely to detect
+# the program).
+case $1 in
+  lex|yacc)
+    # Not GNU programs, they don't have --version.
+    ;;
+
+  tar)
+    if test -n "$run"; then
+       echo 1>&2 "ERROR: \`tar' requires --run"
+       exit 1
+    elif test "x$2" = "x--version" || test "x$2" = "x--help"; then
+       exit 1
+    fi
+    ;;
+
+  *)
+    if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+       # We have it, but it failed.
+       exit 1
+    elif test "x$2" = "x--version" || test "x$2" = "x--help"; then
+       # Could not run --version or --help.  This is probably someone
+       # running `$TOOL --version' or `$TOOL --help' to check whether
+       # $TOOL exists and not knowing $TOOL uses missing.
+       exit 1
+    fi
+    ;;
+esac
+
+# If it does not exist, or fails to run (possibly an outdated version),
+# try to emulate it.
+case $1 in
+  aclocal*)
+    echo 1>&2 "\
+WARNING: \`$1' is $msg.  You should only need it if
+         you modified \`acinclude.m4' or \`${configure_ac}'.  You might want
+         to install the \`Automake' and \`Perl' packages.  Grab them from
+         any GNU archive site."
+    touch aclocal.m4
+    ;;
+
+  autoconf)
+    echo 1>&2 "\
+WARNING: \`$1' is $msg.  You should only need it if
+         you modified \`${configure_ac}'.  You might want to install the
+         \`Autoconf' and \`GNU m4' packages.  Grab them from any GNU
+         archive site."
+    touch configure
+    ;;
+
+  autoheader)
+    echo 1>&2 "\
+WARNING: \`$1' is $msg.  You should only need it if
+         you modified \`acconfig.h' or \`${configure_ac}'.  You might want
+         to install the \`Autoconf' and \`GNU m4' packages.  Grab them
+         from any GNU archive site."
+    files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}`
+    test -z "$files" && files="config.h"
+    touch_files=
+    for f in $files; do
+      case $f in
+      *:*) touch_files="$touch_files "`echo "$f" |
+				       sed -e 's/^[^:]*://' -e 's/:.*//'`;;
+      *) touch_files="$touch_files $f.in";;
+      esac
+    done
+    touch $touch_files
+    ;;
+
+  automake*)
+    echo 1>&2 "\
+WARNING: \`$1' is $msg.  You should only need it if
+         you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'.
+         You might want to install the \`Automake' and \`Perl' packages.
+         Grab them from any GNU archive site."
+    find . -type f -name Makefile.am -print |
+	   sed 's/\.am$/.in/' |
+	   while read f; do touch "$f"; done
+    ;;
+
+  autom4te)
+    echo 1>&2 "\
+WARNING: \`$1' is needed, but is $msg.
+         You might have modified some files without having the
+         proper tools for further handling them.
+         You can get \`$1' as part of \`Autoconf' from any GNU
+         archive site."
+
+    file=`echo "$*" | sed -n "$sed_output"`
+    test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"`
+    if test -f "$file"; then
+	touch $file
+    else
+	test -z "$file" || exec >$file
+	echo "#! /bin/sh"
+	echo "# Created by GNU Automake missing as a replacement of"
+	echo "#  $ $@"
+	echo "exit 0"
+	chmod +x $file
+	exit 1
+    fi
+    ;;
+
+  bison|yacc)
+    echo 1>&2 "\
+WARNING: \`$1' $msg.  You should only need it if
+         you modified a \`.y' file.  You may need the \`Bison' package
+         in order for those modifications to take effect.  You can get
+         \`Bison' from any GNU archive site."
+    rm -f y.tab.c y.tab.h
+    if test $# -ne 1; then
+        eval LASTARG="\${$#}"
+	case $LASTARG in
+	*.y)
+	    SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'`
+	    if test -f "$SRCFILE"; then
+	         cp "$SRCFILE" y.tab.c
+	    fi
+	    SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'`
+	    if test -f "$SRCFILE"; then
+	         cp "$SRCFILE" y.tab.h
+	    fi
+	  ;;
+	esac
+    fi
+    if test ! -f y.tab.h; then
+	echo >y.tab.h
+    fi
+    if test ! -f y.tab.c; then
+	echo 'main() { return 0; }' >y.tab.c
+    fi
+    ;;
+
+  lex|flex)
+    echo 1>&2 "\
+WARNING: \`$1' is $msg.  You should only need it if
+         you modified a \`.l' file.  You may need the \`Flex' package
+         in order for those modifications to take effect.  You can get
+         \`Flex' from any GNU archive site."
+    rm -f lex.yy.c
+    if test $# -ne 1; then
+        eval LASTARG="\${$#}"
+	case $LASTARG in
+	*.l)
+	    SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'`
+	    if test -f "$SRCFILE"; then
+	         cp "$SRCFILE" lex.yy.c
+	    fi
+	  ;;
+	esac
+    fi
+    if test ! -f lex.yy.c; then
+	echo 'main() { return 0; }' >lex.yy.c
+    fi
+    ;;
+
+  help2man)
+    echo 1>&2 "\
+WARNING: \`$1' is $msg.  You should only need it if
+	 you modified a dependency of a manual page.  You may need the
+	 \`Help2man' package in order for those modifications to take
+	 effect.  You can get \`Help2man' from any GNU archive site."
+
+    file=`echo "$*" | sed -n "$sed_output"`
+    test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"`
+    if test -f "$file"; then
+	touch $file
+    else
+	test -z "$file" || exec >$file
+	echo ".ab help2man is required to generate this page"
+	exit 1
+    fi
+    ;;
+
+  makeinfo)
+    echo 1>&2 "\
+WARNING: \`$1' is $msg.  You should only need it if
+         you modified a \`.texi' or \`.texinfo' file, or any other file
+         indirectly affecting the aspect of the manual.  The spurious
+         call might also be the consequence of using a buggy \`make' (AIX,
+         DU, IRIX).  You might want to install the \`Texinfo' package or
+         the \`GNU make' package.  Grab either from any GNU archive site."
+    # The file to touch is that specified with -o ...
+    file=`echo "$*" | sed -n "$sed_output"`
+    test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"`
+    if test -z "$file"; then
+      # ... or it is the one specified with @setfilename ...
+      infile=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'`
+      file=`sed -n '
+	/^@setfilename/{
+	  s/.* \([^ ]*\) *$/\1/
+	  p
+	  q
+	}' $infile`
+      # ... or it is derived from the source name (dir/f.texi becomes f.info)
+      test -z "$file" && file=`echo "$infile" | sed 's,.*/,,;s,.[^.]*$,,'`.info
+    fi
+    # If the file does not exist, the user really needs makeinfo;
+    # let's fail without touching anything.
+    test -f $file || exit 1
+    touch $file
+    ;;
+
+  tar)
+    shift
+
+    # We have already tried tar in the generic part.
+    # Look for gnutar/gtar before invocation to avoid ugly error
+    # messages.
+    if (gnutar --version > /dev/null 2>&1); then
+       gnutar "$@" && exit 0
+    fi
+    if (gtar --version > /dev/null 2>&1); then
+       gtar "$@" && exit 0
+    fi
+    firstarg="$1"
+    if shift; then
+	case $firstarg in
+	*o*)
+	    firstarg=`echo "$firstarg" | sed s/o//`
+	    tar "$firstarg" "$@" && exit 0
+	    ;;
+	esac
+	case $firstarg in
+	*h*)
+	    firstarg=`echo "$firstarg" | sed s/h//`
+	    tar "$firstarg" "$@" && exit 0
+	    ;;
+	esac
+    fi
+
+    echo 1>&2 "\
+WARNING: I can't seem to be able to run \`tar' with the given arguments.
+         You may want to install GNU tar or Free paxutils, or check the
+         command line arguments."
+    exit 1
+    ;;
+
+  *)
+    echo 1>&2 "\
+WARNING: \`$1' is needed, and is $msg.
+         You might have modified some files without having the
+         proper tools for further handling them.  Check the \`README' file,
+         it often tells you about the needed prerequisites for installing
+         this package.  You may also peek at any GNU archive site, in case
+         some other package would contain this missing \`$1' program."
+    exit 1
+    ;;
+esac
+
+exit 0
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-end: "$"
+# End:
Index: /issm/trunk-jpl-damage/scripts/GenerateReferences.sh
===================================================================
--- /issm/trunk-jpl-damage/scripts/GenerateReferences.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/GenerateReferences.sh	(revision 11330)
@@ -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{$ISSM_DIR/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_TIER/externalpackages/latex2rtf/install/latex2rtf -P $ISSM_TIER/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/trunk-jpl-damage/scripts/Update.sh
===================================================================
--- /issm/trunk-jpl-damage/scripts/Update.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/Update.sh	(revision 11330)
@@ -0,0 +1,98 @@
+#!/bin/bash
+FILE=$1
+if [ $# -ne 1 ];
+then
+	echo "Usage: ./Update.sh filename "  1>&2
+	exit 1
+fi
+if [ ! -f $FILE ]; then
+	echo "File $FILE does not exist or is empty. Exiting."  1>&2
+	exit 1
+fi
+
+cat $FILE | sed -e "s/md\.name/md.miscellaneous.name/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.spcvx/md.diagnostic.spcvx/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.spcvy/md.diagnostic.spcvy/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.spcvz/md.diagnostic.spcvz/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.spctemperature/md.thermal.spctemperature/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.spcthickness/md.balancethickness.spcthickness/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.bamg/md.private.bamg/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.numberofgrids/md.mesh.numberofvertices/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.vx_obs/md.inversion.vx_obs/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.vy_obs/md.inversion.vy_obs/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.vel_obs/md.inversion.vel_obs/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.vx/md.initialization.vx/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.vy/md.initialization.vy/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.vz/md.initialization.vz/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.vel/md.initialization.vel/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.temperature/md.initialization.temperature/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.pressure/md.initialization.pressure/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.thickness_obs/md.inversion.thickness_obs/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.thickness/md.geometry.thickness/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.bed/md.geometry.bed/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.bathymetry/md.geometry.bathymetry/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.surface_mass_balance/md.surfaceforcings.mass_balance/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.surface=/md.geometry.surface=/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.surface /md.geometry.surface /g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.surface,/md.geometry.surface,/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.surface;/md.geometry.surface;/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.x/md.mesh.x/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.yts/md.constants.yts/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.y/md.mesh.y/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.z/md.mesh.z/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.lat/md.mesh.lat/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.long/md.mesh.long/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.hemisphere/md.mesh.hemisphere/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.numberofnodes/md.mesh.numberofvertices/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.numberofelements/md.mesh.numberofelements/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.drag_coefficient/md.friction.coefficient/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.drag_p/md.friction.p/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.drag_q/md.friction.q/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/setelementstype/setflowequation/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/geography(md/setmask(md/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.rheology_B/md.materials.rheology_B/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.rho_ice/md.materials.rho_ice/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.rho_water/md.materials.rho_water/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.nodeonbed/md.mesh.vertexonbed/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.nodeonboundary/md.mesh.vertexonboundary/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.petscoptions/md.solver/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.dhdt/md.balancethickness.thickening_rate/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.eps_rel/md.diagnostic.reltol/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.eps_res/md.diagnostic.restol/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.eps_abs/md.diagnostic.abstol/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.eps_cm/md.inversion.cost_function_threshold/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.cm_responses/md.inversion.cost_functions/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.nsteps/md.inversion.nsteps/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.weights/md.inversion.cost_functions_coefficients/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.optscal/md.inversion.gradient_scaling/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.cm_jump/md.inversion.step_threshold/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.control_type/md.inversion.control_parameters/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.waitonlock/md.settings.waitonlock/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.cm_min/md.inversion.min_parameters/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.cm_max/md.inversion.max_parameters/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.maxiter/md.inversion.maxiter_per_step/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.control_type/md.inversion.control_parameters/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.control_type/md.inversion.control_parameters/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.min_thermal_constraints/md.thermal.penalty_threshold/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.control_analysis/md.inversion.iscontrol/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/SurfaceAbsVelMisfitEnum/101/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/SurfaceRelVelMisfitEnum/102/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/SurfaceLogVelMisfitEnum/103/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/SurfaceLogVxVyMisfitEnum/104/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/SurfaceAverageVelMisfitEnum/105/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/ThicknessAbsMisfitEnum/201/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/DragCoefficientAbsGradientEnum/501/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/RheologyBbarAbsGradientEnum/502/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/ThicknessAbsGradientEnum/503/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/DragCoefficientEnum/{'FrictionCoefficient'}/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.elementoniceshelf/md.mask.elementonfloatingice/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.nodeoniceshelf/md.mask.vertexonfloatingice/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.elementonicesheet/md.mask.elementongroundedice/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.nodeonicesheet/md.mask.vertexongroundedice/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.elements/md.mesh.elements/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.rheology_n/md.materials.rheology_n/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.gl_migration/md.groundingline.migration/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.hydrostatic_adjustment/md.prognostic.hydrostatic_adjustment/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.rheology_law/md.materials.rheology_law/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.basal_melting_rate/md.basalforcings.melting_rate/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
+cat $FILE | sed -e "s/md\.geothermalflux/md.basalforcings.geothermalflux/g" > $FILE$$.bak && mv $FILE$$.bak $FILE
Index: /issm/trunk-jpl-damage/scripts/archive.sh
===================================================================
--- /issm/trunk-jpl-damage/scripts/archive.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/archive.sh	(revision 11330)
@@ -0,0 +1,22 @@
+#!/bin/bash
+#This bash routine  will create a tar file for the ISSM
+#code. Just run the following command: 
+
+#Some local script functions 
+function today_date {
+suffix=`date | awk '{printf("%s-%s-%s",$2,$3,$6);}'` 
+echo $suffix;
+}
+
+#Cleanup code 
+cd $ISSM_TIER
+make clean
+make distclean
+
+#Get rid of externalpackages
+rm -rf externalpackages
+
+#Create tar file, with today's date in the title;
+cd $ISSM_TIER/..
+today=`today_date`
+tar zcvf issm-3.0-$today.tar.gz  `basename $ISSM_TIER`
Index: /issm/trunk-jpl-damage/scripts/automakererun.sh
===================================================================
--- /issm/trunk-jpl-damage/scripts/automakererun.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/automakererun.sh	(revision 11330)
@@ -0,0 +1,41 @@
+#!/bin/sh
+#  this shell script will automatically reconfigure the entire ISSM 
+#  archive.
+
+
+ ACLOCAL="$ISSM_TIER/externalpackages/automake/install/bin/aclocal"
+AUTOCONF="$ISSM_TIER/externalpackages/autoconf/install/bin/autoconf"
+AUTOHEAD="$ISSM_TIER/externalpackages/autoconf/install/bin/autoheader"
+AUTOMAKE="$ISSM_TIER/externalpackages/automake/install/bin/automake"
+
+echo "removing config.cach"
+rm -rf config.cach
+rm -rf aclocal.m4
+
+if [ ! -f "$ACLOCAL" ]
+then echo "issm aclocal not found, calling default aclocal" 
+	aclocal -I m4
+else echo "Calling aclocal" 
+	$ACLOCAL -I m4
+fi
+
+if [ ! -f "$AUTOCONF" ]
+then echo "issm autoconf not found, calling default aclocal" 
+	autoconf
+else echo "Calling autoconf" 
+	$AUTOCONF
+fi
+
+if [ ! -f "$AUTOHEAD" ]
+then echo "issm autoheader not found, calling default aclocal" 
+	autoheader
+else echo "Calling autoheader" 
+	$AUTOHEAD
+fi
+
+if [ ! -f "$AUTOMAKE" ]
+then echo "issm automake  not found, calling default aclocal" 
+	automake
+else echo "Calling automake " 
+	$AUTOMAKE -a
+fi
Index: /issm/trunk-jpl-damage/scripts/cloc-1.55.pl
===================================================================
--- /issm/trunk-jpl-damage/scripts/cloc-1.55.pl	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/cloc-1.55.pl	(revision 11330)
@@ -0,0 +1,8264 @@
+#!/usr/bin/env perl
+# cloc -- Count Lines of Code {{{1
+# Copyright (C) 2006-2011 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
+#
+# 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
+# 1}}}
+my $VERSION = sprintf("%.2f", 1.55);
+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";
+}
+
+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 };
+# 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 = 1;  # make Cygwin look like Unix
+    } else {
+        $ON_WINDOWS = 0;  # MKS defines $SHELL but still acts like Windows
+    }
+}
+
+my $NN     = chr(27) . "[0m";  # normal
+   $NN     = "" if $ON_WINDOWS;
+my $BB     = chr(27) . "[1m";  # bold
+   $BB     = "" if $ON_WINDOWS;
+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: 
+                               --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.
+   --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.
+   --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.
+   --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 from <file> the language processing filters.
+                             (see also --write-lang-def) then use these filters
+                             instead of the built-in filters.
+   --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).
+   --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.
+
+ ${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 .cvs 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-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.
+   --match-d=<regex>         Only count files in directories matching the Perl 
+                             regex.  For example
+                               --match-d=/src/
+                             only counts files in directories containing
+                             /src/
+   --not-match-d=<regex>     Count all files except those in directories
+                             matching the Perl regex.
+   --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.
+   -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 --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.
+   --sql=<file>              Write results as SQL create and insert statements
+                             which can be read by a database program such as
+                             SQLite.  If <file> is 1, 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 = time();
+my (
+    $opt_categorized          ,
+    $opt_found                ,
+    @opt_force_lang           ,
+    $opt_lang_no_ext          ,
+    @opt_script_lang          ,
+    $opt_diff                 ,
+    $opt_diff_alignment       ,
+    $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_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_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              ,
+   );
+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      ,
+   "html"                                    => \$opt_html                ,
+   "ignored=s"                               => \$opt_ignored             ,
+   "quiet"                                   => \$opt_quiet               ,
+   "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                 ,
+   "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             ,
+  );
+$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 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;
+$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;
+
+# 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 "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_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, 
+                  );
+if ($opt_read_lang_def) {
+    read_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++}    = '\\$'
+        );
+} 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_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 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 = ();
+
+# 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";
+
+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 = 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;
+}
+# 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 = tempdir( CLEANUP => 1 );  # 1 = delete on exit
+        $TEMP_DIR{ $extract_dir } = 1 if $opt_sql;
+        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;
+    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 = tempdir( CLEANUP => 1 ); # 1 = delete on exit
+            $TEMP_DIR{ $extract_dir } = 1 if $opt_sql;
+            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 = tempdir( CLEANUP => 1 ); # 1 = delete on exit
+            $TEMP_DIR{ $extract_dir } = 1 if $opt_sql;
+            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;
+}
+# 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
+                   );
+    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) {
+            my $Lang = $Language{$fh[$F+$offset]}{$file};
+            my ($all_line_count,
+                $blank_count   ,
+                $comment_count ,
+               ) = call_counter($file, $Lang, \@Errors);
+            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;
+        }
+    }
+   #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) {
+#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) {
+        # 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";
+
+    push @alignment, sprintf "File pairs compared: %d\n", scalar @file_pairs
+        if $opt_diff_alignment;
+#print "Language=\n", Dumper(\%Language);
+    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;
+        }
+        if (!defined @{$Filters_by_Language{$Lang_L} } or
+            !defined @{$Filters_by_Language{$Lang_R} }
+           ) {
+            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";
+            }
+        }
+
+        # 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)
+        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;
+    }
+    write_file($opt_diff_alignment, @alignment) if $opt_diff_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 = 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, time() - $start_time,
+                            "by file",
+                            \%Delta_by_File, \%Scale_Factor);
+} else {
+    @Lines_Out = diff_report($VERSION, 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;
+    }
+    if (!defined @{$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 = 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") {
+                    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
+       ) = @_;
+
+#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 %4.2f", $URL, $version;
+    my $sum_files    = 1;
+    my $sum_lines    = 1;
+       $header_line .= sprintf("  T=%.1f 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 (sort {
+                                 $rhhh_count->{$b}{'code'} <=>
+                                 $rhhh_count->{$a}{'code'}
+                               }
+                          keys %{$rhhh_count}) {
+
+        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) = @_;
+    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 = "";
+       $report_file = "  <report_file>$opt_report_file</report_file>"
+       if $opt_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";
+        $header .= "\n  report_file        : $opt_report_file"
+            if $opt_report_file;
+    }
+    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);
+        $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 (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\" ", 
+                            $lang_or_file;
+                } 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", $lang_or_file;
+                    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;
+    }
+
+    $elapsed_sec = 0.5 unless $elapsed_sec;
+
+    my $line = "Language, ";
+       $line = "File, " if $BY_FILE;
+    foreach my $item (qw(files blank comment code)) {
+        next if $BY_FILE and $item eq 'files';
+        foreach my $symbol qw( == != + - ) {
+            $line .= "$symbol $item, ";
+        }
+    }
+    $line .= "\"$URL v $version T=$elapsed_sec s\"";
+    push @results, $line;
+
+    foreach my $lang_or_file (sort {
+                                 $rhhh_count->{$b}{'code'} <=>
+                                 $rhhh_count->{$a}{'code'}
+                               }
+                          keys %{$rhhh_count}) {
+        $line = "$lang_or_file, ";
+        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}, ";
+                } else {
+                    $line .= "0, ";
+                }
+            }
+        }
+        push @results, $line;
+    }
+
+    print "<- diff_csv_report\n" if $opt_v > 2;
+    return @results;
+} # 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.
+        foreach my $temp_d (keys %TEMP_DIR) {
+            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 \
+        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 @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;
+    } else {
+        $first_column = "Report File";
+    }
+
+    my $header_line  = sprintf "%s v %4.2f", $URL, $version;
+       $header_line .= sprintf("  T=%.1f 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);
+            $ALREADY_SHOWED_HEADER = 1;
+        }
+        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,filename";
+        } else {
+            $header2 = "files,language";
+        }
+        $header2 .= ",blank,comment,code";
+        $header2 .= ",scale,3rd gen. equiv" if $opt_3;
+        $header2 .= ',"' . $header_line . '"';
+        push @results, $header2;
+    }
+
+    my $sum_scaled = 0;
+    foreach my $lang_or_file (sort {
+                                 $rhh_count->{$b}{'code'} <=>
+                                 $rhh_count->{$a}{'code'}
+                               }
+                          keys %{$rhh_count}) {
+        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
+                $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) {
+            $data_line  = sprintf $Format{'1'}{$Style}, $lang_or_file;
+        } 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 = ",$factor,$scaled" if $opt_3;
+            my $str;
+            if ($BY_FILE) {
+                $str = $rhh_count->{$lang_or_file}{'lang'}   . ",";
+            } else {
+                $str = $rhh_count->{$lang_or_file}{'nFiles'} . ",";
+            }
+            $str .= $lang_or_file                         . "," .
+                    $rhh_count->{$lang_or_file}{'blank'}  . "," .
+                    $rhh_count->{$lang_or_file}{'comment'}. "," .
+                    $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";
+        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 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'};
+    }
+
+    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";
+            foreach my $F (different_files(\@{$files_by_size{$bytes}},
+                                            $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 variable @file_list
+    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 and $opt_v > 5) {
+        printf "files(%s)  zero size\n", $File::Find::name;
+    }
+    return unless $nBytes  ; # attempting other tests w/pipe or socket will hang
+    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)";
+
+    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}) {
+        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 'Smarty') {
+                # Smarty extension .tpl is generic; make sure the
+                # file at least roughly resembles PHP
+                if (really_is_php($full_file)) {
+                    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;
+                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)";
+        }
+        push @unique, $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 = glob($file);  # sometimes returns null string
+    }
+#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";
+    print ", $CLOC_XSL" if $opt_xsl and $opt_xsl eq $CLOC_XSL;
+    print "\n";
+    
+    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;
+        # 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);
+        } 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_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 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'             ,
+            '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'               ,
+            'awk'         => 'awk'                   ,
+            'bash'        => 'Bourne Again Shell'    ,
+            'bas'         => 'Visual Basic'          ,
+            'bat'         => 'DOS Batch'             ,
+            'BAT'         => 'DOS Batch'             ,
+            'cbl'         => 'COBOL'                 ,
+            'CBL'         => 'COBOL'                 ,
+            'c'           => 'C'                     ,
+            'C'           => 'C++'                   ,
+            'cc'          => 'C++'                   ,
+            'ccs'         => 'CCS'                   ,
+            'cfm'         => 'ColdFusion'            ,
+            'cl'          => 'Lisp'                  ,
+            'cls'         => 'Visual Basic'          ,
+            'CMakeLists.txt' => 'CMake'              ,
+            'cob'         => 'COBOL'                 ,
+            'COB'         => 'COBOL'                 ,
+            'config'      => 'ASP.Net'               ,
+            'cpp'         => 'C++'                   ,
+            'cs'          => 'C#'                    ,
+            'csh'         => 'C Shell'               ,
+            'css'         => "CSS"                   ,
+            'cxx'         => 'C++'                   ,
+            'd'           => 'D'                     ,
+            'da'          => 'DAL'                   ,
+            'dart'        => 'Dart'                  ,
+            'def'         => 'Teamcenter def'        ,
+            'dmap'        => 'NASTRAN DMAP'          ,
+            'dpr'         => 'Pascal'                ,
+            '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'                ,
+            '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'                   ,
+            'pro'         => 'IDL'                   ,
+            'ig'          => 'Modula3'               ,
+            'il'          => 'SKILL'                 ,
+            'ils'         => 'SKILL++'               ,
+            'inc'         => 'PHP/Pascal'            , # might be PHP or Pascal
+            'itk'         => 'Tcl/Tk'                ,
+            'java'        => 'Java'                  ,
+            'jcl'         => 'JCL'                   , # IBM Job Control Lang.
+            'jl'          => 'Lisp'                  ,
+            'js'          => 'Javascript'            ,
+            'jsp'         => 'JSP'                   , # Java server pages
+            'ksc'         => 'Kermit'                ,
+            'ksh'         => 'Korn Shell'            ,
+            'lhs'         => 'Haskell'               ,
+            'l'           => 'lex'                   ,
+            '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'                 , 
+            '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
+            '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'                   ,
+            'plh'         => 'Perl'                  ,
+            'pl'          => 'Perl'                  ,
+            'PL'          => 'Perl'                  ,
+            'plx'         => 'Perl'                  ,
+            'pm'          => 'Perl'                  ,
+            'p'           => 'Pascal'                ,
+            'pp'          => 'Pascal'                ,
+            'psql'        => 'SQL'                   ,
+            'py'          => 'Python'                ,
+            'pyx'         => 'Cython'                ,
+            'rb'          => 'Ruby'                  ,
+         #  'resx'        => 'ASP.Net'               ,
+            'rex'         => 'Oracle Reports'        ,
+            'rexx'        => 'Rexx'                  ,
+            'rhtml'       => 'Ruby HTML'             ,
+            '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'   ,
+            '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'              ,
+            'tcl'         => 'Tcl/Tk'                ,
+            'tcsh'        => 'C Shell'               ,
+            'tk'          => 'Tcl/Tk'                ,
+            'tpl'         => 'Smarty'                ,
+            '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'              ,
+            );
+# 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*//' ], ],
+    'Assembly'           => [  
+                                [ 'remove_matches'      , '^\s*//' ],
+                                [ 'remove_matches'      , '^\s*;'  ],
+                                [ 'call_regexp_common'  , 'C'      ], 
+                                [ 'remove_inline'       , '//.*$'  ], 
+                                [ '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'       , '//.*$'  ], 
+                            ],
+    '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',         ], ],
+    'ColdFusion'         => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], ],
+    'Crystal Reports'    => [   [ 'remove_matches'      , '^\s*//' ], ],
+    'D'                  => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ '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*;'  ], ],
+    'JSP'                => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ],
+                                [ 'remove_jsp_comments' ,          ], 
+                                [ 'remove_matches'      , '^\s*//' ],
+                                [ 'add_newlines'        ,          ],
+                                [ 'call_regexp_common'  , 'C'      ],
+                            ],
+    'Java'               => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'Javascript'         => [   
+                                [ 'remove_matches'      , '^\s*//' ], 
+                                [ 'call_regexp_common'  , 'C'      ],
+                                [ 'remove_inline'       , '//.*$'  ], 
+                            ],
+    'JCL'                => [   [ 'remove_jcl_comments' ,          ], ],
+    'Lisp'               => [   [ 'remove_matches'      , '^\s*;'  ], ],
+    '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'       , '%.*$'   ],
+                            ], 
+    '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' ], 
+                            ],
+    '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'       , '#.*$'   ],
+                            ], 
+    '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'       , '//.*$'  ],
+                            ],
+    'Rexx'               => [   [ 'call_regexp_common'  , 'C'      ], ],
+    'Ruby'               => [   
+                                [ 'remove_matches'      , '^\s*#'  ], 
+                                [ 'remove_inline'       , '#.*$'   ],
+                            ], 
+    'Ruby HTML'          => [   [ 'remove_html_comments',          ],
+                                [ 'call_regexp_common'  , 'HTML'   ], ],
+    '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
+    '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 = '
+    'yacc'               => [   [ 'call_regexp_common'  , 'C'      ], ],
+    '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'   ], ],
+    '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'         =>     '\\\\$'         ,
+    'Lua'                =>     '\\\\$'         ,
+    'make'               =>     '\\\\$'         ,
+    'MATLAB'             =>     '\.\.\.\s*$'    ,
+    'Objective C'        =>     '\\\\$'         ,
+    'Objective C++'      =>     '\\\\$'         ,
+    'Ocaml'              =>     '\\\\$'         ,
+    'Octave'             =>     '\.\.\.\s*$'    ,
+    'Patran Command Language'=> '\\\\$'         ,
+    'Python'             =>     '\\\\$'         ,
+    'Ruby'               =>     '\\\\$'         ,
+    'sed'                =>     '\\\\$'         ,
+    'Bourne Again Shell' =>     '\\\\$'         ,
+    'Bourne Shell'       =>     '\\\\$'         ,
+    'C Shell'            =>     '\\\\$'         ,
+    'Kermit'             =>     '\\\\$'         ,
+    'Korn Shell'         =>     '\\\\$'         ,
+    'Tcl/Tk'             =>     '\\\\$'         ,
+    'lex'                =>     '\\\\$'         ,
+    );
+# 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,
+    '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,
+
+#   'assembler (basic)'            =>   0.25,
+    'Assembly'                     =>   0.25,
+
+    'Assembly (macro)'             =>   0.51,
+    'associative default'          =>   1.25,
+    'autocoder'                    =>   0.25,
+    '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,
+    '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,
+    '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,
+    '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,
+    '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,
+'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,
+    '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,
+    '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,
+    '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,
+    '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,
+    '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,
+    '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,
+    '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,
+    '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,
+    'vax acms'                     =>   1.38,
+    'vax ade'                      =>   2.00,
+    'vbscript'                     =>   2.35,
+    'vectran'                      =>   0.75,
+    '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,
+    '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,
+'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,
+);
+# 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
+            );
+# 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) {
+        # write to the user-defined scratch directory
+        $dir = $opt_sdir;
+    } else {
+        # let File::Temp create a suitable temporary directory
+        $dir = tempdir( CLEANUP => 1 );  # 1 = delete on exit
+    }
+    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) {
+        # write to the user-defined scratch directory
+        $dir = $opt_sdir;
+    } else {
+        # let File::Temp create a suitable temporary directory
+        $dir = tempdir( CLEANUP => 1 );  # 1 = delete on exit
+    }
+    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*%}) {              #   %
+            --$objective_C_points;
+            ++$matlab_points;
+            ++$mumps_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 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)]
+    #
+
+    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 = sdiff($ra_lines_L, $ra_lines_R);
+#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
+    @{$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
+        return ( basename $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 Microsoft Windows style Unicode
+    # 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
+
+    my @ascii              = ();
+    my $looks_like_unicode = 1;
+    my $length             = length $string;
+# print "length=$length\n";
+    if ($length <= 3) {
+        $looks_like_unicode = 0;
+        return '';
+    }
+    my @unicode            = split(//, $string);
+
+    for (my $i = 2; $i < $length; $i += 2) {
+# print "examining [$unicode[$i]]  ord ", ord($unicode[$i]), "\n";
+        if (32 <= ord($unicode[$i]) and ord($unicode[$i]) <= 127
+            or ord($unicode[$i]) == 13
+            or ord($unicode[$i]) == 10
+            or ord($unicode[$i]) ==  9
+            ) {
+            push @ascii, $unicode[$i];
+# print "adding [$unicode[$i]]\n";
+        } else {
+            $looks_like_unicode = 0;
+            last;
+        }
+        if ($i+1 < $length) {
+            if (!$unicode[$i+1]) {
+                $looks_like_unicode = 0;
+                last;
+            }
+        }
+    }
+    if ($looks_like_unicode) {
+        return join("", @ascii);
+    } else {
+        return '';
+    }
+} # 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 (($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$/ 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';
+        if (!$success) {
+            $success = 1 unless system "which" . " $exe" . ' >& /dev/null';
+        }
+    }
+    
+    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-Z][a-z]*/) {        # 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}}}
+# subroutines copied from SLOCCount
+my %lex_files    = ();  # really_is_lex()
+my %expect_files = ();  # really_is_expect()
+my %pascal_files = ();  # really_is_pascal(), really_is_incpascal()
+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;
+
+ # Return cached result, if available:
+ if ($pascal_files{$filename}) { return pascal_files{$filename};}
+
+ 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;}
+
+ $pascal_files{$filename} = $is_pascal; # Store result in cache.
+
+ 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)) { 
+   $pascal_files{$filename} = 1;
+   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);
+ $pascal_files{$filename} = $is_pascal; # Store result in cache.
+ 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/trunk-jpl-damage/scripts/cloc2html.py
===================================================================
--- /issm/trunk-jpl-damage/scripts/cloc2html.py	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/cloc2html.py	(revision 11330)
@@ -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_TIER=os.getenv('ISSM_TIER');
+if(not ISSM_TIER): raise NameError('ISSM_TIER 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()):
+				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/trunk-jpl-damage/scripts/convertmatlabclasses.py
===================================================================
--- /issm/trunk-jpl-damage/scripts/convertmatlabclasses.py	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/convertmatlabclasses.py	(revision 11330)
@@ -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_TIER=os.getenv('ISSM_TIER');
+if(not ISSM_TIER): raise NameError('ISSM_TIER undefined')
+newclassesdir = ISSM_TIER + '/src/m/classes/'
+oldclassesdir = ISSM_TIER + '/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/trunk-jpl-damage/scripts/dailyrun.sh
===================================================================
--- /issm/trunk-jpl-damage/scripts/dailyrun.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/dailyrun.sh	(revision 11330)
@@ -0,0 +1,164 @@
+#!/bin/bash
+#This bash script calls the dailyrun.m matlab file to run our daily test decks. 
+#It then processes the results and sends an email to the Ice developpers.
+
+#Hard coded options
+NUMCPUS_RUN=7
+NROPTIONS=""
+
+#some functions
+function timer() #{{{1
+{
+	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() #{{{1
+{
+	suffix=`date | awk '{printf("%s-%s-%s  %s",$2,$3,$6,$4);}'`			 
+	echo $suffix;			 
+} #}}}
+function host_name() #{{{1
+{
+	#return host name depending on the OS
+	if [ "$1" = "winxp32" ] 
+	then
+		HOST_NAME=`hostname`;
+	else
+		HOST_NAME=`hostname -s`;
+	fi
+	echo $HOST_NAME;
+} #}}}
+
+#Get configuration
+#Initialize variables {{{1
+TODAY=$(todaydate);
+HOST_NAME=$(host_name $OS);
+START_TIME=$(timer);
+ISSM_RELEASE="N/A"
+USER=$(whoami);
+INIT_PATH=$(pwd);
+#}}}
+
+#Prepare run
+#Windows hack for startup.m {{{1
+#windows environments: ISSM_TIER_WIN variable not correctly picked up when using 
+#the cron job. just get startup to take the ISSM_TIER variable as the pwd:
+if [ "$OS" = "winxp32" ]
+then
+	cat startup.m | sed 's/clear status/clear status; ISSM_TIER=pwd;/g' > startup.m.bak
+	mv startup.m.bak startup.m
+fi
+#}}}
+#create softlink to startup {{{1
+cd $ISSM_TIER/test/NightlyRun/
+ln -s $ISSM_TIER/startup.m .
+#}}}
+#Create dailylog directory and info.log {{{1
+#put installation elapsed time in info.log
+INSTALL_TIME=$(timer)
+ELAPSED_INSTALL=$(timer $START_TIME)
+rm -rf $ISSM_TIER/dailylog
+mkdir  $ISSM_TIER/dailylog
+cat << END > $ISSM_TIER/dailylog/info.log
+today:     $(echo $TODAY)
+user:      $(echo $USER)
+host:      $(echo $HOST_NAME)
+OS:        N/A
+release:   N/A
+init_path: $(echo $INIT_PATH)
+elapsed_install: $(echo $ELAPSED_INSTALL)
+END
+#}}}
+#check NUMCPUS_RUN options {{{1
+if [ "$NUMCPUS_RUN" = "" ]
+then
+	echo "NUMCPUS_RUN option not found, defaulting to NUMCPUS_RUN = 1"
+	NUMCPUS_RUN=1
+fi
+#}}}
+
+#Run tests
+#Launch all tests on different cpus {{{1
+for (( i=1;i<=$NUMCPUS_RUN;i++ ))
+do
+	#Launch matlab and the daily run script
+	cat > $ISSM_TIER/dailylog/matlab_run$i.m << EOF
+	warning off %necessary to avoid a info.log of several Go for parallel runs
+	try,
+	cd $ISSM_TIER/test/NightlyRun
+	startup;
+	$(if [ "$NROPTIONS" = ""  ]
+	then
+		echo "runme('output','daily','rank',$i,'numprocs',$NUMCPUS_RUN);"
+	else
+		echo "runme($NROPTIONS,'output','daily','rank',$i,'numprocs',$NUMCPUS_RUN);"
+	fi
+	)
+	catch me,
+		%An error occured, get report and exit
+		directory=strsplit(pwd,'/');
+		message=getReport(me)
+		fid=fopen([ISSM_TIER '/dailylog/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
+
+	#Start run from dailylog directory
+	cd $ISSM_TIER/dailylog/
+
+	#Start test
+	MATLAB_VERSION="7.6" #7.2,7.4,7.6 and 7.8
+	/usr/local/pkgs/matlab-$MATLAB_VERSION/bin/matlab  -nojvm -nosplash  -r matlab_run$i -logfile matlab_log$i.log &
+done
+
+#wait until matlab closes
+wait
+#}}}
+#concatenate all reports {{{1
+cd $ISSM_TIER/dailylog/
+mv matlab_log1.log  matlab_log.log
+for (( i=2;i<=$NUMCPUS_RUN;i++ ))
+do
+	cat matlab_log.log matlab_log$i.log > matlab_log.log.bak
+	mv matlab_log.log.bak matlab_log.log
+done
+#}}}
+#Complete info.log {{{1
+if [ $(cat matlab_log.log | grep "MATLABEXITEDCORRECTLY" | wc -l) -eq $NUMCPUS_RUN ]
+then
+	MATLABCRASH=0
+else
+	MATLABCRASH=1
+fi
+ELAPSED_RUN=$(timer $INSTALL_TIME)
+ELAPSED_TOTAL=$(timer $START_TIME)
+cat << END >>  $ISSM_TIER/dailylog/info.log
+elapsed_run:   $(echo $ELAPSED_RUN)
+elapsed_total: $(echo $ELAPSED_TOTAL)
+matlab_crash:  $(echo $MATLABCRASH)
+END
+#}}}
+
+#Send Report
+#Build html report {{{1
+cd $ISSM_TIER/dailylog/
+sh ../scripts/report.sh
+ln -s $ISSM_TIER/dailylog/report.html $INIT_PATH
+echo "html report located in $ISSM_TIER/dailylog/report.html and $INIT_PATH/report.html"
+#}}}
Index: /issm/trunk-jpl-damage/scripts/errlog_process.sh
===================================================================
--- /issm/trunk-jpl-damage/scripts/errlog_process.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/errlog_process.sh	(revision 11330)
@@ -0,0 +1,8 @@
+#!/bin/bash
+
+#first get rank we want to keep.
+rank=`cat $1 | awk 'NR==1' | sed 's/==/ /'g | awk '{printf("%s\n",$1);}'`
+
+#now only keep lines with this rank
+cat $1 | grep "==$rank==" > $1.bak
+mv $1.bak $1
Index: /issm/trunk-jpl-damage/scripts/getloc.sh
===================================================================
--- /issm/trunk-jpl-damage/scripts/getloc.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/getloc.sh	(revision 11330)
@@ -0,0 +1,36 @@
+#!/bin/bash
+#get number of lines of code
+cloc-1.55.pl $ISSM_TIER/src $ISSM_TIER/m4 --exclude-dir=.svn --exclude-ext=exp --exclude-lang=make --out=temp
+cat temp
+./cloc2html.py
+rm temp
+
+cat $ISSM_TIER/src/dox/issm.dox | sed '/<table/,//d' > input1
+cat $ISSM_TIER/src/dox/issm.dox | sed '1,/<\/table>/d' > input2
+cat input1 temp.html input2 > $ISSM_TIER/src/dox/issm.dox
+rm input1 input2 temp.html
+
+exit 1
+
+
+
+
+
+#OLDER MANUAL VESION
+#get Matlab number of lines
+cd $ISSM_TIER/src/m
+M_LOC=$(find . -name "*.m" -exec wc -l '{}' \; | awk '{ sum += $1 } END { print sum}');
+echo "Matlab code: $M_LOC"
+
+#get C/CPP number of lines
+cd $ISSM_TIER/src
+CPP_LOC=$(find . -name "*.cpp" -exec wc -l '{}' \; | awk '{ sum += $1 } END { print sum}');
+echo "C++    code: $CPP_LOC"
+C_LOC=$(find . -name "*.c" -exec wc -l '{}' \; | awk '{ sum += $1 } END { print sum}');
+echo "C      code: $C_LOC"
+H_LOC=$(find . -name "*.h" -exec wc -l '{}' \; | awk '{ sum += $1 } END { print sum}');
+echo "header code: $H_LOC"
+
+#print total
+let SUM=$M_LOC+$CPP_LOC+$C_LOC+$H_LOC
+echo "Total      : $SUM"
Index: /issm/trunk-jpl-damage/scripts/historyISSM.m
===================================================================
--- /issm/trunk-jpl-damage/scripts/historyISSM.m	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/historyISSM.m	(revision 11330)
@@ -0,0 +1,18 @@
+!vim runme.m
+md=runme('id',101);
+runme('id',[101]);
+md.numberofelements
+md.numberofnodes
+md=mesh(md,'DomainOutline.exp',5000);
+md=geography(md,'','');
+md=geography(md,'Iceshelves.exp','Islands.exp');
+md=setelementstype(md,'macayeal','all');
+md=setelementstype(md,'pattyn','all','stokes','all');
+md=solve(md,ThermalSolutionEnum);
+md=solve(md,BalancedthicknessSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum);
+md=loadresultsfromcluster(md);
+md=tres(md,ThermalSolutionEnum);
+md=tres(md,DiagnosticSolutionEnum);
+plotmodel(md,'data',md.results.DiagnosticSolution.Vel)
+plotmodel(md,'data',)
Index: /issm/trunk-jpl-damage/scripts/issm_webpdf.sh
===================================================================
--- /issm/trunk-jpl-damage/scripts/issm_webpdf.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/issm_webpdf.sh	(revision 11330)
@@ -0,0 +1,27 @@
+#!/bin/bash
+
+# issm_webpdf.sh
+# convert http://issm/ to issm_web.pdf
+
+# Created by gqwang Thu May 12 13:40:08 PDT 2011
+
+PATH=/usr/bin:/bin:/usr/sbin:/sbin
+
+# 1. Download html
+cd /proj/ice/gqwang/
+rm -rf issm.jpl.nasa.gov || exit 1
+wget -r http://issm.jpl.nasa.gov/
+
+# 2. Convert to pdf
+cd issm.jpl.nasa.gov
+a=`find . -name "*.html"`
+for html in $a; do
+   pdf=`echo $html | sed -e '1,1s/\.html/\.pdf/'`
+   echo /usr/bin/wkhtmltopdf $html $pdf
+done
+
+# 3. Merge into one pdf
+
+mkdir pdf
+find . -name "*.pdf" -exec mv {} pdf \;
+gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=issm_web.pdf pdf/*.pdf
Index: /issm/trunk-jpl-damage/scripts/jpic2pdf
===================================================================
--- /issm/trunk-jpl-damage/scripts/jpic2pdf	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/jpic2pdf	(revision 11330)
@@ -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/trunk-jpl-damage/scripts/ol
===================================================================
--- /issm/trunk-jpl-damage/scripts/ol	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/ol	(revision 11330)
@@ -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/trunk-jpl-damage/scripts/pdfcrop.pl
===================================================================
--- /issm/trunk-jpl-damage/scripts/pdfcrop.pl	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/pdfcrop.pl	(revision 11330)
@@ -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/trunk-jpl-damage/scripts/report.sh
===================================================================
--- /issm/trunk-jpl-damage/scripts/report.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/report.sh	(revision 11330)
@@ -0,0 +1,218 @@
+#!/bin/bash
+#generate html report from info.log output file
+
+#----------------------------#
+# Initialize local variables #
+#----------------------------#
+
+#process info.log
+TODAY=`     cat info.log | grep "today"           | awk '{printf("%s %s",$2,$3);}'`
+USER=`      cat info.log | grep "user"            | awk '{print $2}'`
+HOST_NAME=` cat info.log | grep "host"            | awk '{print $2}'`
+OS=`        cat info.log | grep "OS"              | awk '{print $2}'`
+RELEASE=`   cat info.log | grep "release"         | awk '{print $2}'`
+EL_INSTALL=`cat info.log | grep "elapsed_install" | awk '{print $2}'`
+EL_RUN=`    cat info.log | grep "elapsed_run"     | awk '{print $2}'`
+EL_TOTAL=`  cat info.log | grep "elapsed_total"   | awk '{print $2}'`
+CRASH=`     cat info.log | grep "matlab_crash:"   | awk '{print $2}'`
+
+#Process matlab_log.log
+cat matlab_log.log        | egrep 'ERROR|SUCCESS|FAILURE' | grep -v "PETSC" | sed -e "s/>/\&gt;/g" | sed -e "s/</\&lt;/g" > matlab.log
+cat matlab_log.log        | grep "PETSC" | sed -e "s/>/\&gt;/g" | sed -e "s/</\&lt;/g" > petscerror.log
+NUM_TOT=`wc -l matlab.log | awk '{print $1}'`
+NUM_ERR=`cat matlab.log | grep 'ERROR'   | grep -v "PETSC" | wc -l`
+NUM_SUC=`cat matlab.log | grep 'SUCCESS' | wc -l`
+NUM_FAI=`cat matlab.log | grep 'FAILURE' | wc -l`
+
+#style
+H1_STYLE='width="1000px" cellpadding="20"'
+H1_FONT='style="color:#6495ed; font-family:Arial, Verdana, Tahoma; font-weight: bold; font-size:35px;" align="center"'
+
+H2_STYLE='width="900px" cellpadding="20"'
+H2_FONT='style="color:#6495ed; font-family:Arial, Verdana, Tahoma; font-size:28px; font-weight: bold;" align="left"'
+
+TABLE_STYLE='width="800px" rules=none bgcolor="#ffffdd" border=1 bordercolor="#000000" cellpadding="3"'
+TABLE_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:14; font-weight: normal;" align="left"'
+
+MATLAB_STYLE='width="1000px" rules=none'
+MATLAB_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:12px; font-weight: normal;" align="left"'
+
+BODY_STYLE='width="800px"'
+BODY_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:14px;"'
+
+FOOTER_STYLE='width="800px"  cellpadding="10"'
+FOOTER_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:12px; font-weight: normal;" align="center"'
+
+#style 2
+BODY_FONTC=`echo $BODY_FONT | sed -e "s/style=\"/style=\"text-align:center; /g"`
+BODY_FONTL=`echo $BODY_FONT | sed -e "s/style=\"/style=\"text-align:left; /g"`
+
+#create some variables
+if [ $(ls -1 $ISSM_TIER/bin | wc -l) -le 20 ];
+then
+	IS_INSTALL=0
+else
+	IS_INSTALL=1
+fi
+
+#-------------------#
+# build report.html #
+#-------------------#
+
+#first: summary
+cat << END > summary.html
+<div align="center">
+<table $H1_STYLE><tr><td $H1_FONT>ISSM Nightly run report</td></tr></table>
+
+<table $TABLE_STYLE>
+<tr> 
+<td $TABLE_FONT>host: $HOST_NAME</td>
+<td $TABLE_FONT>date: $TODAY</td>
+</tr>
+<tr>
+<td $TABLE_FONT>OS: $OS</td>
+<td $TABLE_FONT>user: $USER</td>
+</tr>
+<tr>
+<td $TABLE_FONT>status: STATUS</td>
+<td $TABLE_FONT>release: $RELEASE</td>
+</tr>
+<tr>
+<td $TABLE_FONT>number of successes: $NUM_SUC/$NUM_TOT
+<td $TABLE_FONT>total elapsed time: $EL_TOTAL</td>
+</tr>
+<tr>
+<td $TABLE_FONT>number of <a href="#ERROR">errors</a>: $NUM_ERR/$NUM_TOT
+
+<td $TABLE_FONT>installation elapsed time: $EL_INSTALL</td>
+</tr>
+<tr>
+<td $TABLE_FONT>number of <a href="#FAILURE">failures</a>: $NUM_FAI/$NUM_TOT
+<td $TABLE_FONT>execution elapsed time: $EL_RUN</td>
+</tr>
+</table>
+<br><hr width="1000px">
+END
+
+#update status
+if [ $IS_INSTALL -eq 1 ]
+then
+	if [ $CRASH -eq 0 ]
+	then
+		cat summary.html | sed -e "s/STATUS/<span style=\"color:#008000\">all test desks have been run<\/span>/g" > summary2.html
+	else
+		cat summary.html | sed -e "s/STATUS/<span style=\"color:#ff0000\">installation successful but Matlab crashed<\/span>/g" > summary2.html
+	fi
+else
+	cat summary.html | sed -e "s/STATUS/<span style=\"color:#ff0000\">installation failed<\/span>/g" > summary2.html
+fi
+mv summary2.html summary.html
+
+#report table
+if [ $IS_INSTALL -eq 1 ];
+then
+	cat << END > content.html
+<table $(echo $H2_STYLE)><tr><td $(echo $H2_FONT)>List of tests</td></tr></table>
+<table $(echo $BODY_STYLE) style="border-collapse:collapse;">
+<tr> 
+<th $(echo $BODY_FONT)>Result</th> 
+<th $(echo $BODY_FONT)>Tolerance</th> 
+<th $(echo $BODY_FONT)>Test id</th>  
+<th $(echo $BODY_FONT)>Test name</th> 
+<th $(echo $BODY_FONT)>Field checked</th>
+</tr>
+$(cat matlab.log | while read line
+  do
+	  echo "<tr>"
+
+	  #get status
+	  STATUS=`echo $line | awk '{print $1}'`
+
+	  #FAILURE
+	  if [ "$STATUS" = "FAILURE" ]
+	  then
+
+		  FONTC=$(echo "$BODY_FONTC bgcolor=#ffff00");
+		  FONTL=$(echo "$BODY_FONTL bgcolor=#ffff00");
+		  echo $line | awk -v FONTC="$FONTC" -v FONTL="$FONTL" '
+		  { printf("<td %s id=FAILURE>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n\n",FONTL,$1,FONTC,$3,FONTC,$6,FONTL,$9,FONTL,$11);}
+			  '; 
+
+		  else
+
+		  #SUCCESS
+		  if [ "$STATUS" = "SUCCESS" ]
+		  then
+			  FONTC=$(echo "$BODY_FONTC bgcolor=#ddffdd")
+			  FONTL=$(echo "$BODY_FONTL bgcolor=#ddffdd")
+		  #ERROR
+		  else
+			  FONTC=$(echo "$BODY_FONTC bgcolor=#ffdddd id=ERROR")
+			  FONTL=$(echo "$BODY_FONTL bgcolor=#ffdddd")
+		  fi
+
+
+		  echo $line | awk -v FONTC="$FONTC" -v FONTL="$FONTL" '
+		  { printf("<td %s>%s</td>\n<td %s>%s%s%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n\n",FONTL,$1,FONTL,$3,$4,$5,FONTC,$8,FONTL,$11,FONTL,$13);}
+			  '; 
+	  fi
+
+	  echo "</tr>"
+
+  done
+	  )
+</table>
+<br>
+END
+else
+	mktemp content.html
+fi
+
+#Matlab error report
+if [ -e matlaberror.log ]
+then
+	cat << END > matlaberror.html
+<table $H2_STYLE><tr><td $H2_FONT>Matlab errors</td></tr></table>
+<table $MATLAB_STYLE><tr><td $MATLAB_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
+else
+	mktemp matlaberror.html
+fi
+
+#Matlab error report
+if test -s petscerror.log
+then
+	cat << END > petscerror.html
+<table $H2_STYLE><tr><td $H2_FONT>PETSc errors</td></tr></table>
+<table $MATLAB_STYLE><tr><td $MATLAB_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
+else
+	mktemp petscerror.html
+fi
+
+#last footer
+cat << END > footer.html
+<br>
+<table $FOOTER_STYLE><tr><td $FOOTER_FONT><a href="http://issm.jpl.nasa.gov" title="ISSM website" target="_blank">ISSM</a> nightly run report</td></tr></table>
+</div>
+END
+
+#concatenate files
+cat summary.html content.html matlaberror.html petscerror.html footer.html > report.html
+rm  summary.html content.html footer.html matlaberror.html petscerror.html matlab.log
Index: /issm/trunk-jpl-damage/scripts/run.sh
===================================================================
--- /issm/trunk-jpl-damage/scripts/run.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/run.sh	(revision 11330)
@@ -0,0 +1,59 @@
+#!/bin/bash
+
+#prepare runs
+NUMCPUS_RUN=7
+NROPTIONS="";
+MATLAB_VERSION="7.6" #7.2,7.4,7.6 and 7.8
+#create softlink to startup {{{1
+cd $ISSM_TIER/test/NightlyRun/
+ln -s $ISSM_TIER/startup.m .
+#}}}
+
+#Launch all tests on different cpus
+for (( i=1;i<=$NUMCPUS_RUN;i++ ))
+do
+	#Launch matlab and the daily run script
+	cat > $ISSM_TIER/dailylog/matlab_run$i.m << EOF
+	warning off %necessary to avoid a daily.log of several Go for parallel runs
+	try,
+		cd $ISSM_TIER/test/NightlyRun
+		startup;
+		$(if [ "$NROPTIONS" = ""  ]
+	then
+		echo "runme('output','daily','rank',$i,'numprocs',$NUMCPUS_RUN);"
+	else
+		echo "runme($NROPTIONS,'output','daily','rank',$i,'numprocs',$NUMCPUS_RUN);"
+	fi
+	)
+	catch me,
+		%An error occured, get report and exit
+		directory=strsplit(pwd,'/');
+		message=getReport(me)
+		fid=fopen([ISSM_TIER '/dailylog/matlaberror.log'], 'at');
+		fprintf(fid,'\nMatlab error occured in: %s\n\n',directory{end});
+		fprintf(fid,'%s',message);
+		fclose(fid);
+	end
+	exit
+EOF
+
+	#Start run from dailylog directory
+	cd $ISSM_TIER/dailylog/
+
+	#Start test
+	/usr/local/pkgs/matlab-$MATLAB_VERSION/bin/matlab  -nojvm -nosplash  -r matlab_run$i -logfile matlab_log$i.log &
+
+done
+
+#wait until matlab closes
+wait
+
+#concatenate all reports
+mv matlab_log1.log  matlab_log.log
+for (( i=2;i<=$NUMCPUS_RUN;i++ ))
+do
+	cat matlab_log.log matlab_log$i.log > matlab_log.log.bak
+	mv matlab_log.log.bak matlab_log.log
+	rm matlab_log$i.log
+
+done
Index: /issm/trunk-jpl-damage/scripts/svnlog
===================================================================
--- /issm/trunk-jpl-damage/scripts/svnlog	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/svnlog	(revision 11330)
@@ -0,0 +1,3 @@
+#!/bin/bash
+
+svn log $1 | perl -e 'print reverse<>'
Index: /issm/trunk-jpl-damage/scripts/svnvimdiff
===================================================================
--- /issm/trunk-jpl-damage/scripts/svnvimdiff	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/svnvimdiff	(revision 11330)
@@ -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/trunk-jpl-damage/scripts/sync.sh
===================================================================
--- /issm/trunk-jpl-damage/scripts/sync.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/sync.sh	(revision 11330)
@@ -0,0 +1,100 @@
+#!/bin/bash
+
+#This shell tries to synchronize the current cielo root directory on another 
+#machine. 
+
+echo "Watch out, this script should be run in top level directory of cielo"
+
+echo -n "Platform (cosmos,mustang,gemini,pleiades)?: "
+read platform 
+
+
+if [[ "$platform" ==  "cosmos" ]]
+then
+	echo "Synchronizing cielo with cosmos"
+	#first cleanup the archive
+	cl
+	clb
+	cls
+	#then tar the archive
+	present_directory=`pwd`;
+	cd ../
+	rm -rf trunk.tar.gz
+	tar zcvf trunk.tar.gz trunk
+
+	#send archive to cosmos
+	scp  trunk.tar.gz larour@cosmos.jpl.nasa.gov:/home/larour
+
+	#run synchronization script on cosmos
+	ssh larour@cosmos.jpl.nasa.gov './sync_cosmos.sh'
+
+	rm -rf trunk.tar.gz
+elif [[ "$platform" ==  "mustang" ]]
+then
+	
+	echo "Synchronizing cielo with mustang"
+	#first cleanup the archive
+	cl
+	clb
+	cls
+	#then tar the archive
+	present_directory=`pwd`;
+	cd ../
+	rm -rf trunk.tar.gz
+	tar zcvf trunk.tar.gz trunk
+
+	#send archive to mustang
+	scp  trunk.tar.gz larour@mustang.jpl.nasa.gov:/proj/ice/larour/Ice/
+
+	#run synchronization script on cosmos
+	ssh larour@mustang.jpl.nasa.gov './sync_mustang.sh'
+
+	rm -rf trunk.tar.gz
+elif [[ "$platform" ==  "gemini" ]]
+then
+	echo "Synchronizing cielo with gemini"
+
+	rm -rf Synchronisation
+	mkdir Synchronisation
+	cd Synchronisation
+	svn co svn+ssh://mustang.jpl.nasa.gov/proj/ice/issm/issm/trunk
+
+	#then tar the archive
+	tar zcvf trunk.tar.gz trunk/
+
+	#send archive to cosmos
+	scp  trunk.tar.gz larour@gemini.jpl.nasa.gov:/home/larour
+
+	#run synchronization script on cosmos
+	ssh larour@gemini.jpl.nasa.gov './sync_gemini.sh' 
+
+	#exit 
+	cd ..
+	rm -rf Synchronisation
+
+elif [[ "$platform" ==  "pleiades" ]]
+then
+	echo "Synchronizing issm with pleiades"
+
+	rm -rf Synchronisation
+	mkdir Synchronisation
+	cd Synchronisation
+	svn co svn+ssh://mustang.jpl.nasa.gov/proj/ice/issm/issm/trunk
+
+	#then tar the archive
+	tar zcvf trunk.tar.gz trunk/
+
+	#send archive to cosmos
+	scp  trunk.tar.gz elarour@pfe:/home1/elarour
+
+	#run synchronization script on cosmos
+	ssh elarour@pfe './sync_pleiades.sh'
+
+	#exit 
+	cd ..
+	rm -rf Synchronisation
+
+else
+	echo "This platform not supported yet"
+	exit
+fi
Index: /issm/trunk-jpl-damage/scripts/tai
===================================================================
--- /issm/trunk-jpl-damage/scripts/tai	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/tai	(revision 11330)
@@ -0,0 +1,5 @@
+#!/bin/bash
+
+cd $EXECUTION_DIR
+DIR=$(ls -lrtd *"/" | awk '{line= $0} END {print line}' | awk '{printf("%s\n",$9);}')
+tail -f $DIR/*.outlog
Index: /issm/trunk-jpl-damage/scripts/user_kill
===================================================================
--- /issm/trunk-jpl-damage/scripts/user_kill	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/user_kill	(revision 11330)
@@ -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/trunk-jpl-damage/scripts/vil
===================================================================
--- /issm/trunk-jpl-damage/scripts/vil	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/vil	(revision 11330)
@@ -0,0 +1,5 @@
+#!/bin/bash
+
+cd $EXECUTION_DIR
+DIR=$(ls -lrtd *"/" | awk '{line= $0} END {print line}' | awk '{printf("%s\n",$9);}')
+vim $DIR/*.outlog
Index: /issm/trunk-jpl-damage/scripts/waitonlock.sh
===================================================================
--- /issm/trunk-jpl-damage/scripts/waitonlock.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/waitonlock.sh	(revision 11330)
@@ -0,0 +1,60 @@
+#!/bin/bash
+#script version of waitonlock.m
+#function flag=waitonlock(filename,timelimit)
+#%WAITONLOCK - wait for a file
+#%
+#%   This routine will return when a file named 'filename' is written to disk.
+#%   If the time limit given in input is exceeded, return 0
+#%
+#%   Usage:
+#%      flag=waitonlock(filename,timelimit)
+
+#Check input value
+if [ $# -ne 2 ];
+then
+	#no config file specified: exit
+	echo "waitonlock.sh error message: bad usage"
+	exit 0
+fi
+
+#initialization
+TIME=1;
+STEP=1;  #step in seconds
+FILE=$1;
+
+#check time limit
+if [ "$2" == "Inf" ]
+then
+	echo infinity detected
+	LIMIT=999999999;
+else
+	echo not inf
+	let LIMIT=$2*60;
+fi
+
+#display
+echo "waiting for $1 hold on (ctl+c to stop)..."
+
+#Loop till file is found
+while [ $TIME -lt $LIMIT ]
+do
+
+	#lock file exists?
+	if [ -e $FILE ]; then
+		break;
+	fi
+
+	#No-> wait one second
+	sleep $STEP
+	let TIME+=1;
+	echo "waiting $TIME seconds ($TIME < $LIMIT)"
+	dummy=$(ls); #force bash to refresh file list
+
+done
+
+#Compute flag
+if [ $TIME -lt $LIMIT ]; then 
+	exit 1;
+else
+	exit 0;
+fi
Index: /issm/trunk-jpl-damage/scripts/windowsbuild.sh
===================================================================
--- /issm/trunk-jpl-damage/scripts/windowsbuild.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/scripts/windowsbuild.sh	(revision 11330)
@@ -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_TIER/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/trunk-jpl-damage/src/Makefile.am
===================================================================
--- /issm/trunk-jpl-damage/src/Makefile.am	(revision 11330)
+++ /issm/trunk-jpl-damage/src/Makefile.am	(revision 11330)
@@ -0,0 +1,8 @@
+EXTRA_DIST = m  perl  pro
+SUBDIRS = c mex
+
+if ADIC2
+SUBDIRS += ad
+endif
+
+
Index: /issm/trunk-jpl-damage/src/ad/Makefile.am
===================================================================
--- /issm/trunk-jpl-damage/src/ad/Makefile.am	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/Makefile.am	(revision 11330)
@@ -0,0 +1,630 @@
+INCLUDES = @DAKOTAINCL@ @PETSCINCL@ @SLEPCINCL@ @MPIINCL@ @MATLABINCL@  @METISINCL@  @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@  @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@  @TRIANGLEINCL@ @HYPREINCL@ @MLINCL@ @TAOINCL@  @ADIC2INCL@
+
+#This Makefile.am is for automatic differentiation of the parallel version of ISSM.
+#We do not compile in serial mode
+#If user requests no parallel compilation, we compile an empty ISSM.
+#Compilation can still be blocked if user has not activated --with-adic compilation
+
+#Library declaration {{{1
+
+if NOPARALLEL
+lib_LIBRARIES = 
+else
+lib_LIBRARIES = libpISSM.a   libOverload.a
+endif
+
+if ADIC2
+lib_LIBRARIES += libAD.a libpISSMRose.a
+endif
+
+#}}}
+#Overload library, to overload any non-standard symbols. {{{1
+libOverload_a_SOURCES = ./shared/String/stricmp.c
+libOverload_a_CFLAGS = -fPIC -D_PARALLEL_   -D_C_ $(COPTFLAGS)
+#}}}
+#ISSM library  {{{1
+libpISSM_a_SOURCES = ./include/macros.h\
+					./include/typedefs.h\
+					./include/types.h\
+					./include/include.h\
+					./objects/objects.h\
+					./objects/Object.h\
+					./objects/Gauss/GaussTria.h\
+					./objects/Gauss/GaussTria.cpp\
+					./objects/Update.h\
+					./objects/Element.h\
+					./objects/FemModel.h\
+					./objects/FemModel.cpp\
+					./objects/Material.h\
+					./objects/Load.h\
+					./objects/Loads/Friction.h\
+					./objects/Loads/Friction.cpp\
+					./objects/Inputs/TransientInput.h\
+					./objects/Inputs/TransientInput.cpp\
+					./objects/Constraints/SpcTransient.cpp\
+					./objects/Constraints/SpcTransient.h\
+					./objects/DofIndexing.h\
+					./objects/DofIndexing.cpp\
+					./objects/IoModel.h\
+					./objects/IoModel.cpp\
+					./objects/Node.h\
+					./objects/Node.cpp\
+					./objects/Segment.h\
+					./objects/Segment.cpp\
+					./objects/Vertex.h\
+					./objects/Vertex.cpp\
+					./objects/Hook.h\
+					./objects/Hook.cpp\
+					./objects/Patch.h\
+					./objects/Patch.cpp\
+					./objects/ElementResults/ElementResultLocal.h\
+					./objects/ElementResults/DoubleElementResult.h\
+					./objects/ElementResults/DoubleElementResult.cpp\
+					./objects/ElementResults/TriaVertexElementResult.h\
+					./objects/ElementResults/TriaVertexElementResult.cpp\
+					./objects/ElementResults/BoolElementResult.h\
+					./objects/ElementResults/BoolElementResult.cpp\
+					./objects/ExternalResults/ExternalResult.h\
+					./objects/ExternalResults/BoolExternalResult.h\
+					./objects/ExternalResults/BoolExternalResult.cpp\
+					./objects/ExternalResults/DoubleExternalResult.h\
+					./objects/ExternalResults/DoubleExternalResult.cpp\
+					./objects/ExternalResults/DoubleVecExternalResult.h\
+					./objects/ExternalResults/DoubleVecExternalResult.cpp\
+					./objects/ExternalResults/DoubleMatExternalResult.h\
+					./objects/ExternalResults/DoubleMatExternalResult.cpp\
+					./objects/ExternalResults/IntExternalResult.h\
+					./objects/ExternalResults/IntExternalResult.cpp\
+					./objects/ExternalResults/StringExternalResult.h\
+					./objects/ExternalResults/StringExternalResult.cpp\
+					./objects/ExternalResults/PetscVecExternalResult.h\
+					./objects/ExternalResults/PetscVecExternalResult.cpp\
+					./objects/Elements/Tria.h\
+					./objects/Elements/Tria.cpp\
+					./objects/Elements/TriaHook.h\
+					./objects/Elements/TriaHook.cpp\
+					./objects/Elements/TriaRef.h\
+					./objects/Elements/TriaRef.cpp\
+					./objects/Inputs/Input.h\
+					./objects/Inputs/InputLocal.h\
+					./objects/Inputs/TriaVertexInput.h\
+					./objects/Inputs/TriaVertexInput.cpp\
+					./objects/Inputs/BoolInput.h\
+					./objects/Inputs/BoolInput.cpp\
+					./objects/Inputs/IntInput.h\
+					./objects/Inputs/IntInput.cpp\
+					./objects/Inputs/DoubleInput.h\
+					./objects/Inputs/DoubleInput.cpp\
+					./objects/Inputs/DatasetInput.h\
+					./objects/Inputs/DatasetInput.cpp\
+					./objects/Materials/Matice.h\
+					./objects/Materials/Matice.cpp\
+					./objects/Materials/Matpar.h\
+					./objects/Materials/Matpar.cpp\
+					./objects/Constraints/Constraint.h\
+					./objects/Constraints/SpcStatic.cpp\
+					./objects/Constraints/SpcStatic.h\
+					./objects/Constraints/SpcDynamic.cpp\
+					./objects/Constraints/SpcDynamic.h\
+					./objects/Loads/Penpair.cpp\
+					./objects/Loads/Penpair.h\
+					./objects/Loads/Pengrid.cpp\
+					./objects/Loads/Pengrid.h\
+					./objects/Loads/Icefront.cpp\
+					./objects/Loads/Icefront.h\
+					./objects/Loads/Numericalflux.cpp\
+					./objects/Loads/Numericalflux.h\
+					./objects/Numerics/ElementMatrix.h\
+					./objects/Numerics/ElementMatrix.cpp\
+					./objects/Numerics/ElementVector.h\
+					./objects/Numerics/ElementVector.cpp\
+					./objects/Params/Param.h\
+					./objects/Params/BoolParam.cpp\
+					./objects/Params/BoolParam.h\
+					./objects/Params/IntParam.cpp\
+					./objects/Params/IntParam.h\
+					./objects/Params/IntVecParam.cpp\
+					./objects/Params/IntVecParam.h\
+					./objects/Params/IntMatParam.cpp\
+					./objects/Params/IntMatParam.h\
+					./objects/Params/DoubleParam.cpp\
+					./objects/Params/DoubleParam.h\
+					./objects/Params/FileParam.cpp\
+					./objects/Params/FileParam.h\
+					./objects/Params/PetscMatParam.cpp\
+					./objects/Params/PetscMatParam.h\
+					./objects/Params/StringArrayParam.cpp\
+					./objects/Params/StringArrayParam.h\
+					./objects/Params/DoubleMatParam.cpp\
+					./objects/Params/DoubleMatParam.h\
+					./objects/Params/DoubleMatArrayParam.cpp\
+					./objects/Params/DoubleMatArrayParam.h\
+					./objects/Params/DoubleVecParam.cpp\
+					./objects/Params/DoubleVecParam.h\
+					./objects/Params/PetscVecParam.cpp\
+					./objects/Params/PetscVecParam.h\
+					./objects/Params/StringParam.cpp\
+					./objects/Params/StringParam.h\
+					./Container/Container.h\
+					./Container/Constraints.h\
+					./Container/Constraints.cpp\
+					./Container/DataSet.h\
+					./Container/DataSet.cpp\
+					./Container/Elements.h\
+					./Container/Elements.cpp\
+					./Container/Inputs.h\
+					./Container/Inputs.cpp\
+					./Container/Loads.h\
+					./Container/Loads.cpp\
+					./Container/Materials.h\
+					./Container/Materials.cpp\
+					./Container/Nodes.h\
+					./Container/Nodes.cpp\
+					./Container/Parameters.h\
+					./Container/Parameters.cpp\
+					./Container/Results.h\
+					./Container/Results.cpp\
+					./Container/Vertices.h\
+					./Container/Vertices.cpp\
+					./shared/shared.h\
+					./shared/Alloc/alloc.h\
+					./shared/Alloc/alloc.cpp\
+					./shared/Matrix/matrix.h\
+					./shared/Matrix/MatrixUtils.cpp\
+					./shared/Dofs/dofs.h\
+					./shared/Dofs/dofsetgen.cpp\
+					./shared/Numerics/numerics.h\
+					./shared/Numerics/Verbosity.h\
+					./shared/Numerics/Verbosity.cpp\
+					./shared/Numerics/IsInputConverged.cpp\
+					./shared/Numerics/GaussPoints.h\
+					./shared/Numerics/GaussPoints.cpp\
+					./shared/Numerics/cross.cpp\
+					./shared/Numerics/extrema.cpp\
+					./shared/Numerics/UnitConversion.cpp\
+					./shared/Numerics/PetscOptionsFromAnalysis.cpp\
+					./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/GetVerticesCoordinates.cpp\
+					./shared/Elements/GetLocalDofList.cpp\
+					./shared/Elements/GetGlobalDofList.cpp\
+					./shared/Elements/GetNumberOfDofs.cpp\
+					./shared/String/sharedstring.h\
+					./toolkits/petsc\
+					./toolkits/petsc/patches\
+					./toolkits/petsc/patches/SolverEnum.h\
+					./toolkits/petsc/patches/petscpatches.h\
+					./toolkits/petsc/patches/MatlabMatrixToPetscMatrix.cpp\
+					./toolkits/petsc/patches/MatlabVectorToPetscVector.cpp\
+					./toolkits/petsc/patches/PetscMatrixToMatlabMatrix.cpp\
+					./toolkits/petsc/patches/PetscVectorToMatlabVector.cpp\
+					./toolkits/petsc/patches/MatlabMatrixToDoubleMatrix.cpp\
+					./toolkits/petsc/patches/MatlabVectorToDoubleVector.cpp\
+					./toolkits/petsc/patches/PetscDetermineLocalSize.cpp\
+					./toolkits/petsc/patches/VecTranspose.cpp\
+					./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/SerialToVec.cpp\
+					./toolkits/petsc/patches/VecFree.cpp\
+					./toolkits/petsc/patches/VecDuplicatePatch.cpp\
+					./toolkits/petsc/patches/KSPFree.cpp\
+					./toolkits/petsc/patches/ISFree.cpp\
+					./toolkits/petsc/patches/MatFree.cpp\
+					./toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp\
+					./toolkits/petsc/patches/VecPartition.cpp\
+					./toolkits/petsc/patches/MatPartition.cpp\
+					./toolkits/petsc/patches/MatInvert.cpp\
+					./toolkits/petsc/patches/MatMultPatch.cpp\
+					./toolkits/petsc/petscincludes.h\
+					./toolkits/mpi/mpiincludes.h\
+					./toolkits/mpi/patches/mpipatches.h\
+					./toolkits/mpi/patches/MPI_Upperrow.cpp\
+					./toolkits/mpi/patches/MPI_Lowerrow.cpp\
+					./toolkits/mpi/patches/MPI_Boundariesfromrange.cpp\
+					./toolkits/metis/metisincludes.h\
+					./toolkits/metis/patches/metispatches.h\
+					./toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp\
+					./toolkits/triangle/triangleincludes.h\
+					./toolkits.h\
+					./io/io.h\
+					./io/Disk/diskio.h\
+					./io/Disk/pfopen.cpp\
+					./io/Disk/pfclose.cpp\
+					./io/PrintfFunction.cpp\
+					./EnumDefinitions/EnumDefinitions.h\
+					./EnumDefinitions/EnumToModelField.cpp\
+					./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/CreateSingleNodeToElementConnectivity.cpp\
+					./modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp\
+					./modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp\
+					./modules/ParsePetscOptionsx/ParsePetscOptionsx.h\
+					./modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp\
+					./modules/NodesDofx/NodesDofx.h\
+					./modules/NodesDofx/NodesDofx.cpp\
+					./modules/VerticesDofx/VerticesDofx.h\
+					./modules/VerticesDofx/VerticesDofx.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/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/TimeAdaptx/TimeAdaptx.h\
+					./modules/TimeAdaptx/TimeAdaptx.cpp\
+					./modules/UpdateVertexPositionsx/UpdateVertexPositionsx.h\
+					./modules/UpdateVertexPositionsx/UpdateVertexPositionsx.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/UpdateConstraintsx/UpdateConstraintsx.h\
+					./modules/UpdateConstraintsx/UpdateConstraintsx.cpp\
+					./modules/MeshPartitionx/MeshPartitionx.cpp\
+					./modules/MeshPartitionx/MeshPartitionx.h\
+					./modules/Reducevectorgtofx/Reducevectorgtofx.cpp\
+					./modules/Reducevectorgtofx/Reducevectorgtofx.h\
+					./modules/Reduceloadx/Reduceloadx.h\
+					./modules/Reduceloadx/Reduceloadx.cpp\
+					./modules/EnumToStringx/EnumToStringx.cpp\
+					./modules/EnumToStringx/EnumToStringx.h\
+					./modules/StringToEnumx/StringToEnumx.cpp\
+					./modules/StringToEnumx/StringToEnumx.h\
+					./modules/SystemMatricesx/SystemMatricesx.cpp\
+					./modules/SystemMatricesx/SystemMatricesx.h\
+					./modules/ConstraintsStatex/ConstraintsStatex.cpp\
+					./modules/ConstraintsStatex/ConstraintsStatex.h\
+					./modules/ConstraintsStatex/ConstraintsStateLocal.h\
+					./modules/RequestedOutputsx/RequestedOutputsx.h\
+					./modules/RequestedOutputsx/RequestedOutputsx.cpp\
+					./modules/ResetConstraintsx/ResetConstraintsx.h\
+					./modules/ResetConstraintsx/ResetConstraintsx.cpp\
+					./modules/Solverx/Solverx.cpp\
+					./modules/Solverx/Solverx.h\
+					./modules/Solverx/DofTypesToIndexSet.cpp\
+					./modules/VecMergex/VecMergex.cpp\
+					./modules/VecMergex/VecMergex.h\
+					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp\
+					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h\
+					./modules/InputToResultx/InputToResultx.cpp\
+					./modules/InputToResultx/InputToResultx.h\
+					./modules/InputConvergencex/InputConvergencex.cpp\
+					./modules/InputConvergencex/InputConvergencex.h\
+					./solutions/convergence.cpp\
+					./solutions/WriteLockFile.cpp\
+					./solutions/ResetBoundaryConditions.cpp\
+					./solutions/AnalysisConfiguration.cpp\
+					./solutions/CorePointerFromSolutionEnum.cpp\
+					./solvers/solver_linear.cpp\
+					./solvers/solver_nonlinear.cpp
+
+
+libpISSM_a_CXXFLAGS = -fPIC -D_PARALLEL_   -D_C_ $(CXXOPTFLAGS) 
+#}}}
+#DAKOTA sources  {{{1
+if DAKOTA
+libpISSM_a_SOURCES +=  ./objects/DakotaPlugin.h\
+					  ./objects/DakotaPlugin.cpp\
+					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h\
+					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp\
+					  ./modules/DakotaResponsesx/DakotaResponsesx.h\
+					  ./modules/DakotaResponsesx/DakotaResponsesx.cpp\
+					  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h\
+					  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp\
+					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp\
+					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.h\
+					  ./modules/Dakotax/Dakotax.h\
+					  ./modules/Dakotax/Dakotax.cpp\
+					  ./modules/Dakotax/DakotaMPI_Bcast.cpp\
+					  ./modules/Dakotax/DakotaFree.cpp\
+					  ./modules/Dakotax/SpawnCore.cpp\
+					  ./modules/Dakotax/SpawnCoreParallel.cpp\
+					  ./modules/Dakotax/DescriptorIndex.cpp\
+					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp\
+					  ./modules/ModelProcessorx/Qmu/CreateParametersQmu.cpp\
+					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.h
+endif
+#}}}
+#Transient sources  {{{1
+if TRANSIENT
+libpISSM_a_SOURCES +=  ./solutions/transient_core.cpp\
+					   ./modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp
+endif
+#}}}
+#Steadystate sources  {{{1
+if STEADYSTATE
+libpISSM_a_SOURCES += ./solutions/steadystate_core.cpp\
+					  ./solutions/steadystateconvergence.cpp
+endif
+#}}}
+#Prognostic sources  {{{1
+if PROGNOSTIC
+libpISSM_a_SOURCES +=  ./solutions/prognostic_core.cpp\
+					   ./modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp\
+					   ./modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp\
+					   ./modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp\
+					   ./modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp
+
+endif
+#}}}
+#Thermal sources  {{{1
+if THERMAL
+libpISSM_a_SOURCES +=  ./solutions/thermal_core.cpp\
+					   ./solutions/thermal_core_step.cpp\
+					   ./solutions/enthalpy_core.cpp\
+					   ./solvers/solver_thermal_nonlinear.cpp\
+					   ./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
+endif
+#}}}
+#Control sources  {{{1
+if CONTROL
+libpISSM_a_SOURCES += ./solutions/control_core.cpp\
+					  ./solutions/controltao_core.cpp\
+					  ./solutions/controlrestart.cpp\
+					  ./solutions/controlconvergence.cpp\
+					  ./solutions/objectivefunctionC.cpp\
+					  ./solutions/gradient_core.cpp\
+					  ./solutions/adjointdiagnostic_core.cpp\
+					  ./solutions/adjointbalancethickness_core.cpp\
+					  ./solutions/AdjointCorePointerFromSolutionEnum.cpp\
+					  ./solvers/solver_adjoint_linear.cpp\
+					  ./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/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/CostFunctionx/CostFunctionx.h\
+					  ./modules/CostFunctionx/CostFunctionx.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/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp\
+					  ./modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h\
+					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp\
+					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h\
+					  ./objects/Inputs/ControlInput.h\
+					  ./objects/Inputs/ControlInput.cpp\
+					  ./shared/Numerics/BrentSearch.cpp\
+					  ./shared/Numerics/OptimalSearch.cpp\
+					  ./shared/Numerics/OptFunc.cpp\
+					  ./objects/OptArgs.h\
+					  ./objects/OptPars.h
+
+endif
+#}}}
+#Hydrology sources  {{{1
+if HYDROLOGY
+libpISSM_a_SOURCES += ./modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp\
+					  ./modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp\
+					  ./modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp\
+					  ./modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp\
+					  ./solutions/hydrology_core.cpp\
+					  ./solutions/hydrology_core_step.cpp
+endif
+#}}}
+#Diagnostic sources  {{{1
+if DIAGNOSTIC
+libpISSM_a_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\
+					  ./solutions/diagnostic_core.cpp\
+					  ./solvers/solver_stokescoupling_nonlinear.cpp
+endif
+#}}}
+#Balanced sources  {{{1
+if BALANCED
+libpISSM_a_SOURCES += ./modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp\
+					  ./modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp\
+					  ./modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp\
+					  ./modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp\
+					  ./solutions/balancethickness_core.cpp
+endif
+#}}}
+#Responses sources  {{{1
+if RESPONSES
+libpISSM_a_SOURCES += ./modules/MinVelx/MinVelx.h\
+					  ./modules/MinVelx/MinVelx.cpp\
+					  ./modules/MaxVelx/MaxVelx.h\
+					  ./modules/MaxVelx/MaxVelx.cpp\
+					  ./modules/MaxAbsVxx/MaxAbsVxx.h\
+					  ./modules/MaxAbsVxx/MaxAbsVxx.cpp\
+					  ./modules/MaxAbsVyx/MaxAbsVyx.h\
+					  ./modules/MaxAbsVyx/MaxAbsVyx.cpp\
+					  ./modules/MaxAbsVzx/MaxAbsVzx.h\
+					  ./modules/MaxAbsVzx/MaxAbsVzx.cpp\
+					  ./modules/MaxVxx/MaxVxx.h\
+					  ./modules/MaxVxx/MaxVxx.cpp\
+					  ./modules/MaxVyx/MaxVyx.h\
+					  ./modules/MaxVyx/MaxVyx.cpp\
+					  ./modules/MaxVzx/MaxVzx.h\
+					  ./modules/MaxVzx/MaxVzx.cpp\
+					  ./modules/MinVxx/MinVxx.h\
+					  ./modules/MinVxx/MinVxx.cpp\
+					  ./modules/MinVyx/MinVyx.h\
+					  ./modules/MinVyx/MinVyx.cpp\
+					  ./modules/MinVzx/MinVzx.h\
+					  ./modules/MinVzx/MinVzx.cpp\
+					  ./modules/RheologyBbarx/RheologyBbarx.cpp\
+					  ./modules/RheologyBbarx/RheologyBbarx.h\
+					  ./modules/MassFluxx/MassFluxx.cpp\
+					  ./modules/MassFluxx/MassFluxx.h\
+					  ./modules/NodalValuex/NodalValuex.h\
+					  ./modules/NodalValuex/NodalValuex.cpp\
+					  ./modules/SurfaceAreax/SurfaceAreax.h\
+					  ./modules/SurfaceAreax/SurfaceAreax.cpp\
+					  ./modules/Responsex/Responsex.h\
+					  ./modules/Responsex/Responsex.cpp
+endif
+#}}}
+#Slope sources  {{{1
+if SLOPE
+libpISSM_a_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\
+					  ./solutions/surfaceslope_core.cpp\
+					  ./solutions/bedslope_core.cpp
+endif
+#}}}
+#GroundingLine sources  {{{1
+if GROUNDINGLINE
+libpISSM_a_SOURCES += ./modules/GroundingLineMigrationx/GroundingLineMigrationx.cpp\
+					  ./modules/GroundingLineMigrationx/GroundingLineMigrationx.h\
+					  ./modules/GroundingLineMigrationx/GroundingLineMigrationxLocal.h\
+					  ./modules/GroundingLineMigrationx/GroundingLineMigrationxUtils.cpp\
+					  ./solutions/groundinglinemigration2d_core.cpp
+endif
+#}}}
+#Rifts sources  {{{1
+if RIFTS
+libpISSM_a_SOURCES += ./objects/Loads/Riftfront.cpp\
+					  ./objects/Loads/Riftfront.h\
+					  ./modules/ConstraintsStatex/RiftConstraintsState.cpp
+endif
+#}}}
+#3D sources  {{{1
+if THREED
+libpISSM_a_SOURCES += ./objects/Gauss/GaussPenta.h\
+					  ./objects/Gauss/GaussPenta.cpp\
+					  ./objects/ElementResults/PentaVertexElementResult.h\
+					  ./objects/ElementResults/PentaVertexElementResult.cpp\
+					  ./objects/Inputs/PentaVertexInput.h\
+					  ./objects/Inputs/PentaVertexInput.cpp\
+					  ./objects/Elements/Penta.h\
+					  ./objects/Elements/Penta.cpp\
+					  ./objects/Elements/PentaHook.h\
+					  ./objects/Elements/PentaHook.cpp\
+					  ./objects/Elements/PentaRef.h\
+					  ./objects/Elements/PentaRef.cpp
+endif
+#}}}
+
+#ADIC2 library, for automatic differentiation {{{1
+if ADIC2
+#libAD_a_SOURCES = ./mini1.ad.c
+libAD_a_SOURCES = 
+libAD_a_CFLAGS = -fPIC -D_PARALLEL_   -D_C_ $(COPTFLAGS)
+
+#test rose preprocessing 
+%.r2cpp.cpp : %.cpp
+	testTranslator -rose:o $@ -rose:skipfinalCompileStep -DHAVE_CONFIG_H -D_PARALLEL_ -D_C_ -I. -I../.. $(INCLUDES) $<
+
+libpISSMRose_a_SOURCES = $(libpISSM_a_SOURCES:.cpp=.r2cpp.cpp)
+libpISSMRose_a_CXXFLAGS= -fPIC -D_PARALLEL_ -D_C_ $(CXXOPTFLAGS)
+#Automatic differentiation rules: 
+%.ad.c: %.c
+	adic2 -mforward  $< --nary
+endif
+#}}}
+#Executable {{{1
+
+if NOPARALLEL
+bin_PROGRAMS = 
+else 
+bin_PROGRAMS = issm.exe issmRose.exe
+endif
+
+#Standard libraries
+LDADD =      ./libOverload.a
+issm_exe_LDADD = ./libpISSM.a $(LDADD)
+if ADIC2
+issmRose_exe_LDADD = ./libpISSMRose.a $(LDADD)
+endif
+
+#External packages
+LDADD += $(PETSCLIB) $(TAOLIB) $(FLIBS) $(PLAPACKLIB)  $(MUMPSLIB) $(SCALAPACKLIB)  $(BLACSLIB) $(HYPRELIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB)  $(MKLLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(ADIC2LIB) 
+
+
+issm_exe_SOURCES = solutions/issm.cpp
+issm_exe_CXXFLAGS= -fPIC -D_PARALLEL_  $(CXXOPTFLAGS) $(COPTFLAGS) 
+issmRose_exe_SOURCES = solutions/issm.cpp
+issmRose_exe_CXXFLAGS= -fPIC -D_PARALLEL_  $(CXXOPTFLAGS) $(COPTFLAGS) 
+
+#}}}
Index: /issm/trunk-jpl-damage/src/ad/eraselinks.sh
===================================================================
--- /issm/trunk-jpl-damage/src/ad/eraselinks.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/eraselinks.sh	(revision 11330)
@@ -0,0 +1,14 @@
+#/bin/bash
+#This script soflinks all files in trunk/src/c/ directory necessary for compilation 
+#of trunk/src/ad/ 
+rm include
+rm objects
+rm Container
+rm shared
+rm toolkits
+rm io
+rm EnumDefinitions
+rm modules
+rm solutions
+rm solvers
+rm issm.h
Index: /issm/trunk-jpl-damage/src/ad/softlink.sh
===================================================================
--- /issm/trunk-jpl-damage/src/ad/softlink.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/softlink.sh	(revision 11330)
@@ -0,0 +1,14 @@
+#/bin/bash
+#This script soflinks all files in trunk/src/c/ directory necessary for compilation 
+#of trunk/src/ad/ 
+ln -s ../c/include 
+ln -s ../c/objects 
+ln -s ../c/Container 
+ln -s ../c/shared 
+ln -s ../c/toolkits 
+ln -s ../c/io 
+ln -s ../c/EnumDefinitions 
+ln -s ../c/modules 
+ln -s ../c/solutions 
+ln -s ../c/solvers 
+ln -s ../c/issm.h 
Index: /issm/trunk-jpl-damage/src/ad/todo
===================================================================
--- /issm/trunk-jpl-damage/src/ad/todo	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/todo	(revision 11330)
@@ -0,0 +1,30 @@
+Externalpackages: out into astrid-r1b
+
+Get a wiki together. OpenAD. Get ISSM website together.
+https://trac.mcs.anl.gov/projects/ADIC/wiki/ADIC/ISSM
+
+Switch to metis 5.0
+
+Hard stuff: 
+wrap MatSetValues and MatAssembly into one routine. 
+To do so, store Ke matrices into elements, do not add to global. 
+Once all the Ke are built, loop through them and do all the MatSetValues
+at once, followed by MatAssembly. 
+Do the same for VecSet and VecAssembly.
+
+Wrap all Petsc data types Matrix and Vector objects, and map all operations 
+onto these new objects.  Make this preprocessable for configuration using autotools.
+We will probably duplicate data, ex: 
+
+Matrix{
+	ifdef  PETSC_WRAPPER
+	Mat pmatrix; 
+	endif
+	ifdef  DOUBLE_WRAPPER
+	double* pmatrix; 
+	endif
+	adouble* amatrix;
+}
+
+amatrix will be used in adolc. pmatrix will be used in Petsc routines. Matrix will 
+have routines to map one into the other.
Index: /issm/trunk-jpl-damage/src/ad/validation.sh
===================================================================
--- /issm/trunk-jpl-damage/src/ad/validation.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/validation.sh	(revision 11330)
@@ -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/trunk-jpl-damage/src/ad/validation/Update/Square.exp
===================================================================
--- /issm/trunk-jpl-damage/src/ad/validation/Update/Square.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/validation/Update/Square.exp	(revision 11330)
@@ -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/trunk-jpl-damage/src/ad/validation/Update/SquareShelfConstrained.par
===================================================================
--- /issm/trunk-jpl-damage/src/ad/validation/Update/SquareShelfConstrained.par	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/validation/Update/SquareShelfConstrained.par	(revision 11330)
@@ -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.diagnostic.viscosity_overshoot=0.0;
+md.prognostic.stabilization=1;
+md.thermal.stabilization=1;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.diagnostic.restol=0.05;
+md.diagnostic.reltol=0.05;
+md.steadystate.reltol=0.05;
+md.diagnostic.abstol=NaN;
+md.timestepping.time_step=1;
+md.timestepping.final_time=3;
+
+%Deal with boundary conditions:
+md=SetIceShelfBC(md);
+md.miscellaneous.name='validation';
Index: /issm/trunk-jpl-damage/src/ad/validation/Update/update.m
===================================================================
--- /issm/trunk-jpl-damage/src/ad/validation/Update/update.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/validation/Update/update.m	(revision 11330)
@@ -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,'macayeal','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,PrognosticSolutionEnum);
+
+thickness=md.results.PrognosticSolution.Thickness;
+save ../Validation/Archive.mat thickness;
Index: /issm/trunk-jpl-damage/src/ad/validation/Validation/Makefile
===================================================================
--- /issm/trunk-jpl-damage/src/ad/validation/Validation/Makefile	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/validation/Validation/Makefile	(revision 11330)
@@ -0,0 +1,2 @@
+clean:
+	rm validation.lock validation.outlog validationRose.outlog
Index: /issm/trunk-jpl-damage/src/ad/validation/Validation/validation.m
===================================================================
--- /issm/trunk-jpl-damage/src/ad/validation/Validation/validation.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/validation/Validation/validation.m	(revision 11330)
@@ -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.PrognosticSolution.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/trunk-jpl-damage/src/ad/validation/Validation/validation.petsc
===================================================================
--- /issm/trunk-jpl-damage/src/ad/validation/Validation/validation.petsc	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/validation/Validation/validation.petsc	(revision 11330)
@@ -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/trunk-jpl-damage/src/ad/validation/Validation/validation.queue
===================================================================
--- /issm/trunk-jpl-damage/src/ad/validation/Validation/validation.queue	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/validation/Validation/validation.queue	(revision 11330)
@@ -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/trunk-jpl-damage/src/ad/validation/Validation/validationROSE.queue
===================================================================
--- /issm/trunk-jpl-damage/src/ad/validation/Validation/validationROSE.queue	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/validation/Validation/validationROSE.queue	(revision 11330)
@@ -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/trunk-jpl-damage/src/ad/wrappers.txt
===================================================================
--- /issm/trunk-jpl-damage/src/ad/wrappers.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/src/ad/wrappers.txt	(revision 11330)
@@ -0,0 +1,146 @@
+A typical prognostic solution calls the following routines: 
+
+		femmodel->SetCurrentConfiguration
+		femmodel->parameters->FindParam
+
+		solver_linear
+				femmodel->parameters->FindParam
+				UpdateConstraintsx
+						parameters->FindParam
+						SpcNodesx
+								constraint->ConstrainNode(nodes,parameters);
+						NodesDofx
+								nodes->NumberOfNodes
+										MPI_Allreduce 
+								nodes->FlagClones
+										this->NumberOfNodes
+										Ranks
+										MPI_Allreduce 
+										node->SetClone
+								nodes->DistributeDofs
+										node->InAnalysis
+										node->DistributeDofs
+										MPI_Gather
+										MPI_Bcast
+										node->OffsetDofs
+										this->MaxNumDofs
+										this->NumberOfNodes
+										node->ShowTrueDofs
+										MPI_Allreduce 
+										node->UpdateCloneDofs
+				SystemMatricesx
+						parameters->FindParam
+						nodes->NumberOfDofs
+						nodes->MaxNumDofs
+						NewMat
+						NewVec
+						element->CreateKMatrix
+						element->CreatePVector
+						load->CreateKMatrix
+						load->CreatePVector
+						MatAssemblyBegin
+						MatAssemblyEnd
+						MatCompress
+						VecAssemblyBegin
+						VecAssemblyEnd
+						MatNorm
+			CreateNodalConstraintsx
+						nodes->NumberOfDofs
+						ys=NewVec
+						node->CreateNodalConstraints
+						VecAssemblyBegin
+						VecAssemblyEnd
+			Reduceloadx
+						MatGetSize
+						MatGetLocalSize
+						NewVec
+						VecDuplicate
+						VecSet
+						VecAssemblyBegin
+						VecAssemblyEnd
+						MatMultPatch
+						MatMultPatch
+						VecAXPY(pf,a,Kfsy_s);  
+						VecFree
+			Solverx
+						MatGetSize
+						PetscOptionsGetString
+						VecDuplicate
+						MatGetLocalSize
+						PetscOptionsDetermineSolverType
+						MatConvert
+						KSPCreate
+						KSPSetOperators
+						KSPSetFromOptions
+						KSPGetPC
+						PCFactorSetMatSolverPackage
+						KSPSolve
+						KSPGetIterationNumber
+						KSPFree
+			Mergesolutionfromftogx
+						parameters->FindParam
+						nodes->NumberOfDofs
+						VecSet(ys,0.0);
+						NewVec
+						VecMergex
+						VecMergex
+			InputUpdateFromSolutionx
+						VecToMPISerial
+						InputUpdateFromSolutionx
+						element->InputUpdateFromSolution
+			VecFree
+
+		InputToResultx
+						element->InputToResult(enum_type,step,time);
+
+
+
+
+
+The resulting MPI routines that are called are the following: 
+
+MPI_Allreduce 
+MPI_Allreduce 
+MPI_Gather
+MPI_Bcast
+MPI_Allreduce 
+
+The resulting PETSC routines that are called are the following:
+
+MatAssemblyBegin
+MatAssemblyEnd
+MatSetValues
+MatCompress
+MatNorm
+MatGetSize
+MatGetLocalSize
+MatConvert
+
+VecDuplicate
+VecSet
+VecAssemblyBegin
+VecAssemblyEnd
+VecAXPY
+
+KSPCreate
+KSPSetOperators
+KSPSetFromOptions
+KSPGetPC
+KSPSetUp
+KSPSolve
+KSPGetIterationNumber
+PCFactorSetMatSolverPackage
+VecSet
+
+
+The resulting routines are wrappers to PETSC routines, with essentially a PETSC flavor to it: 
+
+NewMat
+NewVec
+MatMultPatch
+PetscOptionsGetString
+PetscOptionsDetermineSolverType
+VecMergex
+VecToMPISerial
+VecFree
+KSPFree
Index: /issm/trunk-jpl-damage/src/c/Container/Constraints.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Constraints.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Constraints.cpp	(revision 11330)
@@ -0,0 +1,59 @@
+/*
+ * \file Constraints.c
+ * \brief: implementation of the Constraints class, derived from DataSet class
+ */
+
+/*Headers: {{{1*/
+#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 "./DataSet.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Constraints::Constraints(){{{1*/
+Constraints::Constraints(){
+	enum_type=ConstraintsEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Constraints::~Constraints(){{{1*/
+Constraints::~Constraints(){
+	return;
+}
+/*}}}*/
+
+/*Numerics: */
+/*FUNCTION Constraints::NumberOfConstraints{{{1*/
+int Constraints::NumberOfConstraints(void){
+
+	int localconstraints;
+	int numberofconstraints;
+
+	/*Get number of local constraints*/
+	localconstraints=this->Size();
+
+	/*figure out total number of constraints combining all the cpus (no clones here)*/
+	#ifdef _PARALLEL_
+	MPI_Reduce(&localconstraints,&numberofconstraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&numberofconstraints,1,MPI_INT,0,MPI_COMM_WORLD);
+	#else
+	numberofconstraints=localconstraints;
+	#endif
+
+	return numberofconstraints;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/Container/Constraints.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Constraints.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Constraints.h	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file: Constraints.h
+ * \brief prototypes for Constraints.h
+ */ 
+
+#ifndef _CONTAINER_CONSTRAINTS_H_
+#define  _CONTAINER_CONSTRAINTS_H_
+
+/*forward declarations */
+class Materials;
+class Parameters;
+class Elements;
+class Vertices;
+class Loads;
+class Nodes;
+class DataSet;
+class Inputs;
+
+
+class Constraints: public DataSet{
+
+	public:
+
+		/*constructors, destructors: {{{1*/
+		Constraints();
+		~Constraints();
+		/*}}}*/
+		/*numerics: {{{1*/
+		int   NumberOfConstraints(void);
+		/*}}}*/
+
+};
+
+
+#endif //ifndef _CONSTRAINTS_H_
+
Index: /issm/trunk-jpl-damage/src/c/Container/Container.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Container.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Container.h	(revision 11330)
@@ -0,0 +1,20 @@
+/*!\file: Container.h
+ * \brief prototypes for all containers used in ISSM
+ */ 
+
+#ifndef _CONTAINER_CONTAINER_H_
+#define  _CONTAINER_CONTAINER_H_
+
+#include "./DataSet.h"
+#include "./Constraints.h"
+#include "./Elements.h"
+#include "./Inputs.h"
+#include "./Loads.h"
+#include "./Materials.h"
+#include "./Nodes.h"
+#include "./Options.h"
+#include "./Parameters.h"
+#include "./Results.h"
+#include "./Vertices.h"
+
+#endif //ifndef _CONTAINER_H_
Index: /issm/trunk-jpl-damage/src/c/Container/DataSet.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/DataSet.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/DataSet.cpp	(revision 11330)
@@ -0,0 +1,588 @@
+/*
+ * \file DataSet.c
+ * \brief: implementation of the DataSet class, and derived classes Inputs and Parameters
+ */
+
+/*Headers: {{{1*/
+#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 "./DataSet.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+using namespace std;
+/*}}}*/
+
+/*Constructors/Destructors*/
+/*FUNCTION DataSet::DataSet(){{{1*/
+DataSet::DataSet(){
+	
+	sorted=0;
+	sorted_ids=NULL;
+	id_offsets=NULL;
+
+}
+/*}}}*/
+/*FUNCTION DataSet::DataSet(int dataset_enum){{{1*/
+DataSet::DataSet(int dataset_enum){
+	enum_type=dataset_enum;
+	
+	sorted=0;
+	sorted_ids=NULL;
+	id_offsets=NULL;
+
+}
+/*}}}*/
+/*FUNCTION DataSet::Copy{{{1*/
+DataSet*   DataSet::Copy(void){
+
+	DataSet* copy=NULL;
+	vector<Object*>::iterator object;
+	Object* object_copy=NULL;
+
+	copy=new DataSet(enum_type);
+
+	copy->sorted=sorted;
+	copy->presorted=presorted;
+	if(sorted_ids){
+		copy->sorted_ids=(int*)xmalloc(objects.size()*sizeof(int));
+		memcpy(copy->sorted_ids,sorted_ids,objects.size()*sizeof(int));
+	}
+	if(id_offsets){
+		copy->id_offsets=(int*)xmalloc(objects.size()*sizeof(int));
+		memcpy(copy->id_offsets,id_offsets,objects.size()*sizeof(int));
+	}
+
+	/*Now we need to deep copy the objects: */
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Call echo on object: */
+		object_copy = (*object)->copy();
+		copy->AddObject(object_copy);
+	}
+	return copy;
+}
+/*}}}*/
+/*FUNCTION DataSet::~DataSet{{{1*/
+DataSet::~DataSet(){
+	clear();
+	xfree((void**)&sorted_ids);
+	xfree((void**)&id_offsets);
+}
+/*}}}*/
+
+/*I/O*/
+#ifdef _SERIAL_
+/*FUNCTION DataSet::Marshall{{{1*/
+char* DataSet::Marshall(){
+
+	vector<Object*>::iterator object;
+	int                       object_size;
+	int                       marshalled_dataset_size=0;
+	char*                     marshalled_dataset=NULL;
+	char*                     old_marshalled_dataset=NULL;
+
+	/*First get size of marshalled dataset: */
+	object_size=(int)objects.size();
+
+	marshalled_dataset_size=MarshallSize();
+	
+	/*Allocate marshalled dataset: */
+	marshalled_dataset=(char*)xmalloc(marshalled_dataset_size*sizeof(char)); 
+
+	/*Keep track of old_marshalled_dataset: */
+	old_marshalled_dataset=marshalled_dataset;
+
+	/*Store internals of dataset first: */
+	memcpy(marshalled_dataset,&object_size,sizeof(int)); marshalled_dataset+=sizeof(int);
+	memcpy(marshalled_dataset,&sorted,sizeof(int)); marshalled_dataset+=sizeof(int);
+	if(sorted){
+		if(object_size)memcpy(marshalled_dataset,sorted_ids,object_size*sizeof(int)); marshalled_dataset+=object_size*sizeof(int);
+		if(object_size)memcpy(marshalled_dataset,id_offsets,object_size*sizeof(int)); marshalled_dataset+=object_size*sizeof(int);
+	}
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+		(*object)->Marshall(&marshalled_dataset);
+	}
+
+	/* Ok, marshalled_dataset now points to the end of the original marshalled_dataset pointer 
+	 * before  we started the loop on objects. Get object to point right again: */
+	marshalled_dataset-=marshalled_dataset_size;
+
+	/*We should be back to old_marshalled_dataset: check and abort if that's not the case, 
+	 * because this is a nasty error: */
+	if (marshalled_dataset!=old_marshalled_dataset){
+		_error_("final marshalled dataset \"%s\" is different from initial one!",EnumToStringx(enum_type)); 
+		abort();
+	}
+
+	/*Return: */
+	return marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION DataSet::MarshallSize{{{1*/
+int DataSet::MarshallSize(){
+
+	vector<Object*>::iterator object;
+	int                      marshalled_dataset_size=0;
+
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+		marshalled_dataset_size+= (*object)->MarshallSize();
+	}
+
+	marshalled_dataset_size+=sizeof(int); //objects size
+	marshalled_dataset_size+=sizeof(int); //sorted size
+	if(sorted){
+		marshalled_dataset_size+=(int)objects.size()*sizeof(int); //sorted ids
+		marshalled_dataset_size+=(int)objects.size()*sizeof(int); //id offsets
+	}
+
+	return marshalled_dataset_size;
+}
+/*}}}*/
+/*FUNCTION DataSet::Demarshall{{{1*/
+DataSet* DataSetDemarshall(char* marshalled_dataset){
+
+	return DataSetDemarshallRaw(&marshalled_dataset);
+
+}
+/*}}}*/
+/*FUNCTION DataSet::DemarshallRaw{{{1*/
+DataSet* DataSetDemarshallRaw(char** pmarshalled_dataset){
+
+	int i;
+
+	DataSet* dataset=NULL;
+	int      numobjects=0;
+	int      enum_type;
+	Object*  object=NULL;
+	int      sorted;
+	int*     sorted_ids=NULL;
+	int*     id_offsets=NULL;
+	char*    marshalled_dataset=NULL;
+
+	/*recover marshalled_dataset pointer: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*initialize dataset: */
+	dataset=new DataSet();
+
+	/*Get internals first: */
+	memcpy(&numobjects,marshalled_dataset,sizeof(int)); marshalled_dataset+=sizeof(int);
+	memcpy(&sorted,marshalled_dataset,sizeof(int)); marshalled_dataset+=sizeof(int);
+	if(sorted){
+		if(numobjects){
+			sorted_ids=(int*)xmalloc(numobjects*sizeof(int));
+			id_offsets=(int*)xmalloc(numobjects*sizeof(int));
+			memcpy(sorted_ids,marshalled_dataset,numobjects*sizeof(int)); marshalled_dataset+=numobjects*sizeof(int);
+			memcpy(id_offsets,marshalled_dataset,numobjects*sizeof(int)); marshalled_dataset+=numobjects*sizeof(int);
+		}
+		dataset->SetSorting(sorted_ids,id_offsets);
+	}
+
+	for(i=0;i<numobjects;i++){
+
+		/*get enum type of object: */
+		memcpy(&enum_type,marshalled_dataset,sizeof(int)); marshalled_dataset+=sizeof(int);
+
+		switch(enum_type){
+			case NodeEnum:{
+				Node* node=NULL;
+				node=new Node();
+				node->Demarshall(&marshalled_dataset);
+				dataset->AddObject(node);}
+				break;
+			case VertexEnum:{
+				Vertex* vertex=NULL;
+				vertex=new Vertex();
+				vertex->Demarshall(&marshalled_dataset);
+				dataset->AddObject(vertex);}
+				break;
+			case DoubleParamEnum:{
+				DoubleParam* doubleparam=NULL;
+				doubleparam=new DoubleParam();
+				doubleparam->Demarshall(&marshalled_dataset);
+				dataset->AddObject(doubleparam);}
+				break;
+			case TriaEnum:{
+				Tria* tria=NULL;
+				tria=new Tria();
+				tria->Demarshall(&marshalled_dataset);
+				dataset->AddObject(tria);}
+				break;
+			case TriaP1InputEnum:{
+				TriaP1Input* triavertexinput=NULL;
+				triavertexinput=new TriaP1Input();
+				triavertexinput->Demarshall(&marshalled_dataset);
+				dataset->AddObject(triavertexinput);}
+				break;
+			#ifdef _HAVE_THREED_
+			case PentaP1InputEnum:{
+				PentaP1Input* pentavertexinput=NULL;
+				pentavertexinput=new PentaP1Input();
+				pentavertexinput->Demarshall(&marshalled_dataset);
+				dataset->AddObject(pentavertexinput);}
+				break;
+			#endif
+			case TransientInputEnum:{
+				TransientInput* transientinput=NULL;
+				transientinput=new TransientInput();
+				transientinput->Demarshall(&marshalled_dataset);
+				dataset->AddObject(transientinput);}
+				break;
+			#ifdef _HAVE_CONTROL_
+			case ControlInputEnum:{
+			   ControlInput* controlinputinput=NULL;
+				controlinputinput=new ControlInput();
+				controlinputinput->Demarshall(&marshalled_dataset);
+				dataset->AddObject(controlinputinput);}
+				break;
+			#endif
+			case DatasetInputEnum:{
+				DatasetInput* datasetinputinput=NULL;
+				datasetinputinput=new DatasetInput();
+				datasetinputinput->Demarshall(&marshalled_dataset);
+				dataset->AddObject(datasetinputinput);}
+				break;
+			case TriaP1ElementResultEnum:{
+				TriaP1ElementResult* triavertexelementresult=NULL;
+				triavertexelementresult=new TriaP1ElementResult();
+				triavertexelementresult->Demarshall(&marshalled_dataset);
+				dataset->AddObject(triavertexelementresult);}
+				break;
+			 #ifdef _HAVE_THREED_
+			case PentaP1ElementResultEnum:{
+				PentaP1ElementResult* pentavertexelementresult=NULL;
+				pentavertexelementresult=new PentaP1ElementResult();
+				pentavertexelementresult->Demarshall(&marshalled_dataset);
+				dataset->AddObject(pentavertexelementresult);}
+				break;
+			case PentaEnum:{
+				Penta* penta=NULL;
+				penta=new Penta();
+				penta->Demarshall(&marshalled_dataset);
+				dataset->AddObject(penta);}
+				break;
+			#endif
+			case MaticeEnum:{
+				Matice* matice=NULL;
+				matice=new Matice();
+				matice->Demarshall(&marshalled_dataset);
+				dataset->AddObject(matice);}
+				break;
+			case MatparEnum:{
+				Matpar* matpar=NULL;
+				matpar=new Matpar();
+				matpar->Demarshall(&marshalled_dataset);
+				dataset->AddObject(matpar);}
+				break;
+			case SpcStaticEnum:{
+				SpcStatic* spcstatic=NULL;
+				spcstatic=new SpcStatic();
+				spcstatic->Demarshall(&marshalled_dataset);
+				dataset->AddObject(spcstatic);}
+				break;
+			case SpcDynamicEnum:{
+				SpcDynamic* spcdynamic=NULL;
+				spcdynamic=new SpcDynamic();
+				spcdynamic->Demarshall(&marshalled_dataset);
+				dataset->AddObject(spcdynamic);}
+				break;
+			case SpcTransientEnum:{
+				SpcTransient* spctransient=NULL;
+				spctransient=new SpcTransient();
+				spctransient->Demarshall(&marshalled_dataset);
+				dataset->AddObject(spctransient);}
+				break;
+			case PengridEnum:{
+				Pengrid* pengrid=NULL;
+				pengrid=new Pengrid();
+				pengrid->Demarshall(&marshalled_dataset);
+				dataset->AddObject(pengrid);}
+				break;
+			case PenpairEnum:{
+				Penpair* penpair=NULL;
+				penpair=new Penpair();
+				penpair->Demarshall(&marshalled_dataset);
+				dataset->AddObject(penpair);}
+				break;
+			case IcefrontEnum:{
+				Icefront* icefront=NULL;
+				icefront=new Icefront();
+				icefront->Demarshall(&marshalled_dataset);
+				dataset->AddObject(icefront);}
+				break;
+			case NumericalfluxEnum:{
+				Numericalflux* numericalflux=NULL;
+				numericalflux=new Numericalflux();
+				numericalflux->Demarshall(&marshalled_dataset);
+				dataset->AddObject(numericalflux);}
+				break;
+			#ifdef _HAVE_RIFTS_
+			case RiftfrontEnum:{
+				Riftfront* riftfront=NULL;
+				riftfront=new Riftfront();
+				riftfront->Demarshall(&marshalled_dataset);
+				dataset->AddObject(riftfront);}
+				break;
+			#endif
+			case DoubleInputEnum:{
+				DoubleInput* doubleinput=NULL;
+				doubleinput=new DoubleInput();
+				doubleinput->Demarshall(&marshalled_dataset);
+				dataset->AddObject(doubleinput);}
+				break;
+			case IntInputEnum:{
+				IntInput* intinput=NULL;
+				intinput=new IntInput();
+				intinput->Demarshall(&marshalled_dataset);
+				dataset->AddObject(intinput);}
+				break;
+			case BoolInputEnum:{
+				BoolInput* boolinput=NULL;
+				boolinput=new BoolInput();
+				boolinput->Demarshall(&marshalled_dataset);
+				dataset->AddObject(boolinput);}
+				break;
+			case IntParamEnum:{
+				IntParam* intparam=NULL;
+				intparam=new IntParam();
+				intparam->Demarshall(&marshalled_dataset);
+				dataset->AddObject(intparam);}
+				break;
+			case BoolParamEnum:{
+				BoolParam* boolparam=NULL;
+				boolparam=new BoolParam();
+				boolparam->Demarshall(&marshalled_dataset);
+				dataset->AddObject(boolparam);}
+				break;
+			case StringParamEnum:{
+				StringParam* stringparam=NULL;
+				stringparam=new StringParam();
+				stringparam->Demarshall(&marshalled_dataset);
+				dataset->AddObject(stringparam);}
+				break;
+			case DoubleVecExternalResultEnum:{
+				DoubleVecExternalResult* doublevecexternalresult=NULL;
+				doublevecexternalresult=new DoubleVecExternalResult();
+				doublevecexternalresult->Demarshall(&marshalled_dataset);
+				dataset->AddObject(doublevecexternalresult);}
+				break;
+			case DoubleExternalResultEnum:{
+				DoubleExternalResult* doubleexternalresult=NULL;
+				doubleexternalresult=new DoubleExternalResult();
+				doubleexternalresult->Demarshall(&marshalled_dataset);
+				dataset->AddObject(doubleexternalresult);}
+				break;
+			#ifdef _HAVE_GROUNDINGLINE_
+			case BoolElementResultEnum:{
+				BoolElementResult* boolelementresult=NULL;
+				boolelementresult=new BoolElementResult();
+				boolelementresult->Demarshall(&marshalled_dataset);
+				dataset->AddObject(boolelementresult);}
+				break;
+			#endif
+			default:
+				_error_("could not recognize enum type: %s",EnumToStringx(enum_type));
+		}
+	}
+
+	/*Assign output pointers:*/
+	*pmarshalled_dataset=marshalled_dataset;
+	
+	return dataset;
+}
+/*}}}*/
+#endif
+
+/*Specific methods*/
+/*FUNCTION DataSet::AddObject{{{1*/
+int  DataSet::AddObject(Object* object){
+
+	objects.push_back(object);
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION DataSet::clear{{{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();
+}
+/*}}}*/
+/*FUNCTION DataSet::DeleteObject{{{1*/
+int  DataSet::DeleteObject(Object* object){
+
+	vector<Object*>::iterator iterator;
+
+	if(object){
+		iterator = find(objects.begin(), objects.end(),object);
+		delete *iterator;
+		objects.erase(iterator);
+	}
+
+	return 1;
+
+}
+/*}}}*/
+/*FUNCTION DataSet::DeepEcho{{{1*/
+void DataSet::DeepEcho(){
+
+
+	vector<Object*>::iterator object;
+
+	if(this==NULL)_error_(" trying to echo a NULL dataset");
+
+	_printf_(true,"DataSet echo: %i objects\n",objects.size());
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Call deep echo on object: */
+		(*object)->DeepEcho();
+
+	}
+}
+/*}}}*/
+/*FUNCTION DataSet::Echo{{{1*/
+void DataSet::Echo(){
+
+	vector<Object*>::iterator object;
+
+	if(this==NULL)_error_(" trying to echo a NULL dataset");
+
+	_printf_(true,"DataSet echo: %i objects\n",objects.size());
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Call echo on object: */
+		(*object)->Echo();
+
+	}
+	return;
+}
+/*}}}*/
+/*FUNCTION DataSet::GetEnum(){{{1*/
+int  DataSet::GetEnum(){
+	return enum_type;
+}
+/*}}}*/
+/*FUNCTION DataSet::GetEnum(int offset){{{1*/
+int   DataSet::GetEnum(int offset){
+
+	return objects[offset]->ObjectEnum();
+
+}
+/*}}}*/
+/*FUNCTION DataSet::GetObjectByOffset{{{1*/
+Object* DataSet::GetObjectByOffset(int offset){
+
+	/*Check index in debugging mode*/
+	_assert_(this!=NULL);
+	_assert_(offset<this->Size());
+
+	return objects[offset];
+
+}
+/*}}}*/
+/*FUNCTION DataSet::GetObjectById{{{1*/
+Object* DataSet::GetObjectById(int* poffset,int eid){
+
+	int id_offset;
+	int offset;
+	int i;
+
+	_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 %i in DataSet %s",eid,EnumToStringx(enum_type));
+	}
+
+	/*Convert  the id offset into sorted offset: */
+	offset=id_offsets[id_offset];
+
+	/*Assign output pointers if requested:*/
+	if (poffset)*poffset=offset;
+
+	/*Return object at offset position in objects :*/
+	return objects[offset];
+}
+/*}}}*/
+/*FUNCTION DataSet::Presort{{{1*/
+void DataSet::Presort(){
+
+	/*vector of objects is already sorted, just allocate the sorted ids and their
+	 * offsets:*/
+	int i;
+
+	if(objects.size()){
+
+		/*Delete existing ids*/
+		xfree((void**)&sorted_ids);
+		xfree((void**)&id_offsets);
+
+		/*Allocate new ids*/
+		sorted_ids=(int*)xmalloc(objects.size()*sizeof(int));
+		id_offsets=(int*)xmalloc(objects.size()*sizeof(int));
+
+		/*Build id_offsets and sorted_ids*/
+		for(i=0;i<objects.size();i++){
+			id_offsets[i]=i;
+			sorted_ids[i]=objects[i]->Id();
+		}
+	}
+
+	/*set sorted flag: */
+	sorted=1;
+}
+/*}}}*/
+/*FUNCTION DataSet::SetSorting{{{1*/
+void DataSet::SetSorting(int* in_sorted_ids,int* in_id_offsets){
+
+	sorted=1;
+	sorted_ids=in_sorted_ids;
+	id_offsets=in_id_offsets;
+}
+/*}}}*/
+/*FUNCTION DataSet::Size{{{1*/
+int  DataSet::Size(void){
+	_assert_(this!=NULL);
+
+	return objects.size();
+}
+/*}}}*/
+/*FUNCTION DataSet::Sort{{{1*/
+void DataSet::Sort(){
+
+	/*Only sort if we are not already sorted: */
+	if(!sorted){
+		_error_(" not implemented yet!");
+	}
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/Container/DataSet.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/DataSet.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/DataSet.h	(revision 11330)
@@ -0,0 +1,79 @@
+/*
+ * DataSet.h: declaration of DataSet,Parameters and Inputs classes
+ */
+
+#ifndef _CONTAINER_DATASET_H_
+#define _CONTAINER_DATASET_H_
+
+#include <vector>
+#include "../objects/Object.h"
+#include "../toolkits/toolkits.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+/*forward declarations */
+
+class Elements;
+class Loads;
+class Nodes;
+class Vertices;
+class Materials;
+class Parameters;
+class Patch;
+class Results;
+class Patch;
+
+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: {{{1*/
+		DataSet();
+		DataSet(int enum_type);
+		~DataSet();
+		/*}}}*/
+		/*management: {{{1*/
+		int   GetEnum();
+		int   GetEnum(int offset);
+		void  Echo();
+		void  DeepEcho();
+		#ifdef _SERIAL_
+		char* Marshall();
+		int   MarshallSize();
+		#endif
+		int   AddObject(Object* object);
+		int   DeleteObject(int id);
+		int   Size();
+		void  clear();
+		Object* GetObjectByOffset(int offset);
+		Object* GetObjectById(int* poffset,int eid);
+		void  Presort();
+		void  SetSorting(int* in_sorted_ids,int* in_id_offsets);
+		void  Sort();
+		DataSet* Copy(void);
+		int   DeleteObject(Object* object);
+		Results* SpawnTriaResults(int* indices);
+		/*}}}*/
+
+};
+
+/*This routine cannot be object oriented, but need for demarshalling: */
+#ifdef _SERIAL_
+DataSet* DataSetDemarshall(char* marshalled_dataset);
+DataSet* DataSetDemarshallRaw(char** pmarshalled_dataset);
+#endif
+	
+
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/Container/Elements.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Elements.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Elements.cpp	(revision 11330)
@@ -0,0 +1,289 @@
+/*
+ * \file Elements.c
+ * \brief: implementation of the Elements class, derived from DataSet class
+ */
+
+/*Headers: {{{1*/
+#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 "./DataSet.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Elements::Elements(){{{1*/
+Elements::Elements(){
+	enum_type=MeshElementsEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Elements::~Elements(){{{1*/
+Elements::~Elements(){
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+/*FUNCTION Elements::Configure{{{1*/
+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=(Element*)(*object);
+		element->Configure(elements,loads,nodes,materials,parameters);
+
+	}
+
+}
+/*}}}*/
+/*FUNCTION Elements::ProcessResultsUnits{{{1*/
+void Elements::ProcessResultsUnits(void){
+
+	//Process results to be output in the correct units
+	for(int i=0;i<this->Size();i++){
+		Element* element=(Element*)this->GetObjectByOffset(i);
+		element->ProcessResultsUnits();
+	}
+}
+/*}}}*/
+/*FUNCTION Elements::DeleteResults{{{1*/
+void Elements::DeleteResults(void){
+	
+	for (int i=0;i<this->Size();i++){
+		Element* element=(Element*)this->GetObjectByOffset(i);
+		element->DeleteResults();
+	}
+}
+/*}}}*/
+/*FUNCTION Elements::ResultsToPatch{{{1*/
+Patch* Elements::ResultsToPatch(void){ 
+
+	/*output: */
+	Patch* patch=NULL;
+
+	/*intermediary: */
+	int i;
+	int count;
+	int numrows;
+	int numvertices;
+	int numnodes;
+	int max_numvertices;
+	int max_numnodes;
+	int element_numvertices;
+	int element_numrows;
+	int element_numnodes;
+
+	/*We are going to extract from the results within the elements, the desired results , and create a table 
+	 * of patch information, that will hold, for each element that computed the result that 
+	 * we desire, the enum_type of the result, the step and time, the id of the element, the interpolation type, the vertices ids, and the values 
+	 * at the nodes (could be different from the vertices). This will be used for visualization purposes. 
+	 * For example, we could build the following patch table, for velocities: 
+	 * 
+	 1. on a Beam element, Vx, at step 1, time .5, element id 1, interpolation type P0 (constant), vertices ids 1 and 2, one constant value 4.5
+	 VxEnum 1  .5  1 P0  1 2       4.5 NaN  NaN
+	 2. on a Tria element, Vz, at step 2, time .8, element id 2, interpolation type P1 (linear), vertices ids 1 3 and 4, with values at 3 nodes 4.5, 3.2, 2.5
+	 VzEnum 2  .8  2 P1  1 3 4     4.5 3.2  2.5
+	 * ... etc ...
+	 *
+	 * So what do we need to build the table: the maximum number of vertices included in the table, 
+	 * and the maximum number of nodal values, as well as the number of rows. Once we have that, 
+	 * we ask the elements to fill their own row in the table, by looping on the elememnts. 
+	 *
+	 * We will use the Patch object, which will store all of the information needed, and will be able 
+	 * to output itself to disk on its own. See object/Patch.h for format of this object.*/
+	
+	/*First, determine maximum number of vertices, nodes, and number of results: */
+	numrows=0;
+	numvertices=0;
+	numnodes=0;
+
+	for(i=0;i<this->Size();i++){
+
+		Element* element=(Element*)this->GetObjectByOffset(i);
+		element->PatchSize(&element_numrows,&element_numvertices,&element_numnodes);
+
+		numrows+=element_numrows;
+		if(element_numvertices>numvertices)numvertices=element_numvertices;
+		if(element_numnodes>numnodes)numnodes=element_numnodes;
+	}
+
+	#ifdef _PARALLEL_
+	/*Synchronize across cluster, so as to not end up with different sizes for each patch on each cpu: */
+	MPI_Reduce (&numvertices,&max_numvertices,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
+	MPI_Bcast(&max_numvertices,1,MPI_INT,0,MPI_COMM_WORLD);
+	numvertices=max_numvertices;
+
+	MPI_Reduce (&numnodes,&max_numnodes,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
+	MPI_Bcast(&max_numnodes,1,MPI_INT,0,MPI_COMM_WORLD);
+	numnodes=max_numnodes;
+	#endif
+
+	/*Ok, initialize Patch object: */
+	patch=new Patch(numrows,numvertices,numnodes);
+
+	/*Now, go through elements, and fill the Patch object: */
+	count=0;
+	for(i=0;i<this->Size();i++){
+		Element* element=(Element*)this->GetObjectByOffset(i);
+		element->PatchFill(&count,patch);
+	}
+
+	return patch;
+}
+/*}}}*/
+/*FUNCTION Elements::SetCurrentConfiguration{{{1*/
+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=(Element*)(*object);
+		element->SetCurrentConfiguration(elements,loads,nodes,materials,parameters);
+
+	}
+
+}
+/*}}}*/
+/*FUNCTION Elements::ToResults{{{1*/
+void Elements::ToResults(Results* results,Parameters* parameters){
+
+	extern int my_rank;
+	extern int num_procs;
+
+	Patch  *patch        = NULL;
+	int    *resultsenums = NULL;
+	int    *resultssizes  = NULL;
+	int    *resultssteps  = NULL;
+	double *resultstimes = NULL;
+	double *vector_serial= NULL;
+	Vec     vector       = NULL;
+	bool   io_gather;
+	bool   results_as_patches;
+	int    numberofvertices,numberofelements;
+	int    numberofresults,vectorsize;
+
+	/*Recover parameters: */
+	parameters->FindParam(&io_gather,SettingsIoGatherEnum);
+	parameters->FindParam(&results_as_patches,SettingsResultsAsPatchesEnum);
+	parameters->FindParam(&numberofvertices,MeshNumberofverticesEnum);
+	parameters->FindParam(&numberofelements,MeshNumberofelementsEnum);
+
+	if(!results_as_patches){
+		/*No patch here, we prepare vectors*/
+
+		/*see what the first element of this partition has in stock (this is common to all partitions)*/
+		if(my_rank==0){
+			if(this->Size()==0) _error_("Cannot write results because first partition has no element. Maybe too many cpus were requested");
+			Element* element=(Element*)this->GetObjectByOffset(0);
+			element->ListResultsInfo(&resultsenums,&resultssizes,&resultstimes,&resultssteps,&numberofresults);
+		}
+		MPI_Bcast(&numberofresults,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+		/*Get out if there is no results. Otherwise broadcast info*/
+		if(!numberofresults) return;
+		if(my_rank!=0){
+			resultsenums=(int*)xmalloc(numberofresults*sizeof(int));
+			resultssizes=(int*)xmalloc(numberofresults*sizeof(int));
+			resultstimes=(double*)xmalloc(numberofresults*sizeof(double));
+			resultssteps=(int*)xmalloc(numberofresults*sizeof(int));
+		}
+		MPI_Bcast(resultsenums,numberofresults,MPI_INT,0,MPI_COMM_WORLD);
+		MPI_Bcast(resultssizes,numberofresults,MPI_INT,0,MPI_COMM_WORLD);
+		MPI_Bcast(resultstimes,numberofresults,MPI_DOUBLE,0,MPI_COMM_WORLD);
+		MPI_Bcast(resultssteps,numberofresults,MPI_INT,0,MPI_COMM_WORLD);
+
+		/*Loop over all results and get nodal vector*/
+		for(int i=0;i<numberofresults;i++){
+
+			/*Get vector for result number i*/
+			if(resultssizes[i]==P1Enum)      vectorsize=numberofvertices;
+			else if(resultssizes[i]==P0Enum) vectorsize=numberofelements;
+			else _error_("Unkown result size: %s",EnumToStringx(resultssizes[i]));
+			vector=NewVec(vectorsize);
+
+			for(int j=0;j<this->Size();j++){
+				Element* element=(Element*)this->GetObjectByOffset(j);
+				element->GetVectorFromResults(vector,i,resultssizes[i]);
+			}
+			VecAssemblyBegin(vector);
+			VecAssemblyEnd(vector);
+
+			/*Serialize and add to results*/
+			VecToMPISerial(&vector_serial,vector);
+			if(my_rank==0){
+				/*No need to add this vector for all cpus*/
+				results->AddObject(new DoubleVecExternalResult(results->Size()+1,resultsenums[i],vector_serial,vectorsize,resultssteps[i],resultstimes[i]));
+			}
+
+			/*clean up*/
+			VecFree(&vector);
+			xfree((void**)&vector_serial);
+		}
+	}
+	else{
+		/*create patch object out of all results in this dataset: */
+		patch=this->ResultsToPatch();
+
+		/*Gather onto master cpu 0, if needed: */
+#ifdef _PARALLEL_
+		if(io_gather)patch->Gather();
+#endif
+
+		/*create result object and add to results dataset:*/
+		if (patch->maxvertices && patch->maxnodes){
+			results->AddObject(new IntExternalResult(results->Size()+1,PatchVerticesEnum,patch->maxvertices,1,0));
+			results->AddObject(new IntExternalResult(results->Size()+1,PatchNodesEnum,   patch->maxnodes,1,0));
+			results->AddObject(new DoubleMatExternalResult(results->Size()+1,PatchEnum,  patch->values,patch->numrows,patch->numcols,1,0));
+		}
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&resultsenums);
+	xfree((void**)&resultssizes);
+	xfree((void**)&resultstimes);
+	xfree((void**)&resultssteps);
+	delete patch;
+}
+/*}}}*/
+/*FUNCTION Elements::NumberOfElements{{{1*/
+int Elements::NumberOfElements(void){
+
+	int local_nelem=0;
+	int numberofelements;
+
+	#ifdef _PARALLEL_
+	local_nelem=this->Size();
+	MPI_Allreduce ( (void*)&local_nelem,(void*)&numberofelements,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
+	#else
+	numberofelements=this->Size();
+	#endif
+
+	return numberofelements;
+}
+/*}}}*/
+/*FUNCTION Elements::InputCopy{{{1*/
+void Elements::InputDuplicate(int input_enum,int output_enum){
+
+	for(int i=0;i<this->Size();i++){
+		Element* element=(Element*)this->GetObjectByOffset(i);
+		element->InputDuplicate(input_enum,output_enum);
+	}
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/Container/Elements.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Elements.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Elements.h	(revision 11330)
@@ -0,0 +1,40 @@
+/*!\file: Elements.h
+ * \brief prototypes for Elements.h
+ */ 
+
+#ifndef _CONTAINER_ELEMENTS_H_
+#define  _CONTAINER_ELEMENTS_H_
+
+/*forward declarations */
+class Materials;
+class Parameters;
+class Elements;
+class Vertices;
+class Loads;
+class Nodes;
+class DataSet;
+class Inputs;
+
+
+class Elements: public DataSet{
+
+	public:
+
+		/*constructors, destructors: {{{1*/
+		Elements();
+		~Elements();
+		/*}}}*/
+		/*numerics: {{{1*/
+		void Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		void DeleteResults(void);
+		void ProcessResultsUnits(void);
+		void SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		void ToResults(Results* results,Parameters* parameters);
+		Patch* ResultsToPatch(void);
+		int   NumberOfElements(void);
+		void InputDuplicate(int input_enum,int output_enum);
+		/*}}}*/
+
+};
+
+#endif //ifndef _ELEMENTS_H_
Index: /issm/trunk-jpl-damage/src/c/Container/Inputs.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Inputs.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Inputs.cpp	(revision 11330)
@@ -0,0 +1,439 @@
+/*
+ * \file Inputs.c
+ * \brief: implementation of the Inputs class, derived from DataSet class
+ */
+
+/*Headers: {{{1*/
+#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 "./DataSet.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Inputs::Inputs(){{{1*/
+Inputs::Inputs(){
+	return;
+}
+/*}}}*/
+/*FUNCTION Inputs::~Inputs(){{{1*/
+Inputs::~Inputs(){
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+/*FUNCTION Inputs::GetInputValue(bool* pvalue,int enum-type){{{1*/
+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=(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 %i (%s)",enum_type,EnumToStringx(enum_type));
+	}
+
+	/*Ok, we have an input if we made it here, request the input to return the value: */
+	input->GetInputValue(pvalue);
+
+}
+/*}}}*/
+/*FUNCTION Inputs::GetInputValue(int* pvalue,int enum-type){{{1*/
+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=(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 %i (%s)",enum_type,EnumToStringx(enum_type));
+	}
+
+	/*Ok, we have an input if we made it here, request the input to return the value: */
+	input->GetInputValue(pvalue);
+
+}
+/*}}}*/
+/*FUNCTION Inputs::GetInputValue(double* pvalue,int enum-type){{{1*/
+void Inputs::GetInputValue(double* 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=(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 %i (%s)",enum_type,EnumToStringx(enum_type));
+	}
+
+	/*Ok, we have an input if we made it here, request the input to return the value: */
+	input->GetInputValue(pvalue);
+
+}
+/*}}}*/
+/*FUNCTION Inputs::GetInputAverage{{{1*/
+void Inputs::GetInputAverage(double* 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=(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 %i (%s)",enum_type,EnumToStringx(enum_type));
+	}
+
+	/*Ok, we have an input if we made it here, request the input to return the value: */
+	input->GetInputAverage(pvalue);
+
+}
+/*}}}*/
+/*FUNCTION Inputs::AddInput{{{1*/
+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=(Input*)(*object); 
+
+		if (input->InstanceEnum()==in_input->InstanceEnum()){
+			this->DeleteObject(input);
+			break;
+		}
+	}
+	this->AddObject(in_input);
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION Inputs::ChangeEnum{{{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=(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=(Input*)(*object); 
+
+		if (input->InstanceEnum()==oldenumtype){
+			input->ChangeEnum(newenumtype);
+			break;
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION Inputs::ConstrainMin{{{1*/
+void  Inputs::ConstrainMin(int constrain_enum, double minimum){
+	   
+	Input* constrain_input=NULL; 
+	/*Find x and y inputs: */
+	constrain_input=(Input*)this->GetInput(constrain_enum);
+
+	/*some checks: */
+	if(!constrain_input) _error_(" input %s could not be found!",EnumToStringx(constrain_enum));
+
+	/*Apply ContrainMin: */
+	constrain_input->ConstrainMin(minimum);
+}
+/*}}}*/
+/*FUNCTION Inputs::InfinityNorm{{{1*/
+double Inputs::InfinityNorm(int enumtype){
+
+	/*Output*/
+	double norm;
+
+	/*Get input*/
+	Input* input=(Input*)this->GetInput(enumtype);
+
+	/*Apply ContrainMin: */
+	if (input){
+		norm=input->InfinityNorm();
+	}
+	else{
+		norm=0;
+	}
+
+	/*Return output*/
+	return norm;
+}
+/*}}}*/
+/*FUNCTION Inputs::Max{{{1*/
+double Inputs::Max(int enumtype){
+
+	/*Output*/
+	double max;
+
+	/*Get input*/
+	Input* input=(Input*)this->GetInput(enumtype);
+
+	/*Apply ContrainMin: */
+	if (input){
+		max=input->Max();
+	}
+	else{
+		_error_("Input %s not found",EnumToStringx(enumtype));
+	}
+
+	/*Return output*/
+	return max;
+}
+/*}}}*/
+/*FUNCTION Inputs::MaxAbs{{{1*/
+double Inputs::MaxAbs(int enumtype){
+
+	/*Output*/
+	double max;
+
+	/*Get input*/
+	Input* input=(Input*)this->GetInput(enumtype);
+
+	/*Apply ContrainMin: */
+	if (input){
+		max=input->MaxAbs();
+	}
+	else{
+		_error_("Input %s not found",EnumToStringx(enumtype));
+	}
+
+	/*Return output*/
+	return max;
+}
+/*}}}*/
+/*FUNCTION Inputs::Min{{{1*/
+double Inputs::Min(int enumtype){
+
+	/*Output*/
+	double min;
+
+	/*Get input*/
+	Input* input=(Input*)this->GetInput(enumtype);
+
+	/*Apply ContrainMin: */
+	if (input){
+		min=input->Min();
+	}
+	else{
+		_error_("Input %s not found",EnumToStringx(enumtype));
+	}
+
+	/*Return output*/
+	return min;
+}
+/*}}}*/
+/*FUNCTION Inputs::MinAbs{{{1*/
+double Inputs::MinAbs(int enumtype){
+
+	/*Output*/
+	double min;
+
+	/*Get input*/
+	Input* input=(Input*)this->GetInput(enumtype);
+
+	/*Apply ContrainMin: */
+	if (input){
+		min=input->MinAbs();
+	}
+	else{
+		_error_("Input %s not found",EnumToStringx(enumtype));
+	}
+
+	/*Return output*/
+	return min;
+}
+/*}}}*/
+/*FUNCTION Inputs::GetInput{{{1*/
+Input* Inputs::GetInput(int enum_name){
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=(Input*)(*object); 
+
+		if (input->InstanceEnum()==enum_name){
+			return input;
+		}
+	}
+	return NULL;
+}
+/*}}}*/
+/*FUNCTION Inputs::DeleteInput{{{1*/
+int  Inputs::DeleteInput(int enum_type){
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=(Input*)(*object); 
+
+		if (input->InstanceEnum()==enum_type){
+			this->DeleteObject(input);
+			break;
+		}
+	}
+
+	return 1;
+
+}
+/*}}}*/
+/*FUNCTION Inputs::DuplicateInput{{{1*/
+void  Inputs::DuplicateInput(int original_enum,int new_enum){
+
+	Input* original=NULL;
+	Input* copy=NULL;
+
+	/*Make a copy of the original input: */
+	original=(Input*)this->GetInput(original_enum);
+	if(!original)_error_("could not find input with enum: %s",EnumToStringx(original_enum)); 
+	copy=(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((Input*)copy);
+}
+/*}}}*/
+/*FUNCTION Inputs::SpawnTriaInputs{{{1*/
+Inputs* Inputs::SpawnTriaInputs(int* indices){
+
+	/*Intermediary*/
+	vector<Object*>::iterator object;
+	Input* inputin=NULL;
+	Input* inputout=NULL;
+
+	/*Output*/
+	Inputs* newinputs=new Inputs();
+
+	/*Go through inputs and call Spawn function*/
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Create new input*/
+		inputin=(Input*)(*object); 
+		inputout=inputin->SpawnTriaInput(indices);
+
+		/*Add input to new inputs*/
+		newinputs->AddObject(inputout);
+	}
+
+	/*Assign output pointer*/
+	return newinputs;
+}
+/*}}}*/
+/*FUNCTION Inputs::AXPY{{{1*/
+void  Inputs::AXPY(int MeshYEnum, double scalar, int MeshXEnum){
+	   
+	Input* xinput=NULL;
+	Input* yinput=NULL;
+
+	/*Find x and y inputs: */
+	xinput=(Input*)this->GetInput(MeshXEnum);
+	yinput=(Input*)this->GetInput(MeshYEnum);
+
+	/*some checks: */
+	if(!xinput) _error_(" input %s could not be found!",EnumToStringx(MeshXEnum));
+	if(!yinput) _error_(" input %s could not be found!",EnumToStringx(MeshYEnum));
+
+	/*Apply AXPY: */
+	yinput->AXPY(xinput,scalar);
+}
+/*}}}*/
+/*FUNCTION Inputs::Configure{{{1*/
+void Inputs::Configure(Parameters* parameters){
+
+	vector<Object*>::iterator object;
+	Input* input=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		input=(Input*)(*object);
+		input->Configure(parameters);
+
+	}
+
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/Container/Inputs.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Inputs.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Inputs.h	(revision 11330)
@@ -0,0 +1,55 @@
+/*!\file: Inputs.h
+ * \brief prototypes for Inputs.h
+ */ 
+
+#ifndef _CONTAINER_INPUTS_H_
+#define  _CONTAINER_INPUTS_H_
+
+/*forward declarations */
+class Materials;
+class Parameters;
+class Elements;
+class Vertices;
+class Loads;
+class Nodes;
+class DataSet;
+class Input;
+class Node;
+class GaussTria;
+class GaussPenta;
+
+class Inputs: public DataSet{
+
+	public:
+
+		/*constructors, destructors: {{{1*/
+		Inputs();
+		~Inputs();
+
+		/*}}}*/
+		/*numerics: {{{1*/
+		int     AddInput(Input* in_input);
+		void    ChangeEnum(int enumtype,int new_enumtype);
+		void    ConstrainMin(int constrain_enum, double minimum);
+		int     DeleteInput(int enum_type);
+		void    DuplicateInput(int original_enum,int new_enum);
+		Input*  GetInput(int enum_name);
+		Inputs* SpawnTriaInputs(int* indices);
+		void    AXPY(int MeshYEnum, double scalar, int MeshXEnum);
+		double  InfinityNorm(int enumtype);
+		double  Max(int enumtype);
+		double  MaxAbs(int enumtype);
+		double  Min(int enumtype);
+		double  MinAbs(int enumtype);
+		
+		void GetInputAverage(double* pvalue, int enum_type);
+		void GetInputValue(bool* pvalue,int enum_type);
+		void GetInputValue(int* pvalue,int enum_type);
+		void GetInputValue(double* pvalue,int enum_type);
+
+		void Configure(Parameters* parameters);
+		/*}}}*/
+
+};
+
+#endif //ifndef _INPUTS_H_
Index: /issm/trunk-jpl-damage/src/c/Container/Loads.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Loads.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Loads.cpp	(revision 11330)
@@ -0,0 +1,89 @@
+/*
+ * \file Loads.c
+ * \brief: implementation of the Loads class, derived from DataSet class
+ */
+
+/*Headers: {{{1*/
+#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 "./DataSet.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Loads::Loads(){{{1*/
+Loads::Loads(){
+	enum_type=LoadsEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Loads::~Loads(){{{1*/
+Loads::~Loads(){
+	return;
+}
+/*}}}*/
+
+/*Numerics:*/
+/*FUNCTION Loads::Configure{{{1*/
+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=(Load*)(*object);
+		load->Configure(elements,loads,nodes,vertices,materials,parameters);
+
+	}
+
+}
+/*}}}*/
+/*FUNCTION Loads::NumberOfLoads{{{1*/
+int Loads::NumberOfLoads(void){
+
+	int localloads=0;
+	int numberofloads=0;
+
+	/*Get number of local loads*/
+	localloads=this->Size();
+
+	/*figure out total number of loads combining all the cpus (no clones here)*/
+	#ifdef _PARALLEL_
+	MPI_Reduce(&localloads,&numberofloads,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&numberofloads,1,MPI_INT,0,MPI_COMM_WORLD);
+	#else
+	numberofloads=localloads;
+	#endif
+
+	return numberofloads;
+}
+/*}}}*/
+/*FUNCTION Loads::SetCurrentConfiguration{{{1*/
+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=(Load*)(*object);
+		load->SetCurrentConfiguration(elements,loads,nodes,vertices,materials,parameters);
+
+	}
+
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/Container/Loads.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Loads.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Loads.h	(revision 11330)
@@ -0,0 +1,34 @@
+/*!\file: Loads.h
+ * \brief prototypes for Loads.h
+ */ 
+
+#ifndef _CONTAINER_LOADS_H_
+#define  _CONTAINER_LOADS_H_
+
+/*forward declarations */
+class Materials;
+class Parameters;
+class Elements;
+class Vertices;
+class Loads;
+class Nodes;
+class DataSet;
+class Inputs;
+
+class Loads: public DataSet{
+
+	public:
+
+		/*constructors, destructors: {{{1*/
+		Loads();
+		~Loads();
+		/*}}}*/
+		/*numerics: {{{1*/
+		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		int   NumberOfLoads(void);
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		/*}}}*/
+
+};
+
+#endif //ifndef _LOADS_H_
Index: /issm/trunk-jpl-damage/src/c/Container/Materials.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Materials.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Materials.cpp	(revision 11330)
@@ -0,0 +1,54 @@
+/*
+ * \file Materials.c
+ * \brief: implementation of the Materials class, derived from DataSet class
+ */
+
+/*Headers: {{{1*/
+#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 "./DataSet.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Materials::Materials(){{{1*/
+Materials::Materials(){
+	enum_type=MaterialsEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Materials::~Materials(){{{1*/
+Materials::~Materials(){
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+/*FUNCTION Materials::Configure{{{1*/
+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=(Material*)(*object);
+		material->Configure(elements);
+
+	}
+
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/Container/Materials.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Materials.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Materials.h	(revision 11330)
@@ -0,0 +1,31 @@
+/*!\file: Materials.h
+ * \brief prototypes for Materials.h
+ */ 
+
+#ifndef _CONTAINER_MATERIALS_H_
+#define  _CONTAINER_MATERIALS_H_
+
+/*forward declarations */
+class Parameters;
+class Elements;
+class Vertices;
+class Loads;
+class Nodes;
+class DataSet;
+class Inputs;
+
+class Materials: public DataSet{
+
+	public:
+
+		/*constructors, destructors: {{{1*/
+		Materials();
+		~Materials();
+		/*}}}*/
+		/*numerics: {{{1*/
+		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		/*}}}*/
+
+};
+
+#endif //ifndef _MATERIALS_H_
Index: /issm/trunk-jpl-damage/src/c/Container/Nodes.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Nodes.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Nodes.cpp	(revision 11330)
@@ -0,0 +1,348 @@
+/*
+ * \file Nodes.c
+ * \brief: implementation of the Nodes class, derived from DataSet class
+ */
+
+/*Headers: {{{1*/
+#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 "./DataSet.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Nodes::Nodes(){{{1*/
+Nodes::Nodes(){
+	enum_type=NodesEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Nodes::~Nodes(){{{1*/
+Nodes::~Nodes(){
+	return;
+}
+/*}}}*/
+
+/*Numerics*/
+/*FUNCTION Nodes::Configure{{{1*/
+void Nodes::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
+
+	vector<Object*>::iterator object;
+	Node* node=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		node=(Node*)(*object);
+		node->Configure(nodes,vertices);
+
+	}
+
+}
+/*}}}*/
+/*FUNCTION Nodes::DistributeDofs{{{1*/
+void  Nodes::DistributeDofs(int analysis_type,int setenum){
+
+	extern int num_procs;
+	extern int my_rank;
+
+	int  i;
+	int  dofcount=0;
+	int  maxdofspernode=0;
+	int* alldofcount=NULL;
+	int* truedofs=NULL;
+	int* alltruedofs=NULL;
+	int  numnodes=0;
+
+	/*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=(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: bet number of dofs for each cpu*/
+	alldofcount=(int*)xmalloc(num_procs*sizeof(int));
+	MPI_Gather(&dofcount,1,MPI_INT,alldofcount,1,MPI_INT,0,MPI_COMM_WORLD);
+	MPI_Bcast(alldofcount,num_procs,MPI_INT,0,MPI_COMM_WORLD);
+
+	/* Every cpu should start its own dof count at the end of the dofcount from cpu-1*/
+	dofcount=0;
+	if(my_rank!=0){
+		for(i=0;i<my_rank;i++){
+			dofcount+=alldofcount[i];
+		}
+	}
+	for (i=0;i<this->Size();i++){
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		Node* node=(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=   (int*)xcalloc(numnodes*maxdofspernode,sizeof(int)); //initialize to 0, so that we can pick up the max
+		alltruedofs=(int*)xcalloc(numnodes*maxdofspernode,sizeof(int));
+	}
+
+	for (i=0;i<this->Size();i++){
+		Node* node=(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
+		}
+	}
+	MPI_Allreduce ( (void*)truedofs,(void*)alltruedofs,numnodes*maxdofspernode,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
+
+	/* Now every cpu knows the true dofs of everyone else that is not a clone*/
+	for (i=0;i<this->Size();i++){
+		Node* node=(Node*)this->GetObjectByOffset(i);
+		if (node->InAnalysis(analysis_type)){
+			node->UpdateCloneDofs(alltruedofs,maxdofspernode,setenum);
+		}
+	}
+
+	/* Free ressources: */
+	xfree((void**)&alldofcount);
+	xfree((void**)&truedofs);
+	xfree((void**)&alltruedofs);
+}
+/*}}}*/
+/*FUNCTION Nodes::FlagClones{{{1*/
+void  Nodes::FlagClones(int analysis_type){
+
+	int i;
+	extern int num_procs;
+
+	int* ranks=NULL;
+	int* minranks=NULL;
+	int  numnodes;
+
+
+	/*Figure out number of nodes for this analysis: */
+	numnodes=this->NumberOfNodes(analysis_type);
+
+	/*Allocate ranks: */
+	ranks=(int*)xmalloc(numnodes*sizeof(int));
+	minranks=(int*)xmalloc(numnodes*sizeof(int));
+
+	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.*/
+	MPI_Allreduce ( (void*)ranks,(void*)minranks,numnodes,MPI_INT,MPI_MIN,MPI_COMM_WORLD);
+
+	/*Now go through all objects, and use minranks to flag which objects are cloned: */
+	for(i=0;i<this->Size();i++){
+
+		Node* node=(Node*)this->GetObjectByOffset(i);
+
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		if (node->InAnalysis(analysis_type)){
+
+			/*For this object, decide whether it is a clone: */
+			node->SetClone(minranks);
+		}
+	}
+
+	/*Free ressources: */
+	xfree((void**)&ranks); 
+	xfree((void**)&minranks);
+
+}
+/*}}}*/
+/*FUNCTION Nodes::MaxNumDofs{{{1*/
+int   Nodes::MaxNumDofs(int analysis_type,int setenum){
+
+	int i;
+	int   max=0;
+	int   allmax;
+	int   numdofs=0;
+
+	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
+	for(i=0;i<this->Size();i++){
+
+		Node* node=(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;
+		}
+	}
+
+#ifdef _PARALLEL_
+	/*Grab max of all cpus: */
+	MPI_Allreduce ( (void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
+	max=allmax;
+#endif
+
+	return max;
+}
+/*}}}*/
+/*FUNCTION Nodes::NumberOfDofs{{{1*/
+int   Nodes::NumberOfDofs(int analysis_type,int setenum){
+
+	int i;
+	
+	int   numdofs=0;
+	int   allnumdofs;
+
+	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
+	for(i=0;i<this->Size();i++){
+
+		Node* node=(Node*)this->GetObjectByOffset(i);
+
+		/*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);
+
+			}
+		}
+	}
+
+	/*Gather from all cpus: */
+	MPI_Allreduce ( (void*)&numdofs,(void*)&allnumdofs,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
+	return allnumdofs;
+}
+/*}}}*/
+/*FUNCTION Nodes::NumberOfNodes(){{{1*/
+int Nodes::NumberOfNodes(void){
+
+	/*Careful! only use once all clones have been setup for all nodes!: */
+
+	int i;
+	
+	int   numnodes=0;
+	int   allnumnodes=0;
+
+	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
+	for(i=0;i<this->Size();i++){
+		Node* node=(Node*)this->GetObjectByOffset(i);
+
+		/*Ok, this object is a node, ask it to plug values into partition: */
+		if (!node->IsClone()) numnodes++;
+	}
+
+	/*Gather from all cpus: */
+	MPI_Allreduce ( (void*)&numnodes,(void*)&allnumnodes,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
+
+	return allnumnodes;
+}
+/*}}}*/
+/*FUNCTION Nodes::NumberOfNodes(analysis){{{1*/
+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=(Node*)this->GetObjectByOffset(i);
+
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		if (node->InAnalysis(analysis_type)){
+
+			sid=node->Sid();
+			if (sid>max_sid)max_sid=sid;
+		}
+	}
+
+	#ifdef _PARALLEL_
+		MPI_Reduce (&max_sid,&node_max_sid,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
+		MPI_Bcast(&node_max_sid,1,MPI_INT,0,MPI_COMM_WORLD);
+		max_sid=node_max_sid;
+	#endif 
+
+	if(max_sid==1){
+		return 0;
+	}
+	else{
+		/*sid starts at 0*/
+		max_sid++;
+	
+		/*return*/
+		return max_sid;
+	}
+}
+/*}}}*/
+/*FUNCTION Nodes::Ranks{{{1*/
+void   Nodes::Ranks(int* ranks,int analysis_type){
+
+	/*Go through nodes, and for each object, report it cpu: */
+
+	int i;
+	int rank;
+	int sid;
+	
+	for(i=0;i<this->Size();i++){
+
+		Node* node=(Node*)this->GetObjectByOffset(i);
+
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		if (node->InAnalysis(analysis_type)){
+
+			rank=node->MyRank();
+			sid=node->Sid();
+
+			/*Plug rank into ranks, according to id: */
+			ranks[sid]=rank; 
+		}
+	}
+	return;
+}
+/*}}}*/
+/*FUNCTION Nodes::SetCurrentConfiguration{{{1*/
+void Nodes::SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
+
+	vector<Object*>::iterator object;
+	Node* node=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		node=(Node*)(*object);
+		node->SetCurrentConfiguration(nodes,vertices);
+
+	}
+
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/Container/Nodes.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Nodes.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Nodes.h	(revision 11330)
@@ -0,0 +1,33 @@
+/*!\file: Nodes.h
+ * \brief prototypes for Nodes.h
+ */ 
+
+#ifndef _CONTAINER_NODES_H_
+#define  _CONTAINER_NODES_H_
+
+#include "./DataSet.h"
+
+/*forward declarations */
+class Nodes: public DataSet{
+
+	public:
+
+		/*constructors, destructors: {{{1*/
+		Nodes();
+		~Nodes();
+		/*}}}*/
+		/*numerics: {{{1*/
+		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		void  DistributeDofs(int analysis_type,int SETENUM);
+		void  FlagClones(int analysis_type);
+		int   MaxNumDofs(int analysis_type,int setenum);
+		int   NumberOfDofs(int analysis_type,int setenum);
+		int   NumberOfNodes(int analysis_type);
+		int   NumberOfNodes(void);
+		void  Ranks(int* ranks,int analysis_type);
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		/*}}}*/
+
+};
+
+#endif //ifndef _NODES_H_
Index: /issm/trunk-jpl-damage/src/c/Container/Options.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Options.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Options.cpp	(revision 11330)
@@ -0,0 +1,324 @@
+/*
+ * \file Options.c
+ * \brief: implementation of the Options class, derived from DataSet class
+ */
+
+/*Headers: {{{1*/
+#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 "./DataSet.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../include/include.h"
+#include "../shared/shared.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#ifdef _SERIAL_
+#include "../io/io.h"
+#endif
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Options::Options(){{{1*/
+Options::Options(){
+	return;
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION Options::Options(int istart, int nrhs, const mxArray* prhs[]){{{1*/
+Options::Options(int istart, int nrhs, const mxArray* prhs[]){
+
+	int            i;
+	char          *name    = NULL;
+	Option *option = NULL;
+
+	/*loop over each name and value*/
+	for (i=istart; i<nrhs; i=i+2){
+		if (!mxIsClass(prhs[i],"char")) _error_("Argument %d must be name of option.",i+1);
+
+		FetchMatlabData(&name,prhs[i]);
+		if (i+1 == nrhs) _error_("Argument %d must exist and be value of option \"%s\".",i+2,name);
+
+		//_printf_(true,"  Processing option \"%s\" of class \"%s\".\n",name,mxGetClassName(prhs[i+1]));
+		option=(Option*)OptionParse(name,&prhs[i+1]);
+		this->AddOption(option);
+		option=NULL;
+	}
+
+	/*echo the dataset  */
+	//if (this->Size()) for(i=0;i<this->Size();i++) ((Option*)this->GetObjectByOffset(i))->Echo();
+}
+/*}}}*/
+#endif
+/*FUNCTION Options::~Options(){{{1*/
+Options::~Options(){
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+/*FUNCTION Options::AddOption{{{1*/
+int  Options::AddOption(Option* in_option){
+
+	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*/
+	if(!in_option->name) _error_("input option has an empty name");
+	if(strchr(in_option->name,'.')) _error_("Option \"%s\" has a protected character \".\"",in_option->name);
+	if(strchr(in_option->name,'[')) _error_("Option \"%s\" has a protected character \"[\"",in_option->name);
+	if(strchr(in_option->name,']')) _error_("Option \"%s\" has a protected character \"]\"",in_option->name);
+
+	/*Finally, check that no option of the same name already exists in the dataset*/
+	for(object=objects.begin();object<objects.end();object++){
+
+		option=(Option*)(*object); 
+		if (!strcmp(option->name,in_option->name)){
+			_error_("Options \"%s\" found multiple times",in_option->name);
+			break;
+		}
+	}
+
+	/*OK, all checks went well, add option to dataset*/
+	this->AddObject(in_option);
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION Options::Get(double* pvalue, char* name){{{1*/
+void Options::Get(double* pvalue,const char* name){
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+
+	/*Get option*/
+	option=GetOption(name);
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(option){
+		option->Get(pvalue);
+	}
+	/*Else, the Option does not exist, no default provided*/
+	else{
+		_error_("option of name \"%s\" not found, and no default value has been provided",name);
+	}
+}
+/*}}}*/
+/*FUNCTION Options::Get(double* pvalue, char* name,double default_value){{{1*/
+void Options::Get(double* pvalue,const char* name,double default_value){
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+
+	/*Get option*/
+	option=GetOption(name);
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(option){
+		option->Get(pvalue);
+	}
+	/*Else, the Option does not exist, a default is provided here*/
+	else{
+		*pvalue=default_value;
+	}
+}
+/*}}}*/
+/*FUNCTION Options::Get(bool* pvalue, char* name){{{1*/
+void Options::Get(bool* pvalue,const char* name){
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+
+	/*Get option*/
+	option=GetOption(name);
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(option){
+		option->Get(pvalue);
+	}
+	/*Else, the Option does not exist, no default provided*/
+	else{
+		_error_("option of name \"%s\" not found, and no default value has been provided",name);
+	}
+}
+/*}}}*/
+/*FUNCTION Options::Get(bool* pvalue, char* name,bool default_value){{{1*/
+void Options::Get(bool* pvalue,const char* name,bool default_value){
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+
+	/*Get option*/
+	option=GetOption(name);
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(option){
+		option->Get(pvalue);
+	}
+	/*Else, the Option does not exist, a default is provided here*/
+	else{
+		*pvalue=default_value;
+	}
+}
+/*}}}*/
+/*FUNCTION Options::Get(char** pvalue, char* name){{{1*/
+void Options::Get(char** pvalue,const char* name){
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+	char* outstring=NULL;
+	int   stringsize;
+
+	/*Get option*/
+	option=GetOption(name);
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(option){
+		option->Get(pvalue);
+	}
+	/*Else, the Option does not exist, no default provided*/
+	else{
+		_error_("option of name \"%s\" not found, and no default value has been provided",name);
+	}
+
+}
+/*}}}*/
+/*FUNCTION Options::Get(char** pvalue, char* name,char* default_value){{{1*/
+void Options::Get(char** pvalue,const char* name,const char* default_value){
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+	char* outstring=NULL;
+	int   stringsize;
+
+	/*Get option*/
+	option=GetOption(name);
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(option){
+		option->Get(pvalue);
+	}
+	/*Else, the Option does not exist, a default is provided here*/
+	else{
+		stringsize=strlen(default_value)+1;
+		outstring=(char*)xmalloc(stringsize*sizeof(char));
+		memcpy(outstring,default_value,stringsize*sizeof(char));
+		*pvalue=outstring;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Options::Get(char*** ppvalue,int* numel,char* name){{{1*/
+void Options::Get(char*** ppvalue,int* numel,const char* name){
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+	Option* option2=NULL;
+	Options* options=NULL;
+	int   i;
+
+	/*Get option*/
+	option=GetOption(name);
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(option){
+		/*If the object is a Cell, copy the strings from its options dataset*/ 
+		if(option->ObjectEnum()==OptionCellEnum){
+			if (option->NumEl()) {
+				*ppvalue=(char **) xmalloc(option->NumEl()*sizeof(char *));
+				if (numel) *numel=option->NumEl();
+				option->Get(&options);
+				for (i=0; i<option->NumEl(); i++) {
+					option2=((Option *)options->GetObjectByOffset(i));
+					if(option2->ObjectEnum()==OptionCharEnum)
+						option2->Get(&((*ppvalue)[i]));
+					else
+						((*ppvalue)[i])=NULL;
+				}
+			}
+		}
+		/*If the object is a Char, copy the strings from its concatenation*/ 
+		else if(option->ObjectEnum()==OptionCharEnum){
+			option->Get(ppvalue,numel);
+		}
+		/*Else: not supported*/
+		else{
+			_error_("Cannot recover field \"%s\" for an option of type %s",name,EnumToStringx(option->ObjectEnum()));
+		}
+	}
+	/*Else, the Option does not exist, no default provided*/
+	else{
+		*ppvalue=NULL;
+		if (numel) *numel=0;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Options::Get(double** pvalue,int* numel,const char* name){{{1*/
+void Options::Get(double** pvalue,int* numel,const char* name){
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+
+	/*Get option*/
+	option=GetOption(name);
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(option){
+		option->Get(pvalue,numel);
+	}
+	/*Else, the Option does not exist, no default provided*/
+	else{
+		_error_("option of name \"%s\" not found, and no default value has been provided",name);
+	}
+}
+/*}}}*/
+/*FUNCTION Options::GetOption{{{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=(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){
+					return ((OptionCell*)option)->values->GetOption(name);
+				}
+				/*If the object is a Struct loop over its size and recursive call*/
+				else if(option->ObjectEnum()==OptionStructEnum){
+					for(int i=0;i<option->numel;i++){
+						_assert_(((OptionStruct*)option)->values[i]);
+						return ((OptionStruct*)option)->values[i]->GetOption(name);
+					}
+				}
+				/*Else: not supported*/
+				else{
+					_error_("Cannot recover field \"%s\" for an option of type %s",name,EnumToStringx(option->ObjectEnum()));
+				}
+			}
+		}
+	}
+
+	/*Option not found return NULL pointer*/
+	return NULL;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/Container/Options.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Options.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Options.h	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file: Options.h
+ * \brief prototypes for Options.h
+ */ 
+
+#ifndef _CONTAINER_OPTIONS_H_
+#define _CONTAINER_OPTIONS_H_
+
+/*forward declarations */
+class Option;
+
+class Options: public DataSet{
+
+	public:
+
+		/*constructors, destructors*/
+		Options();
+		#ifdef _SERIAL_
+		Options(int istart, int nrhs, const mxArray* prhs[]);
+		#endif
+		~Options();
+
+		/*numerics*/
+		int  AddOption(Option* in_oobject);
+		Option* GetOption(const char* name);
+		void Get(double*  pvalue,const char* name);
+		void Get(double*  pvalue,const char* name,double default_value);
+		void Get(bool*    pvalue,const char* name);
+		void Get(bool*    pvalue,const char* name,bool default_value);
+		void Get(char**   pvalue,const char* name);
+		void Get(char**   pvalue,const char* name,const char* default_value);
+		void Get(char***  pvalue,int* numel,const char* name);
+		void Get(double** pvalue,int* numel,const char* name);
+};
+
+#endif //ifndef _INPUTS_H_
Index: /issm/trunk-jpl-damage/src/c/Container/Parameters.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Parameters.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Parameters.cpp	(revision 11330)
@@ -0,0 +1,456 @@
+/*
+ * \file Parameters.c
+ * \brief: implementation of the Parameters class, derived from DataSet class
+ */
+
+/*Headers: {{{1*/
+#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 "./DataSet.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Parameters::Parameters(){{{1*/
+Parameters::Parameters(){
+	enum_type=ParametersEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Parameters::~Parameters(){{{1*/
+Parameters::~Parameters(){
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+/*FUNCTION Parameters::Exist{{{1*/
+bool Parameters::Exist(int enum_type){
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+		param=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type) return true;
+	}
+	return false;
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(bool* pbool,int enum_type){{{1*/
+void Parameters::FindParam(bool* pbool,int enum_type){ _assert_(this);
+	
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pbool);
+			return;
+		}
+	}
+	_error_("could not find parameter %s",EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(int* pinteger,int enum_type){{{1*/
+void Parameters::FindParam(int* pinteger,int enum_type){ _assert_(this);
+	
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pinteger);
+			return;
+		}
+	}
+	_error_("could not find parameter %s",EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(double* pscalar, int enum_type){{{1*/
+void Parameters::FindParam(double* pscalar, int enum_type){ _assert_(this);
+	
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pscalar);
+			return;
+		}
+	}
+	_error_("could not find parameter %s",EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(char** pstring,int enum_type){{{1*/
+void Parameters::FindParam(char** pstring,int enum_type){ _assert_(this);
+	
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pstring);
+			return;
+		}
+	}
+	_error_("could not find parameter %s",EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(char*** pstringarray,int* pM,int enum_type){{{1*/
+void Parameters::FindParam(char*** pstringarray,int* pM,int enum_type){ _assert_(this);
+	
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pstringarray,pM);
+			return;
+		}
+	}
+	_error_("could not find parameter %s",EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(int** pintarray,int* pM,int enum_type){{{1*/
+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=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pintarray,pM);
+			return;
+		}
+	}
+	_error_("could not find parameter %s",EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(int** pintarray,int* pM,int* pN,int enum_type){{{1*/
+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=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pintarray,pM,pN);
+			return;
+		}
+	}
+	_error_("could not find parameter %s",EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(double** pdoublearray,int* pM,int enum_type){{{1*/
+void Parameters::FindParam(double** pdoublearray,int* pM, int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pdoublearray,pM);
+			return;
+		}
+	}
+	_error_("could not find parameter %s",EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(double** pdoublearray,int* pM, int* pN,int enum_type){{{1*/
+void Parameters::FindParam(double** pdoublearray,int* pM, int* pN,int enum_type){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pdoublearray,pM,pN);
+			return;
+		}
+	}
+	_error_("could not find parameter %s",EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(double*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){{{1*/
+void Parameters::FindParam(double*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){ _assert_(this);
+	
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(parray,pM,pmdims_array,pndims_array);
+			return;
+		}
+	}
+	_error_("could not find parameter %s",EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(Vec* pvec,int enum_type){{{1*/
+void Parameters::FindParam(Vec* pvec,int enum_type){ _assert_(this);
+	
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pvec);
+			return;
+		}
+	}
+	_error_("could not find parameter %s",EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(Mat* pmat,int enum_type){{{1*/
+void Parameters::FindParam(Mat* pmat,int enum_type){ _assert_(this);
+	
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pmat);
+			return;
+		}
+	}
+	_error_("could not find parameter %s",EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(FILE** pfid,int enum_type){{{1*/
+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=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pfid);
+			return;
+		}
+	}
+	_error_("could not find parameter %s",EnumToStringx(enum_type));
+}
+/*}}}*/
+
+/*FUNCTION Parameters::SetParam(bool boolean,int enum_type);{{{1*/
+void   Parameters::SetParam(bool boolean,int enum_type){
+
+	Param* param=NULL;
+	
+	/*first, figure out if the param has already been created: */
+	param=(Param*)this->FindParamObject(enum_type);
+
+	if(param) param->SetValue(boolean); //already exists, just set it.
+	else this->AddObject(new BoolParam(enum_type,boolean)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(int integer,int enum_type);{{{1*/
+void   Parameters::SetParam(int integer,int enum_type){
+
+	Param* param=NULL;
+	
+	/*first, figure out if the param has already been created: */
+	param=(Param*)this->FindParamObject(enum_type);
+
+	if(param) param->SetValue(integer); //already exists, just set it.
+	else this->AddObject(new IntParam(enum_type,integer)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(double scalar,int enum_type);{{{1*/
+void   Parameters::SetParam(double scalar,int enum_type){
+
+	Param* param=NULL;
+	
+	/*first, figure out if the param has already been created: */
+	param=(Param*)this->FindParamObject(enum_type);
+
+	if(param) param->SetValue(scalar); //already exists, just set it.
+	else this->AddObject(new DoubleParam(enum_type,scalar)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(char* string,int enum_type);{{{1*/
+void   Parameters::SetParam(char* string,int enum_type){
+
+	Param* param=NULL;
+	
+	/*first, figure out if the param has already been created: */
+	param=(Param*)this->FindParamObject(enum_type);
+
+	if(param) param->SetValue(string); //already exists, just set it.
+	else this->AddObject(new StringParam(enum_type,string)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(char** stringarray,int M, int enum_type);{{{1*/
+void   Parameters::SetParam(char** stringarray,int M, int enum_type){
+
+	Param* param=NULL;
+	
+	/*first, figure out if the param has already been created: */
+	param=(Param*)this->FindParamObject(enum_type);
+
+	if(param) param->SetValue(stringarray,M); //already exists, just set it.
+	else this->AddObject(new StringArrayParam(enum_type,stringarray,M)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(double* doublearray,int M,int enum_type);{{{1*/
+void   Parameters::SetParam(double* doublearray,int M, int enum_type){
+
+	Param* param=NULL;
+	
+	/*first, figure out if the param has already been created: */
+	param=(Param*)this->FindParamObject(enum_type);
+
+	if(param) param->SetValue(doublearray,M); //already exists, just set it.
+	else this->AddObject(new DoubleVecParam(enum_type,doublearray,M)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(double* doublearray,int M,int N, int enum_type);{{{1*/
+void   Parameters::SetParam(double* doublearray,int M, int N, int enum_type){
+
+	Param* param=NULL;
+	
+	/*first, figure out if the param has already been created: */
+	param=(Param*)this->FindParamObject(enum_type);
+
+	if(param) param->SetValue(doublearray,M,N); //already exists, just set it.
+	else this->AddObject(new DoubleMatParam(enum_type,doublearray,M,N)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(int* intarray,int M,int enum_type);{{{1*/
+void   Parameters::SetParam(int* intarray,int M, int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=(Param*)this->FindParamObject(enum_type);
+
+	if(param) param->SetValue(intarray,M); //already exists, just set it.
+	else this->AddObject(new IntVecParam(enum_type,intarray,M)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(int* intarray,int M,int N, int enum_type);{{{1*/
+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=(Param*)this->FindParamObject(enum_type);
+
+	if(param) param->SetValue(intarray,M,N); //already exists, just set it.
+	else this->AddObject(new IntMatParam(enum_type,intarray,M,N)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(Vec vector,int enum_type);{{{1*/
+void   Parameters::SetParam(Vec vector,int enum_type){
+
+	Param* param=NULL;
+	
+	/*first, figure out if the param has already been created: */
+	param=(Param*)this->FindParamObject(enum_type);
+
+	if(param) param->SetValue(vector); //already exists, just set it.
+	else this->AddObject(new PetscVecParam(enum_type,vector)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(Mat matrix,int enum_type);{{{1*/
+void   Parameters::SetParam(Mat matrix,int enum_type){
+
+	Param* param=NULL;
+	
+	/*first, figure out if the param has already been created: */
+	param=(Param*)this->FindParamObject(enum_type);
+
+	if(param) param->SetValue(matrix); //already exists, just set it.
+	else this->AddObject(new PetscMatParam(enum_type,matrix)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::SetParam(FILE* fid,int enum_type);{{{1*/
+void   Parameters::SetParam(FILE* fid,int enum_type){
+
+	Param* param=NULL;
+
+	/*first, figure out if the param has already been created: */
+	param=(Param*)this->FindParamObject(enum_type);
+
+	if(param) param->SetValue(fid); //already exists, just set it.
+	else this->AddObject(new FileParam(enum_type,fid)); //just add the new parameter.
+}
+/*}}}*/
+/*FUNCTION Parameters::UnitConversion(int direction_enum);{{{1*/
+void   Parameters::UnitConversion(int direction_enum){
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+		param=(Param*)(*object);
+		param->UnitConversion(direction_enum);
+	}
+
+}
+/*}}}*/
+
+/*FUNCTION Parameters::FindParamObject{{{1*/
+Object* Parameters::FindParamObject(int enum_type){
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			return (*object);
+		}
+	}
+	return NULL;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/Container/Parameters.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Parameters.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Parameters.h	(revision 11330)
@@ -0,0 +1,62 @@
+/*!\file: Parameters.h
+ * \brief prototypes for Parameters.h
+ */ 
+
+#ifndef _CONTAINER_PARAMETERS_H_
+#define  _CONTAINER_PARAMETERS_H_
+
+/*forward declarations */
+class Materials;
+class Parameters;
+class Elements;
+class Vertices;
+class Loads;
+class Nodes;
+class DataSet;
+class Inputs;
+
+class Parameters: public DataSet{
+
+	public:
+
+		/*constructors, destructors: {{{1*/
+		Parameters();
+		~Parameters();
+		/*}}}*/
+		/*numerics: {{{1*/
+		bool  Exist(int enum_type);
+
+		void  FindParam(bool* pinteger,int enum_type);
+		void  FindParam(int* pinteger,int enum_type);
+		void  FindParam(double* pscalar, int enum_type);
+		void  FindParam(char** pstring,int enum_type);
+		void  FindParam(char*** pstringarray,int* pM,int enum_type);
+		void  FindParam(int** pintarray,int* pM,int enum_type);
+		void  FindParam(int** pintarray,int* pM,int* PN,int enum_type);
+		void  FindParam(double** pdoublearray,int* pM,int enum_type);
+		void  FindParam(double** pdoublearray,int* pM,int* pN,int enum_type);
+		void  FindParam(double*** parray,int* pM, int** pmdims_array,int** pndims_array,int enum_type);
+		void  FindParam(Vec* pvec,int enum_type);
+		void  FindParam(Mat* pmat,int enum_type);
+		void  FindParam(FILE** pfid,int enum_type);
+		
+		void  SetParam(bool boolean,int enum_type);
+		void  SetParam(int integer,int enum_type);
+		void  SetParam(double scalar, int enum_type);
+		void  SetParam(char* string,int enum_type);
+		void  SetParam(char** stringarray,int M,int enum_type);
+		void  SetParam(double* doublearray,int M,int enum_type);
+		void  SetParam(double* doublearray,int M,int N,int enum_type);
+		void  SetParam(int* intarray,int M,int enum_type);
+		void  SetParam(int* intarray,int M,int N,int enum_type);
+		void  SetParam(Vec vec,int enum_type);
+		void  SetParam(Mat mat,int enum_type);
+		void  SetParam(FILE* fid,int enum_type);
+		void  UnitConversion(int direction_enum);
+
+		Object* FindParamObject(int enum_type);
+		/*}}}*/
+
+};
+
+#endif //ifndef _PARAMETERS_H_
Index: /issm/trunk-jpl-damage/src/c/Container/Results.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Results.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Results.cpp	(revision 11330)
@@ -0,0 +1,170 @@
+/*
+ * \file Results.c
+ * \brief: implementation of the Results class, derived from DataSet class
+ */
+
+/*Headers: {{{1*/
+#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 "./DataSet.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Results::Results(){{{1*/
+Results::Results(){
+	enum_type=ResultsEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Results::~Results(){{{1*/
+Results::~Results(){
+	return;
+}
+/*}}}*/
+
+/*Object management*/
+/*FUNCTION Results::SpawnTriaResults{{{1*/
+Results* Results::SpawnTriaResults(int* indices){
+
+	/*Intermediary*/
+	vector<Object*>::iterator object;
+	ElementResult* resultin=NULL;
+	ElementResult* resultout=NULL;
+
+	/*Output*/
+	Results* newresults=new Results();
+
+	/*Go through results and call Spawn function*/
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		/*Create new result*/
+		resultin=(ElementResult*)(*object); 
+		resultout=resultin->SpawnTriaElementResult(indices);
+
+		/*Add result to new results*/
+		newresults->AddObject((Object*)resultout);
+	}
+
+	/*Assign output pointer*/
+	return newresults;
+}
+/*}}}*/
+/*FUNCTION Results::Write{{{1*/
+#ifdef _SERIAL_
+void Results::Write(mxArray** pdataref){
+
+	int i,j;
+	int count;
+
+	/*output: */
+	mxArray* dataref=NULL;
+	mxArray* processeddataref=NULL;
+	mwSize nfields;
+	mwSize maxfields;
+	mwSize nsteps;
+	mwSize step;
+	const char **fnames      = NULL;
+	int         *enums       = NULL;
+	int          baseenum;
+	mwSize       onebyone[2] = {1,1};
+	mwSize       ndim        = 2;
+
+	/*How many time steps do we have? : */
+	nsteps=0;
+	for(i=0;i<this->Size();i++){
+		ExternalResult* result=(ExternalResult*)this->GetObjectByOffset(i);
+		step=result->GetStep();
+		if(step>nsteps)nsteps=step;
+	}
+	onebyone[0]=nsteps;
+
+	/*How many field names do we have. First, figure out how many result types we have: */
+	maxfields=(mwSize)this->Size();
+	enums=(int*)xmalloc(maxfields*sizeof(int));
+	for(i=0;i<maxfields;i++){
+		ExternalResult* result=(ExternalResult*)this->GetObjectByOffset(i);
+		enums[i]=result->InstanceEnum();
+	}
+	/*Now, make result types unique: */
+	for(i=0;i<maxfields;i++){
+		if(enums[i]>=0){//if <0, it means this enum was found to replicate another one previously
+			baseenum=enums[i]; 		
+			/*is the baseenum repeated later on?:*/
+			for(j=i+1;j<maxfields;j++){
+				if (enums[j]==baseenum)enums[j]=-1;
+			}
+		}
+		else continue;
+	}
+
+	/*Now, go through enums, and whatever is not null is a non repeated field name: */
+	nfields=0;
+	for(i=0;i<maxfields;i++)if(enums[i]>0)nfields++;
+
+	/*Add 2 fields for time and step: */
+	nfields=nfields+2;
+	
+	/*Fill the names of the structure field: */
+	fnames=(const char**)xmalloc(nfields*sizeof(char*));
+	count=0;
+	for(i=0;i<maxfields;i++){
+		if (enums[i]>0){
+			fnames[count]=EnumToStringx(enums[i]);
+			count++;
+		}
+	}
+	/*don't forget the extra fields "time" and "step":*/
+	fnames[nfields-2]="time";
+	fnames[nfields-1]="step";
+
+	/*Initialize structure: */
+	dataref=mxCreateStructArray( ndim,onebyone,nfields,fnames);
+
+	/*Fill each field: */
+	for(i=0;i<this->Size();i++){ //do not include the last one used for time
+		ExternalResult* result=(ExternalResult*)this->GetObjectByOffset(i);
+		result->SetMatlabField(dataref);
+	}
+
+	/*Now, process the patch in the dataref structure, by calling MatlabProcessPatch.m 
+	 *on the current dataref structure: */
+	mexCallMATLAB(1,&processeddataref,1,&dataref, "MatlabProcessPatch");
+
+	/*Assign output pointers:*/
+	*pdataref=processeddataref;
+}
+#else 
+void Results::Write(Parameters* parameters){
+	
+	int         i;
+	FILE       *fid          = NULL;
+	bool        io_gather=true;
+
+	/*Recover file descriptor: */
+	parameters->FindParam(&fid,OutputFilePointerEnum);
+	parameters->FindParam(&io_gather,SettingsIoGatherEnum);
+
+	for(i=0;i<this->Size();i++){
+		ExternalResult* result=(ExternalResult*)this->GetObjectByOffset(i);
+
+		/*write result to disk: */
+		result->WriteData(fid,io_gather);
+	}
+
+}
+#endif
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/Container/Results.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Results.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Results.h	(revision 11330)
@@ -0,0 +1,36 @@
+/*!\file: Results.h
+ * \brief prototypes for Results.h
+ */ 
+
+#ifndef _CONTAINER_RESULTS_H_
+#define  _CONTAINER_RESULTS_H_
+
+/*forward declarations */
+class Materials;
+class Parameters;
+class Elements;
+class Vertices;
+class Loads;
+class Nodes;
+class DataSet;
+class Inputs;
+
+class Results: public DataSet{
+
+	public:
+
+		/*constructors, destructors: {{{1*/
+		Results();
+		~Results();
+		/*}}}*/
+		/*numerics: {{{1*/
+		Results* SpawnTriaResults(int* indices);
+		#ifdef _SERIAL_
+		void Write(mxArray** pdataref);
+		#else 
+		void Write(Parameters* parameters);
+		#endif
+		/*}}}*/
+};
+#endif //ifndef _RESULTS_H_
+
Index: /issm/trunk-jpl-damage/src/c/Container/Vertices.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Vertices.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Vertices.cpp	(revision 11330)
@@ -0,0 +1,183 @@
+/*
+ * \file Vertices.c
+ * \brief: implementation of the Vertices class, derived from DataSet class
+ */
+
+/*Headers: {{{1*/
+#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 "./DataSet.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+using namespace std;
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION Vertices::Vertices(){{{1*/
+Vertices::Vertices(){
+	enum_type=VerticesEnum;
+	return;
+}
+/*}}}*/
+/*FUNCTION Vertices::~Vertices(){{{1*/
+Vertices::~Vertices(){
+	return;
+}
+/*}}}*/
+
+/*Numerics management*/
+/*FUNCTION Vertices::DistributeDofs{{{1*/
+void  Vertices::DistributeDofs(int numberofobjects,int numberofdofsperobject){
+
+	extern int num_procs;
+	extern int my_rank;
+
+	int  i;
+	int  dofcount=0;
+	int* alldofcount=NULL;
+	int* truedofs=NULL;
+	int* alltruedofs=NULL;
+
+	/*Go through objects, and distribute dofs locally, from 0 to numberofdofsperobject*/
+	for (i=0;i<this->Size();i++){
+		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
+		vertex->DistributeDofs(&dofcount);
+	}
+
+	/* Now every object has distributed dofs, but locally, and with a dof count starting from 
+	 * 0. This means the dofs between all the cpus are not unique. We now offset the dofs of eache
+	 * cpus by the total last dofs of the previus cpu, starting from 0.
+	 * First: bet number of dofs for each cpu*/
+	alldofcount=(int*)xmalloc(num_procs*sizeof(int));
+	MPI_Gather(&dofcount,1,MPI_INT,alldofcount,1,MPI_INT,0,MPI_COMM_WORLD);
+	MPI_Bcast(alldofcount,num_procs,MPI_INT,0,MPI_COMM_WORLD);
+
+	/* Every cpu should start its own dof count at the end of the dofcount from cpu-1*/
+	dofcount=0;
+	if(my_rank!=0){
+		for(i=0;i<my_rank;i++){
+			dofcount+=alldofcount[i];
+		}
+	}
+	for (i=0;i<this->Size();i++){
+		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
+		vertex->OffsetDofs(dofcount);
+	}
+
+	/* 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: */
+	truedofs   =(int*)xcalloc(numberofobjects*numberofdofsperobject,sizeof(int));
+	alltruedofs=(int*)xcalloc(numberofobjects*numberofdofsperobject,sizeof(int));
+	for (i=0;i<this->Size();i++){
+		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
+		vertex->ShowTrueDofs(truedofs);
+	}
+	MPI_Allreduce((void*)truedofs,(void*)alltruedofs,numberofobjects*numberofdofsperobject,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
+
+	/* Now every cpu knows the true dofs of everyone else that is not a clone*/
+	for (i=0;i<this->Size();i++){
+		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
+		vertex->UpdateCloneDofs(alltruedofs);
+	}
+
+	/* Free ressources: */
+	xfree((void**)&alldofcount);
+	xfree((void**)&truedofs);
+	xfree((void**)&alltruedofs);
+}
+/*}}}*/
+/*FUNCTION Vertices::FlagClones{{{1*/
+void  Vertices::FlagClones(int numberofobjects){
+
+	int i;
+	extern int num_procs;
+
+	int* ranks=NULL;
+	int* minranks=NULL;
+
+	/*Allocate ranks: */
+	ranks=(int*)xmalloc(numberofobjects*sizeof(int));
+	minranks=(int*)xmalloc(numberofobjects*sizeof(int));
+
+	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.*/
+	MPI_Allreduce ( (void*)ranks,(void*)minranks,numberofobjects,MPI_INT,MPI_MIN,MPI_COMM_WORLD);
+
+	/*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=(Vertex*)this->GetObjectByOffset(i);
+		vertex->SetClone(minranks);
+	}
+
+	/*Free ressources: */
+	xfree((void**)&ranks); 
+	xfree((void**)&minranks);
+
+}
+/*}}}*/
+/*FUNCTION Vertices::NumberOfVertices{{{1*/
+int Vertices::NumberOfVertices(void){
+
+	int i,sid;
+	int max_sid=0;
+	int vertex_max_sid;
+
+	for(i=0;i<this->Size();i++){
+		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
+		sid=vertex->Sid();
+		if (sid>max_sid)max_sid=sid;
+	}
+
+	#ifdef _PARALLEL_
+	MPI_Reduce (&max_sid,&vertex_max_sid,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
+	MPI_Bcast(&vertex_max_sid,1,MPI_INT,0,MPI_COMM_WORLD);
+	max_sid=vertex_max_sid;
+	#endif
+
+	/*sid starts at 0*/
+	max_sid++;
+
+	/*return:*/
+	return max_sid;
+}
+/*}}}*/
+/*FUNCTION Vertices::Ranks{{{1*/
+void   Vertices::Ranks(int* ranks){
+
+	/*Go through a dataset, and for each object, report it cpu: */
+
+	int i;
+	int rank;
+	int sid;
+	
+	for(i=0;i<this->Size();i++){
+		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
+		rank=vertex->MyRank();
+		sid=vertex->Sid();
+		
+		/*Plug rank into ranks, according to id: */
+		ranks[sid]=rank; 
+	}
+	return;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/Container/Vertices.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/Container/Vertices.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Container/Vertices.h	(revision 11330)
@@ -0,0 +1,37 @@
+/*!\file: Vertices.h
+ * \brief prototypes for Vertices.h
+ */ 
+
+#ifndef _CONTAINER_VERTICES_H_
+#define  _CONTAINER_VERTICES_H_
+
+/*forward declarations */
+class Materials;
+class Elements;
+class Vertices;
+class Loads;
+class Nodes;
+class DataSet;
+class Inputs;
+
+class Vertices: public DataSet{
+
+	public:
+
+		/*constructors, destructors: {{{1*/
+		Vertices();
+		~Vertices();
+		/*}}}*/
+		/*numerics: {{{1*/
+		void  DistributeDofs(int numberofnodes,int numdofspernode);
+		void  FlagClones(int numberofnodes);
+		int   NumberOfVertices(void);
+		void  Ranks(int* ranks);
+		/*}}}*/
+
+};
+
+
+
+#endif //ifndef _VERTICES_H_
+
Index: /issm/trunk-jpl-damage/src/c/EnumDefinitions/.deps/EnumDefinitions.Po
===================================================================
--- /issm/trunk-jpl-damage/src/c/EnumDefinitions/.deps/EnumDefinitions.Po	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/EnumDefinitions/.deps/EnumDefinitions.Po	(revision 11330)
@@ -0,0 +1,3 @@
+EnumDefinitions.o EnumDefinitions.o: EnumDefinitions.c EnumDefinitions.h
+
+EnumDefinitions.h:
Index: /issm/trunk-jpl-damage/src/c/EnumDefinitions/EnumDefinitions.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/EnumDefinitions/EnumDefinitions.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/EnumDefinitions/EnumDefinitions.h	(revision 11330)
@@ -0,0 +1,483 @@
+/*
+ * \file EnumDefinitions.h:
+ * \brief: enum functions for our objects
+ */
+
+#ifndef _ENUM_DEFINITIONS_
+#define _ENUM_DEFINITIONS_
+
+#include "../modules/EnumToStringx/EnumToStringx.h"
+#include "../modules/StringToEnumx/StringToEnumx.h"
+
+enum definitions{
+	/*Model fields {{{1*/
+	AutodiffForwardEnum,
+	AutodiffIsautodiffEnum, 
+	AutodiffReverseEnum,
+	BalancethicknessSpcthicknessEnum,
+	BalancethicknessStabilizationEnum,
+	BalancethicknessThickeningRateEnum,
+	BasalforcingsGeothermalfluxEnum,
+	BasalforcingsMeltingRateCorrectionEnum,
+	BasalforcingsMeltingRateEnum,
+	BathymetryEnum,
+	BedEnum,
+	ConstantsGEnum,
+	ConstantsReferencetemperatureEnum,
+	ConstantsYtsEnum,
+	DiagnosticAbstolEnum,
+	DiagnosticIcefrontEnum,
+	DiagnosticMaxiterEnum,
+	DiagnosticNumRequestedOutputsEnum,
+	DiagnosticPenaltyFactorEnum,
+	DiagnosticReferentialEnum,
+	DiagnosticReltolEnum,
+	DiagnosticRequestedOutputsEnum,
+	DiagnosticRestolEnum,
+	DiagnosticRiftPenaltyLockEnum,
+	DiagnosticRiftPenaltyThresholdEnum,
+	DiagnosticShelfDampeningEnum,
+	DiagnosticSpcvxEnum,
+	DiagnosticSpcvyEnum,
+	DiagnosticSpcvzEnum,
+	DiagnosticStokesreconditioningEnum,
+	DiagnosticVertexPairingEnum,
+	DiagnosticViscosityOvershootEnum,
+	FlowequationBordermacayealEnum,
+	FlowequationBorderpattynEnum,
+	FlowequationBorderstokesEnum,
+	FlowequationElementEquationEnum,
+	FlowequationIshutterEnum,
+	FlowequationIsmacayealpattynEnum,
+	FlowequationIsstokesEnum,
+	FlowequationVertexEquationEnum,
+	FrictionCoefficientEnum,
+	FrictionPEnum,
+	FrictionQEnum,
+	GeometryHydrostaticRatioEnum,
+	HydrologyCREnum,
+	HydrologyKnEnum,
+	HydrologyNEnum,
+	HydrologyPEnum,
+	HydrologyQEnum,
+	HydrologySpcwatercolumnEnum,
+	HydrologyStabilizationEnum,
+	InversionControlParametersEnum,
+	InversionCostFunctionEnum,
+	InversionCostFunctionThresholdEnum,
+	InversionCostFunctionsCoefficientsEnum,
+	InversionCostFunctionsEnum,
+	InversionGradientOnlyEnum,
+	InversionGradientScalingEnum,
+	InversionIscontrolEnum,
+	InversionTaoEnum,
+	InversionMaxParametersEnum,
+	InversionMaxiterPerStepEnum,
+	InversionMinParametersEnum,
+	InversionNstepsEnum,
+	InversionNumControlParametersEnum,
+	InversionNumCostFunctionsEnum,
+	InversionStepThresholdEnum,
+	InversionThicknessObsEnum,
+	InversionVelObsEnum,
+	InversionVxObsEnum,
+	InversionVyObsEnum,
+	InversionVzObsEnum,
+	MaskElementonfloatingiceEnum,
+	MaskElementongroundediceEnum,
+	MaskElementonwaterEnum,
+	MaskVertexonfloatingiceEnum,
+	MaskVertexongroundediceEnum,
+	MaskVertexonwaterEnum,
+	MaterialsBetaEnum,
+	MaterialsHeatcapacityEnum,
+	MaterialsLatentheatEnum,
+	MaterialsMeltingpointEnum,
+	MaterialsMixedLayerCapacityEnum,
+	MaterialsRheologyBEnum,
+	MaterialsRheologyBbarEnum,
+	MaterialsRheologyLawEnum,
+	MaterialsRheologyNEnum,
+	MaterialsRhoIceEnum,
+	MaterialsRhoWaterEnum,
+	MaterialsMuWaterEnum,
+	MaterialsThermalExchangeVelocityEnum,
+	MaterialsThermalconductivityEnum,
+	MeshAverageVertexConnectivityEnum,
+	MeshDimensionEnum,
+	MeshEdgesEnum,
+	MeshElementconnectivityEnum,
+	MeshElementonbedEnum,
+	MeshElementonsurfaceEnum,
+	MeshElements2dEnum,
+	MeshElementsEnum,
+	MeshLowerelementsEnum,
+	MeshNumberofedgesEnum,
+	MeshNumberofelements2dEnum,
+	MeshNumberofelementsEnum,
+	MeshNumberoflayersEnum,
+	MeshNumberofvertices2dEnum,
+	MeshNumberofverticesEnum,
+	MeshUpperelementsEnum,
+	MeshVertexonbedEnum,
+	MeshVertexonsurfaceEnum,
+	MeshXEnum,
+	MeshYEnum,
+	MeshZEnum,
+	MiscellaneousNameEnum, //FIXME: only used by qmu, should not be marshalled (already in queueing script)
+	PrognosticHydrostaticAdjustmentEnum,
+	PrognosticMinThicknessEnum,
+	PrognosticPenaltyFactorEnum,
+	PrognosticSpcthicknessEnum,
+	PrognosticStabilizationEnum,
+	PrognosticVertexPairingEnum,
+	QmuIsdakotaEnum,
+	QmuMassFluxSegmentsEnum,
+	QmuNumberofpartitionsEnum,
+	QmuNumberofresponsesEnum,
+	QmuPartitionEnum,
+	QmuResponsedescriptorsEnum,
+	QmuVariabledescriptorsEnum,
+	RiftsNumriftsEnum,
+	RiftsRiftstructEnum,
+	SettingsIoGatherEnum,
+	SettingsLowmemEnum,
+	SettingsOutputFrequencyEnum,
+	SettingsResultsAsPatchesEnum,
+	SettingsWaitonlockEnum,
+	SteadystateMaxiterEnum,
+	SteadystateNumRequestedOutputsEnum,
+	SteadystateReltolEnum,
+	SteadystateRequestedOutputsEnum,
+	SurfaceEnum,
+	SurfaceforcingsAblationRateEnum,
+	SurfaceforcingsAccumulationRateEnum,
+	SurfaceforcingsMassBalanceEnum,
+	ThermalMaxiterEnum,
+	ThermalPenaltyFactorEnum,
+	ThermalPenaltyLockEnum,
+	ThermalPenaltyThresholdEnum,
+	ThermalSpctemperatureEnum,
+	ThermalStabilizationEnum,
+	ThicknessEnum,
+	TimesteppingCflCoefficientEnum,
+	TimesteppingFinalTimeEnum,
+	TimesteppingTimeAdaptEnum,
+	TimesteppingTimeStepEnum,
+	TransientIsdiagnosticEnum,
+	TransientIsgroundinglineEnum,
+	TransientIsprognosticEnum,
+	TransientIsthermalEnum,
+	TransientNumRequestedOutputsEnum,
+	TransientRequestedOutputsEnum,
+	/*}}}*/
+	/*Solutions and Analyses{{{1 */
+	SolutionTypeEnum,
+	AnalysisTypeEnum,
+	ConfigurationTypeEnum,
+	AdjointBalancethicknessAnalysisEnum,
+	AdjointHorizAnalysisEnum,
+	AdjointSolutionEnum,
+	AnalysisCounterEnum,
+	BalancethicknessAnalysisEnum,
+	BalancethicknessSolutionEnum,
+	BedSlopeAnalysisEnum,
+	BedSlopeSolutionEnum,
+	BedSlopeXAnalysisEnum,
+	BedSlopeYAnalysisEnum,
+	DiagnosticHorizAnalysisEnum,
+	DiagnosticHutterAnalysisEnum,
+	DiagnosticSolutionEnum,
+	DiagnosticVertAnalysisEnum,
+	EnthalpyAnalysisEnum,
+	EnthalpySolutionEnum,
+	FlaimAnalysisEnum,
+	FlaimSolutionEnum,
+	HydrologyAnalysisEnum,
+	HydrologySolutionEnum,
+	MeltingAnalysisEnum,
+	NoneAnalysisEnum,
+	PrognosticAnalysisEnum,
+	PrognosticSolutionEnum,
+	SteadystateSolutionEnum,
+	SurfaceSlopeAnalysisEnum,
+	SurfaceSlopeSolutionEnum,
+	SurfaceSlopeXAnalysisEnum,
+	SurfaceSlopeYAnalysisEnum,
+	ThermalAnalysisEnum,
+	ThermalSolutionEnum,
+	TransientSolutionEnum,
+	/*}}}*/
+	/*Approximations {{{1*/
+	ApproximationEnum,
+	HutterApproximationEnum,
+	MacAyealApproximationEnum,
+	MacAyealPattynApproximationEnum,
+	MacAyealStokesApproximationEnum,
+	NoneApproximationEnum,
+	PattynApproximationEnum,
+	PattynStokesApproximationEnum,
+	StokesApproximationEnum,
+	/*}}}*/
+	/*Datasets {{{1*/
+	ConstraintsEnum,
+	LoadsEnum,
+	MaterialsEnum,
+	NodesEnum,
+	ParametersEnum,
+	VerticesEnum,
+	ResultsEnum,
+	/*}}}*/
+	/*Objects {{{1*/
+	BoolInputEnum,
+	BoolParamEnum,
+	ControlInputEnum,
+	DatasetInputEnum,
+	DofIndexingEnum,
+	DoubleInputEnum,
+	DoubleMatArrayParamEnum,
+	DoubleMatParamEnum,
+	DoubleParamEnum,
+	DoubleVecParamEnum,
+	ElementEnum,
+	ElementResultEnum,
+	ExternalResultEnum,
+	FileParamEnum,
+	HookEnum,
+	IcefrontEnum,
+	InputEnum,
+	IntInputEnum,
+	IntParamEnum,
+	IntVecParamEnum,
+	MacAyeal2dIceFrontEnum,
+	MacAyeal3dIceFrontEnum,
+	MaticeEnum,
+	MatparEnum,
+	NodeEnum,
+	NumericalfluxEnum,
+	ParamEnum,
+	PattynIceFrontEnum,
+	PengridEnum,
+	PenpairEnum,
+	PentaEnum,
+	PentaP1InputEnum,
+	PetscMatParamEnum,
+	PetscVecParamEnum,
+	RiftfrontEnum,
+	SegmentEnum,
+	SegmentRiftfrontEnum,
+	SpcDynamicEnum,
+	SpcStaticEnum,
+	SpcTransientEnum,
+	StokesIceFrontEnum,
+	StringArrayParamEnum,
+	StringParamEnum,
+	TriaEnum,
+	TriaP1InputEnum,
+	VertexEnum,
+	/*}}}*/
+	/*Fill {{{1*/
+	AirEnum,
+	IceEnum,
+	MelangeEnum,
+	WaterEnum,
+	/*}}}*/
+	/*Rift state {{{1*/
+	ClosedEnum,
+	FreeEnum,
+	OpenEnum,
+	/*}}}*/
+	/*Inputs {{{1*/
+	AdjointpEnum,
+	AdjointxEnum,
+	AdjointyEnum,
+	AdjointzEnum,
+	BedSlopeXEnum,
+	BedSlopeYEnum,
+	BoundaryEnum,
+	ConstantEnum,
+	ConvergedEnum,
+	ExtToIuEnum,
+	FillEnum,
+	FractionIncrementEnum,
+	FrictionEnum,
+	GroundinglineMeltingRateEnum,
+	InternalEnum,
+	IuToExtEnum,
+	MassFluxEnum,
+	MaxPenetrationEnum,
+	MeltingOffsetEnum,
+	MisfitEnum,
+	NumberNodeToElementConnectivityEnum,
+	PressureEnum,
+	PressurePicardEnum,
+	QmuPressureEnum,
+	QmuVxEnum,
+	QmuVyEnum,
+	QmuVzEnum,
+	QmuThicknessEnum,
+	QmuBedEnum,
+	QmuSurfaceEnum,
+	QmuMeltingEnum,
+	ResetPenaltiesEnum,
+	SegmentOnIceShelfEnum,
+	SurfaceAbsVelMisfitEnum,
+	SurfaceAreaEnum,
+	SurfaceAverageVelMisfitEnum,
+	SurfaceLogVelMisfitEnum,
+	SurfaceLogVxVyMisfitEnum,
+	SurfaceRelVelMisfitEnum,
+	SurfaceSlopeXEnum,
+	SurfaceSlopeYEnum,
+	TemperatureEnum,
+	TemperatureOldEnum,
+	TemperaturePicardEnum,
+	ThicknessAbsMisfitEnum,
+	TypeEnum,
+	VelEnum,
+	VelocityEnum,
+	VxAverageEnum,
+	VxEnum,
+	VxPicardEnum,
+	VyAverageEnum,
+	VyEnum,
+	VyPicardEnum,
+	VzEnum,
+	VzMacAyealEnum,
+	VzPattynEnum,
+	VzPicardEnum,
+	VzStokesEnum,
+	VxMeshEnum,
+	VyMeshEnum,
+	VzMeshEnum,
+	EnthalpyEnum,
+	EnthalpyPicardEnum,
+	ThicknessAbsGradientEnum,
+	StepResponsesEnum,
+	IntMatParamEnum,
+	RheologyBbarAbsGradientEnum,
+	DragCoefficientAbsGradientEnum,
+	TransientInputEnum,
+	OutputfilenameEnum,
+	WaterfractionEnum,
+	WatercolumnEnum,
+	BasalFrictionEnum,
+	ViscousHeatingEnum,
+	QmuTemperatureEnum,
+	HydrologyWaterVxEnum,
+	HydrologyWaterVyEnum,
+	StressTensorEnum,
+	StressTensorxxEnum,
+	StressTensorxyEnum,
+	StressTensorxzEnum,
+	StressTensoryyEnum,
+	StressTensoryzEnum,
+	StressTensorzzEnum,
+	IceVolumeEnum,
+	/*}}}*/
+	/*Element Interpolations{{{1*/
+	P0Enum,
+	P1Enum,
+	P1DGEnum,
+	/*}}}*/
+	/*Results{{{1*/
+	BoolElementResultEnum,
+	BoolExternalResultEnum,
+	DoubleElementResultEnum,
+	DoubleExternalResultEnum,
+	DoubleMatExternalResultEnum,
+	DoubleVecExternalResultEnum,
+	IntExternalResultEnum,
+	JEnum,
+	PatchEnum,
+	PatchNodesEnum,
+	PatchVerticesEnum,
+	PentaP1ElementResultEnum,
+	PetscVecExternalResultEnum,
+	StringExternalResultEnum,
+	TimeEnum,
+	TriaP1ElementResultEnum,
+	WaterColumnOldEnum,
+	/*}}}*/
+	/*Responses{{{1*/
+	MinVelEnum,
+	MaxVelEnum,
+	MinVxEnum,
+	MaxVxEnum,
+	MaxAbsVxEnum,
+	MinVyEnum,
+	MaxVyEnum,
+	MaxAbsVyEnum,
+	MinVzEnum,
+	MaxVzEnum,
+	MaxAbsVzEnum,
+	/*}}}*/
+	/*Convergence{{{1*/
+	RelativeEnum,
+	AbsoluteEnum,
+	IncrementalEnum,
+	/*}}}*/
+	/*Grounding Line{{{1*/
+	AgressiveMigrationEnum,
+	NoneEnum,
+	SoftMigrationEnum,
+	/*}}}*/
+	/*Solver{{{1*/
+	StokesSolverEnum,
+	/*}}}*/
+	/*Parameters{{{1*/
+	AdjointEnum,
+	ColinearEnum,
+	ControlSteadyEnum,
+	FsetEnum,
+	Gradient1Enum,
+	Gradient2Enum,
+	Gradient3Enum,
+	GradientEnum,
+	GroundinglineMigrationEnum,
+	GsetEnum,
+	IndexEnum,
+	IndexedEnum,
+	IntersectEnum,
+	NodalEnum,
+	OldGradientEnum,
+	OutputFilePointerEnum,
+	PetscOptionsAnalysesEnum,
+	PetscOptionsStringsEnum,
+	QmuErrNameEnum,
+	QmuInNameEnum,
+	QmuOutNameEnum,
+	RegularEnum,
+	ScaledEnum,
+	SeparateEnum,
+	SsetEnum,
+	VerboseEnum,
+	/*}}}*/
+	/*Interpolation {{{1*/
+	TriangleInterpEnum,
+	BilinearInterpEnum,
+	NearestInterpEnum,
+	/*}}}*/
+	/*Coordinate Systems{{{1*/
+	XYEnum,
+	XYZPEnum,
+	/*}}}*/
+	/*Options{{{1*/
+	OptionEnum,
+	OptionCellEnum,
+	OptionCharEnum,
+	OptionStructEnum,
+	OptionDoubleEnum,
+	OptionLogicalEnum,
+	/*}}}*/
+	/*Rheology law (move too Material) {{{1*/
+	PatersonEnum,
+	ArrheniusEnum,
+	/*}}}*/
+	MaximumNumberOfEnums
+};
+
+/*Functions on enums: */
+const char *EnumToModelField(int  en);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/EnumDefinitions/EnumToModelField.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/EnumDefinitions/EnumToModelField.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/EnumDefinitions/EnumToModelField.cpp	(revision 11330)
@@ -0,0 +1,30 @@
+/*\file EnumToModelField.cpp:
+* \brief: output string associated with enum, that corresponds  to a model field
+* for example: ThicknessEnum corresponds to model field thickness
+*              FrictionCoefficientEnum corresponds to model field drag
+*/
+
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "./EnumDefinitions.h"
+
+const char* EnumToModelField(int en){
+
+	switch(en){
+
+		case ThicknessEnum : return "thickness";
+		case FrictionCoefficientEnum : return "drag_coefficient";
+		case MaterialsRheologyBEnum : return "rheology_B";
+		case MaterialsRheologyBbarEnum : return "rheology_B";
+		case BalancethicknessThickeningRateEnum: return "dhdt";
+		case VxEnum : return "vx";
+		case InversionVxObsEnum : return "vx_obs";
+		case VyEnum : return "vy";
+		case InversionVyObsEnum : return "vy_obs";
+		case BasalforcingsMeltingRateEnum : return "basal_melting_rate";
+      case SurfaceforcingsAccumulationRateEnum : return "surface_accumulation_rate";
+		case SurfaceforcingsAblationRateEnum : return "surface_ablation_rate";
+		case SurfaceforcingsMassBalanceEnum : return "surface_mass_balance";
+		default : _error_("No model field is associated to enum %s",EnumToStringx(en));
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/EnumDefinitions/README
===================================================================
--- /issm/trunk-jpl-damage/src/c/EnumDefinitions/README	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/EnumDefinitions/README	(revision 11330)
@@ -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 and EnumToModelField.cpp
+
+TO ADD AN ENUM:
+add the corresponding lines to EnumDefinitions.h
+and execute synchronizing script.
Index: /issm/trunk-jpl-damage/src/c/EnumDefinitions/Synchronize.sh
===================================================================
--- /issm/trunk-jpl-damage/src/c/EnumDefinitions/Synchronize.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/EnumDefinitions/Synchronize.sh	(revision 11330)
@@ -0,0 +1,162 @@
+#!/bin/bash
+#Synchronize EnumToStringx.cpp and StringToEnumx.cpp and matlab Enums
+
+#Get all lines of EnumDefinitions2.h which hold Enum | remove all comas | add line number in the first column > put everything in file temp
+cat EnumDefinitions.h | grep -e "[0-9]Enum," -e "[a-zA-Z]Enum," | grep -v include | sed -e "s/,//g" | awk '{ printf "%s %s\n", NR, $0 }' > temp
+
+#Removed existing files
+rm $ISSM_TIER/src/m/enum/*.m
+rm $ISSM_TIER/src/c/modules/EnumToStringx/EnumToStringx.cpp
+rm $ISSM_TIER/src/c/modules/StringToEnumx/StringToEnumx.cpp
+
+#Take care of EnumToModelField.m first (easy)
+#Build EnumToModelField.m {{{1
+cat <<END > $ISSM_TIER/src/m/enum/EnumToModelField.m
+function string=EnumToModelField(enum)
+%ENUMTOMODELFIELD - output string of model field associated to enum
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      string=EnumToModelField(enum)
+
+switch enum,
+
+END
+
+cat EnumToModelField.cpp | grep "case" | sed -e "s/Enum :/Enum(),/g" -e "s/\"/'/g" -e "s/return /string=/g" -e "s/;/; return/g" >> $ISSM_TIER/src/m/enum/EnumToModelField.m
+
+cat <<END >> $ISSM_TIER/src/m/enum/EnumToModelField.m
+		otherwise, error(['Enum ' num2str(enum)  ' not found associated to any model field']);
+
+end
+END
+#}}}
+#Build EnumToStringx.cpp {{{1
+#Header
+cat <<END >  $ISSM_TIER/src/c/modules/EnumToStringx/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 "../../shared/shared.h"
+#include "../../include/include.h"
+#include "./EnumToStringx.h"
+
+const char* EnumToStringx(int en){
+
+	switch(en){
+
+END
+#core
+cat temp |  awk '{print "\t\t" "case " $2" : return \"" substr($2,1,length($2)-4) "\";"}' >> $ISSM_TIER/src/c/modules/EnumToStringx/EnumToStringx.cpp
+#Footer
+cat <<END >> $ISSM_TIER/src/c/modules/EnumToStringx/EnumToStringx.cpp
+		default : return "unknown";
+
+	}
+}
+void EnumToStringx(char** pstring,int enum_in){
+	char *string = NULL;
+	int   len = 0;
+
+	len=strlen(EnumToStringx(enum_in));
+	string=(char*)xmalloc((len+1)*sizeof(char));
+	memcpy(string,EnumToStringx(enum_in),(len+1)*sizeof(char));
+
+	/*Assign output pointer*/
+	*pstring=string;
+}
+END
+#}}}
+#Build StringToEnumx.cpp {{{1
+#Header
+cat <<END > $ISSM_TIER/src/c/modules/StringToEnumx/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 "../../shared/shared.h"
+#include "../../include/include.h"
+#include "./StringToEnumx.h"
+
+int  StringToEnumx(const char* name){
+
+END
+#core
+cat temp |  awk '{print "\t" ((NR==1)?"if":"else if") " (strcmp(name,\"" substr($2,1,length($2)-4) "\")==0) return " $2 ";"}' >> $ISSM_TIER//src/c/modules/StringToEnumx/StringToEnumx.cpp
+#Footer
+cat <<END >> $ISSM_TIER/src/c/modules/StringToEnumx/StringToEnumx.cpp
+	else _error_("Enum %s not found",name);
+
+}
+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 and enum of the line i
+	NAMEENUM=$(cat temp | grep "^[ ]*$i " | awk '{printf("%s",$2);}');
+	NAME=$(echo $NAMEENUM | sed -e "s/Enum//g")
+	ENUM=$i;
+	#offset Enum by one (Enum begins with 0 and not 1!)
+	let ENUM=$ENUM-1
+
+	#print info {{{
+	if [ $i -lt 10 ]
+	then
+		printf "\r                                                                      "
+		printf "\r  $i/$NUMBEROFLINES Adding "$NAME"..."
+	else
+		if [ $i -lt 100 ]
+		then
+			printf "\r                                                                      "
+			printf "\r $i/$NUMBEROFLINES Adding "$NAME"..."
+		else
+			printf "\r                                                                      "
+			printf "\r$i/$NUMBEROFLINES Adding "$NAME"..."
+		fi
+	fi
+	#}}}
+	#Add case to matlabenum file{{{
+	cat <<END > $ISSM_TIER"/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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/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/trunk-jpl-damage/src/c/Makefile.am
===================================================================
--- /issm/trunk-jpl-damage/src/c/Makefile.am	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/Makefile.am	(revision 11330)
@@ -0,0 +1,921 @@
+INCLUDES = @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @MPIINCL@ @MATLABINCL@  @METISINCL@  @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@  @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@  @TRIANGLEINCL@ @HYPREINCL@ @MLINCL@ @TAOINCL@
+
+#Library declaration {{{1
+#Compile serial library, and then try and compile parallel library
+if NOSERIAL
+if NOPARALLEL
+lib_LIBRARIES = 
+else
+lib_LIBRARIES = libpISSM.a libOverload.a
+endif
+else
+if NOPARALLEL
+lib_LIBRARIES = libISSM.a  libOverload.a
+else
+lib_LIBRARIES = libISSM.a libpISSM.a libOverload.a
+endif
+endif
+#}}}
+
+#sources
+#Core sources{{{1
+core_sources   = ./include/macros.h\
+					./include/typedefs.h\
+					./include/types.h\
+					./include/include.h\
+					./objects/objects.h\
+					./objects/Object.h\
+					./objects/Gauss/GaussTria.h\
+					./objects/Gauss/GaussTria.cpp\
+					./objects/Update.h\
+					./objects/Element.h\
+					./objects/FemModel.h\
+					./objects/FemModel.cpp\
+					./objects/Material.h\
+					./objects/Load.h\
+					./objects/Contour.h\
+					./objects/Contour.cpp\
+					./objects/OptArgs.h\
+					./objects/OptPars.h\
+					./objects/Loads/Friction.h\
+					./objects/Loads/Friction.cpp\
+					./objects/Inputs/TransientInput.h\
+					./objects/Inputs/TransientInput.cpp\
+					./objects/Constraints/SpcTransient.cpp\
+					./objects/Constraints/SpcTransient.h\
+					./objects/DofIndexing.h\
+					./objects/DofIndexing.cpp\
+					./objects/IoModel.h\
+					./objects/IoModel.cpp\
+					./objects/Node.h\
+					./objects/Node.cpp\
+					./objects/Segment.h\
+					./objects/Segment.cpp\
+					./objects/Vertex.h\
+					./objects/Vertex.cpp\
+					./objects/Hook.h\
+					./objects/Hook.cpp\
+					./objects/Patch.h\
+					./objects/Patch.cpp\
+					./objects/ElementResults/ElementResultLocal.h\
+					./objects/ElementResults/DoubleElementResult.h\
+					./objects/ElementResults/DoubleElementResult.cpp\
+					./objects/ElementResults/TriaP1ElementResult.h\
+					./objects/ElementResults/TriaP1ElementResult.cpp\
+					./objects/ElementResults/BoolElementResult.h\
+					./objects/ElementResults/BoolElementResult.cpp\
+					./objects/ExternalResults/ExternalResult.h\
+					./objects/ExternalResults/BoolExternalResult.h\
+					./objects/ExternalResults/BoolExternalResult.cpp\
+					./objects/ExternalResults/DoubleExternalResult.h\
+					./objects/ExternalResults/DoubleExternalResult.cpp\
+					./objects/ExternalResults/DoubleVecExternalResult.h\
+					./objects/ExternalResults/DoubleVecExternalResult.cpp\
+					./objects/ExternalResults/DoubleMatExternalResult.h\
+					./objects/ExternalResults/DoubleMatExternalResult.cpp\
+					./objects/ExternalResults/IntExternalResult.h\
+					./objects/ExternalResults/IntExternalResult.cpp\
+					./objects/ExternalResults/StringExternalResult.h\
+					./objects/ExternalResults/StringExternalResult.cpp\
+					./objects/ExternalResults/PetscVecExternalResult.h\
+					./objects/ExternalResults/PetscVecExternalResult.cpp\
+					./objects/Elements/Tria.h\
+					./objects/Elements/Tria.cpp\
+					./objects/Elements/TriaHook.h\
+					./objects/Elements/TriaHook.cpp\
+					./objects/Elements/TriaRef.h\
+					./objects/Elements/TriaRef.cpp\
+					./objects/Inputs/Input.h\
+					./objects/Inputs/InputLocal.h\
+					./objects/Inputs/TriaP1Input.h\
+					./objects/Inputs/TriaP1Input.cpp\
+					./objects/Inputs/BoolInput.h\
+					./objects/Inputs/BoolInput.cpp\
+					./objects/Inputs/IntInput.h\
+					./objects/Inputs/IntInput.cpp\
+					./objects/Inputs/DoubleInput.h\
+					./objects/Inputs/DoubleInput.cpp\
+					./objects/Inputs/DatasetInput.h\
+					./objects/Inputs/DatasetInput.cpp\
+					./objects/Materials/Matice.h\
+					./objects/Materials/Matice.cpp\
+					./objects/Materials/Matpar.h\
+					./objects/Materials/Matpar.cpp\
+					./objects/Constraints/Constraint.h\
+					./objects/Constraints/SpcStatic.cpp\
+					./objects/Constraints/SpcStatic.h\
+					./objects/Constraints/SpcDynamic.cpp\
+					./objects/Constraints/SpcDynamic.h\
+					./objects/Loads/Penpair.cpp\
+					./objects/Loads/Penpair.h\
+					./objects/Loads/Pengrid.cpp\
+					./objects/Loads/Pengrid.h\
+					./objects/Loads/Icefront.cpp\
+					./objects/Loads/Icefront.h\
+					./objects/Loads/Numericalflux.cpp\
+					./objects/Loads/Numericalflux.h\
+					./objects/Numerics/ElementMatrix.h\
+					./objects/Numerics/ElementMatrix.cpp\
+					./objects/Numerics/ElementVector.h\
+					./objects/Numerics/ElementVector.cpp\
+					./objects/Params/Param.h\
+					./objects/Params/BoolParam.cpp\
+					./objects/Params/BoolParam.h\
+					./objects/Params/IntParam.cpp\
+					./objects/Params/IntParam.h\
+					./objects/Params/IntVecParam.cpp\
+					./objects/Params/IntVecParam.h\
+					./objects/Params/IntMatParam.cpp\
+					./objects/Params/IntMatParam.h\
+					./objects/Params/DoubleParam.cpp\
+					./objects/Params/DoubleParam.h\
+					./objects/Params/FileParam.cpp\
+					./objects/Params/FileParam.h\
+					./objects/Params/PetscMatParam.cpp\
+					./objects/Params/PetscMatParam.h\
+					./objects/Params/StringArrayParam.cpp\
+					./objects/Params/StringArrayParam.h\
+					./objects/Params/DoubleMatParam.cpp\
+					./objects/Params/DoubleMatParam.h\
+					./objects/Params/DoubleTransientMatParam.cpp\
+					./objects/Params/DoubleTransientMatParam.h\
+					./objects/Params/DoubleMatArrayParam.cpp\
+					./objects/Params/DoubleMatArrayParam.h\
+					./objects/Params/DoubleVecParam.cpp\
+					./objects/Params/DoubleVecParam.h\
+					./objects/Params/PetscVecParam.cpp\
+					./objects/Params/PetscVecParam.h\
+					./objects/Params/StringParam.cpp\
+					./objects/Params/StringParam.h\
+					./Container/Container.h\
+					./Container/Constraints.h\
+					./Container/Constraints.cpp\
+					./Container/DataSet.h\
+					./Container/DataSet.cpp\
+					./Container/Elements.h\
+					./Container/Elements.cpp\
+					./Container/Inputs.h\
+					./Container/Inputs.cpp\
+					./Container/Loads.h\
+					./Container/Loads.cpp\
+					./Container/Materials.h\
+					./Container/Materials.cpp\
+					./Container/Nodes.h\
+					./Container/Nodes.cpp\
+					./Container/Options.h\
+					./Container/Options.cpp\
+					./Container/Parameters.h\
+					./Container/Parameters.cpp\
+					./Container/Results.h\
+					./Container/Results.cpp\
+					./Container/Vertices.h\
+					./Container/Vertices.cpp\
+					./shared/shared.h\
+					./shared/Alloc/alloc.h\
+					./shared/Alloc/alloc.cpp\
+					./shared/Matrix/matrix.h\
+					./shared/Matrix/MatrixUtils.cpp\
+					./shared/Dofs/dofs.h\
+					./shared/Dofs/dofsetgen.cpp\
+					./shared/Numerics/numerics.h\
+					./shared/Numerics/Verbosity.h\
+					./shared/Numerics/Verbosity.cpp\
+					./shared/Numerics/IsInputConverged.cpp\
+					./shared/Numerics/GaussPoints.h\
+					./shared/Numerics/GaussPoints.cpp\
+					./shared/Numerics/cross.cpp\
+					./shared/Numerics/extrema.cpp\
+					./shared/Numerics/XZvectorsToCoordinateSystem.cpp\
+					./shared/Numerics/UnitConversion.cpp\
+					./shared/Numerics/PetscOptionsFromAnalysis.cpp\
+					./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/GetVerticesCoordinates.cpp\
+					./shared/Elements/GetLocalDofList.cpp\
+					./shared/Elements/GetGlobalDofList.cpp\
+					./shared/Elements/GetNumberOfDofs.cpp\
+					./shared/Elements/CoordinateSystemTransform.cpp\
+					./shared/String/sharedstring.h\
+					./toolkits/petsc\
+					./toolkits/petsc/patches\
+					./toolkits/petsc/patches/SolverEnum.h\
+					./toolkits/petsc/patches/petscpatches.h\
+					./toolkits/petsc/patches/MatlabMatrixToPetscMatrix.cpp\
+					./toolkits/petsc/patches/MatlabVectorToPetscVector.cpp\
+					./toolkits/petsc/patches/PetscMatrixToMatlabMatrix.cpp\
+					./toolkits/petsc/patches/PetscVectorToMatlabVector.cpp\
+					./toolkits/petsc/patches/MatlabMatrixToDoubleMatrix.cpp\
+					./toolkits/petsc/patches/MatlabVectorToDoubleVector.cpp\
+					./toolkits/petsc/patches/PetscDetermineLocalSize.cpp\
+					./toolkits/petsc/patches/VecTranspose.cpp\
+					./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/SerialToVec.cpp\
+					./toolkits/petsc/patches/VecFree.cpp\
+					./toolkits/petsc/patches/VecDuplicatePatch.cpp\
+					./toolkits/petsc/patches/KSPFree.cpp\
+					./toolkits/petsc/patches/ISFree.cpp\
+					./toolkits/petsc/patches/MatFree.cpp\
+					./toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp\
+					./toolkits/petsc/patches/VecPartition.cpp\
+					./toolkits/petsc/patches/MatPartition.cpp\
+					./toolkits/petsc/patches/MatInvert.cpp\
+					./toolkits/petsc/patches/MatMultPatch.cpp\
+					./toolkits/petsc/petscincludes.h\
+					./toolkits/mpi/mpiincludes.h\
+					./toolkits/mpi/patches/mpipatches.h\
+					./toolkits/mpi/patches/MPI_Upperrow.cpp\
+					./toolkits/mpi/patches/MPI_Lowerrow.cpp\
+					./toolkits/mpi/patches/MPI_Boundariesfromrange.cpp\
+					./toolkits/metis/metisincludes.h\
+					./toolkits/metis/patches/metispatches.h\
+					./toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp\
+					./toolkits/triangle/triangleincludes.h\
+					./toolkits.h\
+					./io/io.h\
+					./io/Disk/diskio.h\
+					./io/Disk/pfopen.cpp\
+					./io/Disk/pfclose.cpp\
+					./io/PrintfFunction.cpp\
+					./EnumDefinitions/EnumDefinitions.h\
+					./EnumDefinitions/EnumToModelField.cpp\
+					./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/CreateSingleNodeToElementConnectivity.cpp\
+					./modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp\
+					./modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp\
+					./modules/ParsePetscOptionsx/ParsePetscOptionsx.h\
+					./modules/ParsePetscOptionsx/ParsePetscOptionsx.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/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/TimeAdaptx/TimeAdaptx.h\
+					./modules/TimeAdaptx/TimeAdaptx.cpp\
+					./modules/UpdateVertexPositionsx/UpdateVertexPositionsx.h\
+					./modules/UpdateVertexPositionsx/UpdateVertexPositionsx.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/UpdateConstraintsx/UpdateConstraintsx.h\
+					./modules/UpdateConstraintsx/UpdateConstraintsx.cpp\
+					./modules/MeshPartitionx/MeshPartitionx.cpp\
+					./modules/MeshPartitionx/MeshPartitionx.h\
+					./modules/Reducevectorgtofx/Reducevectorgtofx.cpp\
+					./modules/Reducevectorgtofx/Reducevectorgtofx.h\
+					./modules/Reduceloadx/Reduceloadx.h\
+					./modules/Reduceloadx/Reduceloadx.cpp\
+					./modules/EnumToStringx/EnumToStringx.cpp\
+					./modules/EnumToStringx/EnumToStringx.h\
+					./modules/StringToEnumx/StringToEnumx.cpp\
+					./modules/StringToEnumx/StringToEnumx.h\
+					./modules/SystemMatricesx/SystemMatricesx.cpp\
+					./modules/SystemMatricesx/SystemMatricesx.h\
+					./modules/ConstraintsStatex/ConstraintsStatex.cpp\
+					./modules/ConstraintsStatex/ConstraintsStatex.h\
+					./modules/ConstraintsStatex/ConstraintsStateLocal.h\
+					./modules/Responsex/Responsex.h\
+					./modules/Responsex/Responsex.cpp\
+					./modules/RequestedOutputsx/RequestedOutputsx.h\
+					./modules/RequestedOutputsx/RequestedOutputsx.cpp\
+					./modules/ResetConstraintsx/ResetConstraintsx.h\
+					./modules/ResetConstraintsx/ResetConstraintsx.cpp\
+					./modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h\
+					./modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp\
+					./modules/Solverx/Solverx.cpp\
+					./modules/Solverx/Solverx.h\
+					./modules/Solverx/DofTypesToIndexSet.cpp\
+					./modules/VecMergex/VecMergex.cpp\
+					./modules/VecMergex/VecMergex.h\
+					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp\
+					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h\
+					./modules/InputToResultx/InputToResultx.cpp\
+					./modules/InputToResultx/InputToResultx.h\
+					./modules/InputConvergencex/InputConvergencex.cpp\
+					./modules/InputConvergencex/InputConvergencex.h\
+					./solutions/convergence.cpp\
+					./solutions/ProcessArguments.cpp\
+					./solutions/WriteLockFile.cpp\
+					./solutions/ResetBoundaryConditions.cpp\
+					./solutions/AnalysisConfiguration.cpp\
+					./solutions/CorePointerFromSolutionEnum.cpp\
+					./solvers/solver_linear.cpp\
+					./solvers/solver_nonlinear.cpp
+#}}}
+#DAKOTA sources  {{{1
+dakota_sources = ./objects/DakotaPlugin.h\
+					  ./objects/DakotaPlugin.cpp\
+					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h\
+					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp\
+					  ./modules/DakotaResponsesx/DakotaResponsesx.h\
+					  ./modules/DakotaResponsesx/DakotaResponsesx.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/Dakotax/Dakotax.h\
+					  ./modules/Dakotax/Dakotax.cpp\
+					  ./modules/Dakotax/DakotaMPI_Bcast.cpp\
+					  ./modules/Dakotax/DakotaFree.cpp\
+					  ./modules/Dakotax/SpawnCore.cpp\
+					  ./modules/Dakotax/DescriptorIndex.cpp\
+					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp\
+					  ./modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp\
+					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.h
+dakota_psources= ./modules/Dakotax/SpawnCoreParallel.cpp
+#}}}
+#Transient sources  {{{1
+transient_sources  = ./modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp
+transient_psources = ./solutions/transient_core.cpp
+#}}}
+#Steadystate sources  {{{1
+steadystate_psources = ./solutions/steadystate_core.cpp\
+					        ./solutions/steadystateconvergence.cpp
+#}}}
+#Prognostic sources  {{{1
+prognostic_sources = ./modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp\
+					      ./modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp\
+					      ./modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp\
+					      ./modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp
+prognostic_psources = ./solutions/prognostic_core.cpp
+#}}}
+#Thermal sources  {{{1
+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
+
+thermal_psources = ./solutions/thermal_core.cpp\
+					    ./solutions/thermal_core_step.cpp\
+					    ./solutions/enthalpy_core.cpp\
+					    ./solutions/enthalpy_core_step.cpp\
+					    ./solvers/solver_thermal_nonlinear.cpp
+#}}}
+#Control sources  {{{1
+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/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/CostFunctionx/CostFunctionx.h\
+					  ./modules/CostFunctionx/CostFunctionx.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/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp\
+					  ./modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h\
+					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp\
+					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h\
+					  ./objects/Inputs/ControlInput.h\
+					  ./objects/Inputs/ControlInput.cpp\
+					  ./shared/Numerics/BrentSearch.cpp\
+					  ./shared/Numerics/OptimalSearch.cpp\
+					  ./shared/Numerics/OptFunc.cpp
+
+control_psources=./solutions/control_core.cpp\
+					  ./solutions/controltao_core.cpp\
+					  ./solutions/controlrestart.cpp\
+					  ./solutions/controlconvergence.cpp\
+					  ./solutions/objectivefunctionC.cpp\
+					  ./solutions/gradient_core.cpp\
+					  ./solutions/adjointdiagnostic_core.cpp\
+					  ./solutions/adjointbalancethickness_core.cpp\
+					  ./solutions/AdjointCorePointerFromSolutionEnum.cpp\
+					  ./solvers/solver_adjoint_linear.cpp
+
+#}}}
+#Hydrology sources  {{{1
+hydrology_sources  = ./modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp\
+					      ./modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp\
+					      ./modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp\
+					      ./modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp
+					  
+hydrology_psources  = ./solutions/hydrology_core.cpp\
+					       ./solutions/hydrology_core_step.cpp 
+#}}}
+#Diagnostic sources  {{{1
+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 \
+							./shared/Elements/TransformLoadVectorCoord.cpp \
+							./shared/Elements/TransformStiffnessMatrixCoord.cpp \
+							./shared/Elements/TransformInvStiffnessMatrixCoord.cpp \
+							./shared/Elements/TransformSolutionCoord.cpp
+diagnostic_psources =./solutions/diagnostic_core.cpp\
+					      ./solvers/solver_stokescoupling_nonlinear.cpp
+#}}}
+#Balanced sources  {{{1
+balanced_sources = ./modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp\
+					    ./modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp\
+					    ./modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp\
+					    ./modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp
+balanced_psources = ./solutions/balancethickness_core.cpp
+#}}}
+#Responses sources  {{{1
+responses_sources = ./modules/MinVelx/MinVelx.h\
+					     ./modules/MinVelx/MinVelx.cpp\
+					     ./modules/MaxVelx/MaxVelx.h\
+					     ./modules/MaxVelx/MaxVelx.cpp\
+					     ./modules/MaxAbsVxx/MaxAbsVxx.h\
+					     ./modules/MaxAbsVxx/MaxAbsVxx.cpp\
+					     ./modules/MaxAbsVyx/MaxAbsVyx.h\
+					     ./modules/MaxAbsVyx/MaxAbsVyx.cpp\
+					     ./modules/MaxAbsVzx/MaxAbsVzx.h\
+					     ./modules/MaxAbsVzx/MaxAbsVzx.cpp\
+					     ./modules/MaxVxx/MaxVxx.h\
+					     ./modules/MaxVxx/MaxVxx.cpp\
+					     ./modules/MaxVyx/MaxVyx.h\
+					     ./modules/MaxVyx/MaxVyx.cpp\
+					     ./modules/MaxVzx/MaxVzx.h\
+					     ./modules/MaxVzx/MaxVzx.cpp\
+					     ./modules/MinVxx/MinVxx.h\
+					     ./modules/MinVxx/MinVxx.cpp\
+					     ./modules/MinVyx/MinVyx.h\
+					     ./modules/MinVyx/MinVyx.cpp\
+					     ./modules/MinVzx/MinVzx.h\
+					     ./modules/MinVzx/MinVzx.cpp\
+					     ./modules/IceVolumex/IceVolumex.h\
+					     ./modules/IceVolumex/IceVolumex.cpp\
+					     ./modules/ElementResponsex/ElementResponsex.h\
+					     ./modules/ElementResponsex/ElementResponsex.cpp\
+					     ./modules/MassFluxx/MassFluxx.cpp\
+					     ./modules/MassFluxx/MassFluxx.h
+#}}}
+#Slope sources  {{{1
+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
+slope_psources = ./solutions/surfaceslope_core.cpp\
+					  ./solutions/bedslope_core.cpp
+#}}}
+#Groundingline sources  {{{1
+groundingline_sources= ./modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp\
+					        ./modules/GroundinglineMigrationx/GroundinglineMigrationx.h
+#}}}
+#Rifts sources  {{{1
+rifts_sources = ./objects/Loads/Riftfront.cpp\
+				    ./objects/Loads/Riftfront.h\
+				    ./modules/ConstraintsStatex/RiftConstraintsState.cpp
+#}}}
+#3D sources  {{{1
+threed_sources = ./objects/Gauss/GaussPenta.h\
+				     ./objects/Gauss/GaussPenta.cpp\
+				     ./objects/ElementResults/PentaP1ElementResult.h\
+				     ./objects/ElementResults/PentaP1ElementResult.cpp\
+				     ./objects/Inputs/PentaP1Input.h\
+				     ./objects/Inputs/PentaP1Input.cpp\
+				     ./objects/Elements/Penta.h\
+				     ./objects/Elements/Penta.cpp\
+				     ./objects/Elements/PentaHook.h\
+				     ./objects/Elements/PentaHook.cpp\
+				     ./objects/Elements/PentaRef.h\
+				     ./objects/Elements/PentaRef.cpp
+#}}}
+#Bamg sources  {{{1
+bamg_sources =  ./objects/Bamg/BamgGeom.h\
+				./objects/Bamg/BamgGeom.cpp\
+				./objects/Bamg/BamgMesh.h\
+				./objects/Bamg/BamgMesh.cpp\
+				./objects/Bamg/BamgOpts.h\
+				./objects/Bamg/BamgOpts.cpp\
+				./objects/Bamg/CrackedEdge.h\
+				./objects/Bamg/CrackedEdge.cpp\
+				./objects/Bamg/Curve.h\
+				./objects/Bamg/Curve.cpp\
+				./objects/Bamg/Direction.h\
+				./objects/Bamg/Direction.cpp\
+				./objects/Bamg/DoubleAndInt.h\
+				./objects/Bamg/Edge.h\
+				./objects/Bamg/Edge.cpp\
+				./objects/Bamg/GeomEdge.h\
+				./objects/Bamg/GeomEdge.cpp\
+				./objects/Bamg/GeomSubDomain.h\
+				./objects/Bamg/GeomSubDomain.cpp\
+				./objects/Bamg/GeomVertex.h\
+				./objects/Bamg/GeomVertex.cpp\
+				./objects/Bamg/Geometry.cpp\
+				./objects/Bamg/Geometry.h\
+				./objects/Bamg/ListofIntersectionTriangles.cpp\
+				./objects/Bamg/ListofIntersectionTriangles.h\
+				./objects/Bamg/EigenMetric.cpp\
+				./objects/Bamg/Metric.cpp\
+				./objects/Bamg/Metric.h\
+				./objects/Bamg/QuadTree.cpp\
+				./objects/Bamg/QuadTree.h\
+				./objects/Bamg/R2.h\
+				./objects/Bamg/SetOfE4.cpp\
+				./objects/Bamg/SetOfE4.h\
+				./objects/Bamg/SubDomain.h\
+				./objects/Bamg/SubDomain.cpp\
+				./objects/Bamg/AdjacentTriangle.h\
+				./objects/Bamg/AdjacentTriangle.cpp\
+				./objects/Bamg/Triangle.cpp\
+				./objects/Bamg/Triangle.h\
+				./objects/Bamg/BamgVertex.cpp\
+				./objects/Bamg/BamgVertex.h\
+				./objects/Bamg/VertexOnEdge.h\
+				./objects/Bamg/VertexOnEdge.cpp\
+				./objects/Bamg/VertexOnGeom.h\
+				./objects/Bamg/VertexOnGeom.cpp\
+				./objects/Bamg/VertexOnVertex.h\
+				./objects/Bamg/VertexOnVertex.cpp\
+				./objects/Bamg/Mesh.cpp\
+				./objects/Bamg/Mesh.h\
+				./shared/Bamg/Abs.h \
+				./shared/Bamg/BigPrimeNumber.h\
+				./shared/Bamg/BigPrimeNumber.cpp\
+				./shared/Bamg/BinaryRand.h \
+				./shared/Bamg/det.h \
+				./shared/Bamg/Exchange.h \
+				./shared/Bamg/extrema.h \
+				./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
+#}}}
+#Kml sources  {{{1
+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\
+			     ./objects/KML/KML_Attribute.cpp\
+			     ./objects/KML/KML_Attribute.h\
+			     ./objects/KML/KML_Comment.cpp\
+			     ./objects/KML/KML_Comment.h\
+			     ./objects/KML/KML_ColorStyle.cpp\
+			     ./objects/KML/KML_ColorStyle.h\
+			     ./objects/KML/KML_Container.cpp\
+			     ./objects/KML/KML_Container.h\
+			     ./objects/KML/KML_Document.cpp\
+			     ./objects/KML/KML_Document.h\
+			     ./objects/KML/KML_Feature.cpp\
+			     ./objects/KML/KML_Feature.h\
+			     ./objects/KML/KML_File.cpp\
+			     ./objects/KML/KML_File.h\
+			     ./objects/KML/KML_Folder.cpp\
+			     ./objects/KML/KML_Folder.h\
+			     ./objects/KML/KML_Geometry.cpp\
+			     ./objects/KML/KML_Geometry.h\
+			     ./objects/KML/KML_GroundOverlay.cpp\
+			     ./objects/KML/KML_GroundOverlay.h\
+			     ./objects/KML/KML_Icon.cpp\
+			     ./objects/KML/KML_Icon.h\
+			     ./objects/KML/KML_LatLonBox.cpp\
+		  	     ./objects/KML/KML_LatLonBox.h\
+			     ./objects/KML/KML_LinearRing.cpp\
+			     ./objects/KML/KML_LinearRing.h\
+			     ./objects/KML/KML_LineString.cpp\
+			     ./objects/KML/KML_LineString.h\
+			     ./objects/KML/KML_LineStyle.cpp\
+			     ./objects/KML/KML_LineStyle.h\
+			     ./objects/KML/KML_MultiGeometry.cpp\
+			     ./objects/KML/KML_MultiGeometry.h\
+			     ./objects/KML/KML_Object.cpp\
+			     ./objects/KML/KML_Object.h\
+			     ./objects/KML/KML_Overlay.cpp\
+			     ./objects/KML/KML_Overlay.h\
+			     ./objects/KML/KML_Point.cpp\
+			     ./objects/KML/KML_Point.h\
+			     ./objects/KML/KML_Placemark.cpp\
+			     ./objects/KML/KML_Placemark.h\
+			     ./objects/KML/KML_Polygon.cpp\
+			     ./objects/KML/KML_Polygon.h\
+			     ./objects/KML/KML_PolyStyle.cpp\
+			     ./objects/KML/KML_PolyStyle.h\
+			     ./objects/KML/KML_Style.cpp\
+			     ./objects/KML/KML_Style.h\
+			     ./objects/KML/KML_StyleSelector.cpp\
+			     ./objects/KML/KML_StyleSelector.h\
+			     ./objects/KML/KML_SubStyle.cpp\
+			     ./objects/KML/KML_SubStyle.h\
+			     ./objects/KML/KML_Unknown.cpp\
+			     ./objects/KML/KML_Unknown.h\
+			     ./objects/KML/KMLFileReadUtils.cpp\
+			     ./objects/KML/KMLFileReadUtils.h
+#}}}
+#Matlab sources  {{{1
+matlab_sources= ./shared/Matlab/matlabshared.h\
+				    ./shared/Matlab/ModuleBoot.cpp\
+				    ./shared/Matlab/ModuleEnd.cpp\
+				    ./shared/Matlab/mxGetAssignedField.cpp\
+				    ./shared/Matlab/mxGetField.cpp\
+				    ./shared/Matlab/CheckNumMatlabArguments.cpp\
+				    ./toolkits/matlab/matlabincludes.h\
+				    ./toolkits/matlab/MatlabNArrayToNArray.cpp\
+				    ./io/Matlab/matlabio.h\
+				    ./io/Matlab/WriteMatlabData.cpp\
+				    ./io/Matlab/FetchMatlabData.cpp\
+				    ./io/Matlab/OptionParse.cpp
+#}}}
+#Serialsources  {{{1
+serial_sources= ./objects/Options/Option.cpp\
+			./objects/Options/Option.h\
+			./objects/Options/OptionDouble.cpp\
+			./objects/Options/OptionDouble.h\
+			./objects/Options/OptionLogical.cpp\
+			./objects/Options/OptionLogical.h\
+			./objects/Options/OptionChar.cpp\
+			./objects/Options/OptionChar.h\
+			./objects/Options/OptionStruct.cpp\
+			./objects/Options/OptionStruct.h\
+			./objects/Options/OptionCell.cpp\
+			./objects/Options/OptionCell.h\
+			./objects/Options/OptionUtilities.cpp\
+			./objects/Options/OptionUtilities.h\
+			./shared/Threads/issm_threads.h\
+			./shared/Threads/LaunchThread.cpp\
+			./shared/Threads/PartitionRange.cpp\
+			./shared/Numerics/isnan.h\
+			./shared/Numerics/isnan.cpp\
+			./shared/Exp/exp.h\
+			./shared/Exp/IsInPoly.cpp\
+			./shared/Exp/IsInPolySerial.cpp\
+			./shared/Exp/DomainOutlineRead.cpp\
+			./shared/Exp/DomainOutlineWrite.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/AddExternalResultx/AddExternalResultx.h\
+			./modules/AddExternalResultx/AddExternalResultx.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/Dakotax/SpawnCoreSerial.cpp\
+			./modules/TriaSearchx/TriaSearchx.h\
+			./modules/TriaSearchx/TriaSearchx.cpp\
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h\
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp\
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp\
+			./modules/Xy2llx/Xy2llx.h\
+			./modules/Xy2llx/Xy2llx.cpp\
+			./modules/Ll2xyx/Ll2xyx.h\
+			./modules/Ll2xyx/Ll2xyx.cpp\
+			./modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp\
+			./modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h\
+			./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/AverageFilterx/AverageFilterx.cpp\
+			./modules/AverageFilterx/AverageFilterx.h\
+			./modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp\
+			./modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h\
+			./modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp\
+			./modules/MeshProfileIntersectionx/ElementSegmentsIntersection.cpp\
+			./modules/MeshProfileIntersectionx/ElementSegment.cpp\
+			./modules/MeshProfileIntersectionx/SegmentIntersect.cpp\
+			./modules/MeshProfileIntersectionx/NodeInElement.cpp\
+			./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
+#}}}
+
+#ISSM sources are a combination of core sources and sources related to specific capabilities (which can 
+#be activated by autotools conditionals {{{1
+
+#First the core
+issm_sources  =  $(core_sources)
+issm_psources =  
+
+#Now the optional source
+if DAKOTA
+issm_sources  +=  $(dakota_sources)
+issm_psources +=  $(dakota_psources)
+endif
+
+if TRANSIENT
+issm_sources  +=  $(transient_sources)
+issm_psources +=  $(transient_psources)
+endif
+
+if STEADYSTATE
+issm_sources  +=  $(steadystate_sources)
+issm_psources +=  $(steadystate_psources)
+endif
+
+if PROGNOSTIC
+issm_sources  +=  $(prognostic_sources)
+issm_psources +=  $(prognostic_psources)
+endif
+
+if THERMAL
+issm_sources  +=  $(thermal_sources)
+issm_psources +=  $(thermal_psources)
+endif
+
+if CONTROL
+issm_sources  +=  $(control_sources)
+issm_psources +=  $(control_psources)
+endif
+
+if HYDROLOGY
+issm_sources  +=  $(hydrology_sources)
+issm_psources +=  $(hydrology_psources)
+endif
+
+if DIAGNOSTIC
+issm_sources  +=  $(diagnostic_sources)
+issm_psources +=  $(diagnostic_psources)
+endif
+
+if BALANCED
+issm_sources  +=  $(balanced_sources)
+issm_psources +=  $(balanced_psources)
+endif
+
+if RESPONSES
+issm_sources +=  $(responses_sources)
+endif
+
+if SLOPE
+issm_sources  +=  $(slope_sources)
+issm_psources +=  $(slope_psources)
+endif
+
+if GROUNDINGLINE
+issm_sources +=  $(groundingline_sources)
+endif
+
+if RIFTS
+issm_sources +=  $(rifts_sources)
+endif
+
+if THREED
+issm_sources +=  $(threed_sources)
+endif
+#}}}
+
+#ISSM serial library {{{1
+libISSM_a_SOURCES  = $(issm_sources)
+libISSM_a_SOURCES += $(serial_sources)
+libISSM_a_SOURCES += $(bamg_sources)
+libISSM_a_SOURCES += $(kml_sources)
+libISSM_a_SOURCES += $(matlab_sources)
+
+libISSM_a_CXXFLAGS = -fPIC -DMATLAB -D_SERIAL_ -ansi -D_GNU_SOURCE -fno-omit-frame-pointer -pthread -D_CPP_  $(CXXOPTFLAGS)
+if LARGEARRAYS
+libISSM_a_CXXFLAGS += -D__GCC4BUILD__  
+else
+libISSM_a_CXXFLAGS += -DMX_COMPAT_32 
+endif
+#}}}
+#ISSM parallel library {{{1
+libpISSM_a_SOURCES  = $(issm_sources)
+libpISSM_a_SOURCES += $(issm_psources)
+libpISSM_a_CXXFLAGS = -fPIC -D_PARALLEL_   -D_C_ $(CXXOPTFLAGS) 
+#}}}
+#Overload library, to overload any non-standard symbols. {{{1
+libOverload_a_SOURCES = ./shared/String/stricmp.c
+libOverload_a_CFLAGS  = -fPIC -D_PARALLEL_   -D_C_ $(COPTFLAGS)
+#}}}
+
+#Executable {{{1
+if NOPARALLEL
+bin_PROGRAMS = 
+else 
+bin_PROGRAMS = issm.exe
+endif
+
+#Standard libraries
+LDADD =      ./libpISSM.a ./libOverload.a
+
+#External packages
+LDADD += $(PETSCLIB) $(TAOLIB) $(FLIBS) $(PLAPACKLIB)  $(MUMPSLIB) $(SCALAPACKLIB)  $(BLACSLIB) $(HYPRELIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB)  $(MKLLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(ADIC2LIB) 
+
+issm_exe_SOURCES = solutions/issm.cpp
+issm_exe_CXXFLAGS= -fPIC -D_PARALLEL_  $(CXXOPTFLAGS) $(COPTFLAGS) 
+#}}}
Index: /issm/trunk-jpl-damage/src/c/include/globals.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/include/globals.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/include/globals.h	(revision 11330)
@@ -0,0 +1,11 @@
+/*!\file global.h:
+ * \brief: these are the global variables always needed. 
+ */
+
+#ifndef GLOBALS_H_
+#define GLOBALS_H_
+
+int my_rank;
+int num_procs;
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/include/include.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/include/include.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/include/include.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file: include.h
+ * \brief prototypes for include.h
+ */ 
+
+#ifndef _INCLUDEGLOBAL_H_
+#define  _INCLUDEGLOBAL_H_
+
+#include "./macros.h"
+#include "./typedefs.h"
+#include "./types.h"
+
+
+#endif //ifndef _INCLUDE_H_
+
Index: /issm/trunk-jpl-damage/src/c/include/macros.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/include/macros.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/include/macros.h	(revision 11330)
@@ -0,0 +1,78 @@
+/* \file macros.h
+ * \brief: global macros used in the whole code
+ */
+
+/*Header {{{1*/
+#ifndef _MACROS_H_
+#define _MACROS_H_
+
+#include "./typedefs.h"
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+/*}}}*/
+
+/* _printf_ {{{1*/
+/*Printing macro: only cpu number 0 */
+#define _printf_(flag,...) do { if(flag) PrintfFunction(__VA_ARGS__); }while (0)
+/*}}}*/
+/* _error_ {{{1*/
+/*Error exception macro*/
+#ifdef _INTEL_WIN_
+#define _error_(...)\
+  throw ErrorException(exprintf(__VA_ARGS__))
+#else
+#define _error_(...)\
+  throw ErrorException(__FILE__,__func__,__LINE__,exprintf(__VA_ARGS__))
+#endif
+/*}}}*/
+/* _assert_ {{{1*/
+/*Assertion macro: do nothing if macro _ISSM_DEBUG_ undefined*/
+#ifdef _ISSM_DEBUG_ 
+#define _assert_(statement)\
+  if (!(statement)) _error_("Assertion \"%s\" failed, please report bug to ISSM developers",#statement)
+#else
+#define _assert_(ignore)\
+  ((void) 0)
+#endif
+/*}}}*/
+/* MODULEBOOT/MODULEEND {{{1*/
+/*The following macros hide the error exception handling in a matlab module. Just put 
+ * MODULEBOOT(); and MODULEEND(); at the beginning and end of a module, and c++ exceptions 
+ * will be trapped. Really nifty!*/
+#ifdef _SERIAL_
+
+#define MODULEBOOT(); ModuleBoot(); \
+	try{
+
+#define MODULEEND(); ModuleEnd(); }\
+	catch(ErrorException &exception){\
+		exception.Report(); \
+		mexErrMsgTxt(""); \
+	}\
+	catch (exception& e) {\
+		_printf_(true,"Standard exception: %s\n",e.what());\
+		mexErrMsgTxt(" ");\
+	}
+
+#else 
+
+#define MODULEBOOT(); \
+	try{
+
+#define MODULEEND(); }\
+	catch(ErrorException &exception){\
+		exception.Report(); \
+		return 1;\
+	}\
+	catch (exception& e) {\
+		_printf_(true,"Standard exception: %s\n",e.what());\
+		return 1;\
+	}
+#endif
+/*}}}*/
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/include/typedefs.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/include/typedefs.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/include/typedefs.h	(revision 11330)
@@ -0,0 +1,32 @@
+/*!\file: typedefs.h
+ * \brief prototypes for typedefs.h
+ */ 
+
+#ifndef _ISSMTYPEDEFS_H_
+#define  _ISSMTYPEDEFS_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_
+#define NAN 0.0/0.0
+#define INFINITY 1.0/0.0
+#endif
+
+
+
+
+#endif //ifndef _ISSMTYPEDEFS_H_
Index: /issm/trunk-jpl-damage/src/c/include/types.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/include/types.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/include/types.h	(revision 11330)
@@ -0,0 +1,41 @@
+/*!\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>
+
+/*Define abstract type for I/O: */
+#ifdef _SERIAL_
+#include <mex.h>
+typedef const mxArray* ConstDataHandle;  //serially, we are reading data from a matlab array.
+typedef mxArray* DataHandle;  
+#else 
+typedef FILE* ConstDataHandle; //in parallel, we are reading data from a file.
+typedef FILE* DataHandle; 
+#endif
+enum param_type { STRING, INTEGER, STRINGARRAY, DOUBLE, DOUBLEVEC, DOUBLEMAT, PETSCVEC, PETSCMAT };
+
+/*here are our abstracted types: inspired on petsc */
+#if ISSM_USE_64BIT_INDICES == 1
+typedef long long IssmInt;
+//#define MPIU_INT MPI_LONG_LONG_INT already define in petsc
+#else
+typedef int IssmInt;
+//#define MPIU_INT MPI_INT already defined in petsc
+#endif  
+
+typedef double IssmDouble;
+typedef bool IssmBool;
+
+
+#endif //ifndef _TYPES_H_
Index: /issm/trunk-jpl-damage/src/c/intel-compile.sh
===================================================================
--- /issm/trunk-jpl-damage/src/c/intel-compile.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/intel-compile.sh	(revision 11330)
@@ -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
+ar cru libISSM.a *.obj
Index: /issm/trunk-jpl-damage/src/c/io/Disk/diskio.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/io/Disk/diskio.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/io/Disk/diskio.h	(revision 11330)
@@ -0,0 +1,18 @@
+/*\file diskio.h
+ *\brief: I/O for ISSM from disk
+ */
+
+#ifndef _DISK_IO_H_
+#define _DISK_IO_H_
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+class DataSet;
+class Parameters;
+
+FILE* pfopen(char* filename,const char* format);
+void  pfclose(FILE* fid,char* filename);
+
+#endif	/* _IO_H_ */
Index: /issm/trunk-jpl-damage/src/c/io/Disk/pfclose.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/io/Disk/pfclose.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/io/Disk/pfclose.cpp	(revision 11330)
@@ -0,0 +1,21 @@
+/*!\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/shared.h"
+#include "../../include/include.h"
+
+void pfclose(FILE* fid,char* filename){
+
+	/*Close file handle: */
+	extern int my_rank;
+	_assert_(fid);
+	if(fclose(fid)!=0)_error_("%s%s","could not close file ",filename);
+}
Index: /issm/trunk-jpl-damage/src/c/io/Disk/pfopen.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/io/Disk/pfopen.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/io/Disk/pfopen.cpp	(revision 11330)
@@ -0,0 +1,26 @@
+/*!\file:  pfopen.cpp
+ * \brief fopen wrapper for parallel solution
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+
+FILE* pfopen(char* filename,const char* format){
+
+	FILE* fid=NULL;
+	extern int my_rank;
+	
+	/*Open handle to data on disk: */
+	fid=fopen(filename,format);
+	if(fid==NULL) _error_("%s%s%s","could not open file ",filename," for binary reading or writing"); 
+
+	return fid;
+}
+
Index: /issm/trunk-jpl-damage/src/c/io/Matlab/FetchMatlabData.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/io/Matlab/FetchMatlabData.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/io/Matlab/FetchMatlabData.cpp	(revision 11330)
@@ -0,0 +1,736 @@
+/*\file FetchMatlabData.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 "../../shared/shared.h"
+#include "../../include/include.h"
+
+#ifdef _SERIAL_
+#include <mex.h>
+/*FUNCTION FetchMatlabData(DataSet** pdataset,const mxArray* dataref){{{1*/
+void FetchMatlabData(DataSet** pdataset,const mxArray* dataref){
+
+	/*output*/
+	DataSet* outdataset=NULL;
+	char*    outdataset_buffer=NULL;
+	int      outdataset_size;
+
+	/*First, check that our reference is a double, otherwise, error out: */
+	if (mxIsClass(dataref,"double")){
+			
+		/*We need to copy the data pointed by dataref, so that our dataset is not actually a pointer!:*/
+		if (!mxIsEmpty(dataref)){
+			outdataset_buffer=(char*)mxGetPr(dataref);
+			outdataset_size=mxGetM(dataref)*mxGetN(dataref);
+			if(outdataset_size)outdataset=DataSetDemarshall(outdataset_buffer);
+		}
+	}
+	else{
+		if (mxIsEmpty(dataref)){
+			/*Nothing to pick up. Just initialize pointer to NULL, and warn the server we are not uploading anything: */
+			outdataset_size=0;
+			outdataset=NULL;
+		}
+		else{
+			/*This is an error: we don't have the correct input!: */
+			_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+		}
+	}
+
+	/*Assign output pointers:*/
+	*pdataset=outdataset;
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(double** pmatrix,int* pM,int *pN,const mxArray* dataref){{{1*/
+void FetchMatlabData(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") ){
+
+		/*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(&outmatrix,&outmatrix_rows,&outmatrix_cols,dataref);
+		}
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+	}
+			
+	/*Assign output pointers:*/
+	*pmatrix=outmatrix;
+	if (pM)*pM=outmatrix_rows;
+	if (pN)*pN=outmatrix_cols;
+
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(double** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){{{1*/
+void FetchMatlabData(double** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){
+
+	double*  outmatrix=NULL;
+	int      outmatrix_numel,outmatrix_ndims;
+	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") ){
+
+		/*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(&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 %s not supported yet",mxGetClassName(dataref));
+	}
+			
+	/*Assign output pointers:*/
+	*pmatrix=outmatrix;
+	if (pnumel)*pnumel=outmatrix_numel;
+	if (pndims)*pndims=outmatrix_ndims;
+	if (psize )*psize =outmatrix_size;
+	else xfree((void**)&outmatrix_size);
+
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(int** pmatrix,int* pM,int *pN,const mxArray* dataref){{{1*/
+void FetchMatlabData(int** pmatrix,int* pM,int *pN,const mxArray* dataref){
+
+	int     i,outmatrix_rows,outmatrix_cols;
+	double *doublematrix=NULL;
+	int    *outmatrix=NULL;
+
+	if(mxIsEmpty(dataref) ){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		outmatrix_rows=0;
+		outmatrix_cols=0;
+		outmatrix=NULL;
+	}
+	else if (mxIsClass(dataref,"double") ){
+
+		/*Check dataref is not pointing to NaN: */
+		if ( mxIsNaN(*(mxGetPr(dataref))) && (mxGetM(dataref)==1) && (mxGetN(dataref)==1) ){
+			outmatrix_rows=0;
+			outmatrix_cols=0;
+			outmatrix=NULL;
+		}
+		else{
+
+			/*Convert matlab matrix to double* matrix: */
+			MatlabMatrixToDoubleMatrix(&doublematrix,&outmatrix_rows,&outmatrix_cols,dataref);
+
+			/*Convert double matrix into integer matrix: */
+			outmatrix=(int*)xmalloc(outmatrix_rows*outmatrix_cols*sizeof(int));
+			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 %s not supported yet",mxGetClassName(dataref));
+	}
+
+	/*Assign output pointers:*/
+	*pmatrix=outmatrix;
+	if (pM)*pM=outmatrix_rows;
+	if (pN)*pN=outmatrix_cols;
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(bool** pmatrix,int* pM,int *pN,const mxArray* dataref){{{1*/
+void FetchMatlabData(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=(bool*)xmalloc(outmatrix_rows*outmatrix_cols*sizeof(bool));
+			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 %s not supported yet",mxGetClassName(dataref));
+	}
+
+	/*Assign output pointers:*/
+	*pmatrix=outmatrix;
+	if (pM)*pM=outmatrix_rows;
+	if (pN)*pN=outmatrix_cols;
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(bool** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){{{1*/
+void FetchMatlabData(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=(bool*)xmalloc(outmatrix_numel*sizeof(bool));
+			for(i=0;i<outmatrix_numel;i++)outmatrix[i]=(bool)doublematrix[i];
+			xfree((void**)&doublematrix);
+		}
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+	}
+			
+	/*Assign output pointers:*/
+	*pmatrix=outmatrix;
+	if (pnumel)*pnumel=outmatrix_numel;
+	if (pndims)*pndims=outmatrix_ndims;
+	if (psize )*psize =outmatrix_size;
+	else xfree((void**)&outmatrix_size);
+
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(Mat* pmatrix,const mxArray* dataref){{{1*/
+void FetchMatlabData(Mat* pmatrix,const mxArray* dataref){
+	
+	Mat outmatrix=NULL;
+	int dummy=0;
+
+	if (mxIsClass(dataref,"double") ){
+
+		/*Check dataref is not pointing to NaN: */
+		if ( mxIsNaN(*(mxGetPr(dataref))) && (mxGetM(dataref)==1) && (mxGetN(dataref)==1) ){
+			outmatrix=NULL;
+		}
+		else{
+
+			/*Convert matlab matrix to petsc matrix: */
+			MatlabMatrixToPetscMatrix(&outmatrix,&dummy,&dummy,dataref);
+		}
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+	}
+
+	/*Assign output pointers:*/
+	*pmatrix=outmatrix;
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(double** pvector,int* pM,const mxArray* dataref){{{1*/
+void FetchMatlabData(double** pvector,int* pM,const mxArray* dataref){
+
+	double* outvector=NULL;
+	int outvector_rows;
+
+	if(mxIsEmpty(dataref)){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		outvector_rows=0;
+		outvector=NULL;
+	}
+	else if (mxIsClass(dataref,"double") ){
+
+		/*Convert matlab vector to double*  vector: */
+		MatlabVectorToDoubleVector(&outvector,&outvector_rows,dataref);
+
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+	}
+
+	/*Assign output pointers:*/
+	*pvector=outvector;
+	if (pM)*pM=outvector_rows;
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(int** pvector,int* pM,const mxArray* dataref){{{1*/
+void FetchMatlabData(int** pvector,int* pM,const mxArray* dataref){
+
+	int    i;
+	double *doublevector   = NULL;
+	int    *outvector      = NULL;
+	int     outvector_rows;
+
+	if(mxIsEmpty(dataref)){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		outvector_rows=0;
+		outvector=NULL;
+	}
+	else if (mxIsClass(dataref,"double") ){
+
+		/*Convert matlab vector to double*  vector: */
+		MatlabVectorToDoubleVector(&doublevector,&outvector_rows,dataref);
+
+		/*Convert double vector into integer vector: */
+		outvector=(int*)xmalloc(outvector_rows*sizeof(int));
+		for(i=0;i<outvector_rows;i++)outvector[i]=(int)doublevector[i];
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+	}
+
+	/*Assign output pointers:*/
+	*pvector=outvector;
+	if (pM)*pM=outvector_rows;
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(bool** pvector,int* pM,const mxArray* dataref){{{1*/
+void FetchMatlabData(bool** pvector,int* pM,const mxArray* dataref){
+
+	int    i;
+	double *doublevector   = NULL;
+	bool   *outvector      = NULL;
+	int     outvector_rows;
+
+	if(mxIsEmpty(dataref)){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		outvector_rows=0;
+		outvector=NULL;
+	}
+	else if (mxIsClass(dataref,"double") ){
+
+		/*Convert matlab vector to double*  vector: */
+		MatlabVectorToDoubleVector(&doublevector,&outvector_rows,dataref);
+
+		/*Convert double vector into integer vector: */
+		outvector=(bool*)xmalloc(outvector_rows*sizeof(bool));
+		for(i=0;i<outvector_rows;i++)outvector[i]=(bool)doublevector[i];
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+	}
+
+	/*Assign output pointers:*/
+	*pvector=outvector;
+	if (pM)*pM=outvector_rows;
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(float** pvector,int* pM,const mxArray* dataref){{{1*/
+void FetchMatlabData(float** pvector,int* pM,const mxArray* dataref){
+
+	int    i;
+	double *doublevector   = NULL;
+	float  *outvector      = NULL;
+	int     outvector_rows;
+
+	if(mxIsEmpty(dataref)){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		outvector_rows=0;
+		outvector=NULL;
+	}
+	else if (mxIsClass(dataref,"double") ){
+
+		/*Convert matlab vector to double*  vector: */
+		MatlabVectorToDoubleVector(&doublevector,&outvector_rows,dataref);
+
+		/*Convert double vector into float vector: */
+		outvector=(float*)xmalloc(outvector_rows*sizeof(float));
+		for(i=0;i<outvector_rows;i++)outvector[i]=(float)doublevector[i];
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+	}
+
+	/*Assign output pointers:*/
+	*pvector=outvector;
+	if (pM)*pM=outvector_rows;
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(Vec* pvector,const mxArray* dataref){{{1*/
+void FetchMatlabData(Vec* pvector,const mxArray* dataref){
+
+	Vec vector=NULL;
+	int dummy;
+
+	if(mxIsEmpty(dataref)){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		vector=NULL;
+	}
+	else if (mxIsClass(dataref,"double") ){
+
+		/*Convert matlab vector to petsc vector: */
+		MatlabVectorToPetscVector(&vector,&dummy,dataref);
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+	}
+
+	/*Assign output pointers:*/
+	*pvector=vector;
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(char** pstring,const mxArray* dataref){{{1*/
+void FetchMatlabData(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 = (char*)xmalloc(sizeof(mxChar)*stringlen);
+		mxGetString(dataref,outstring,stringlen);
+	}
+
+	/*Assign output pointers:*/
+	*pstring=outstring;
+}
+/*FUNCTION FetchMatlabData(char** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){{{1*/
+void FetchMatlabData(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") ){
+
+		/*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 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 %s not supported yet",mxGetClassName(dataref));
+	}
+			
+	/*Assign output pointers:*/
+	*pmatrix=outmatrix;
+	if (pnumel)*pnumel=outmatrix_numel;
+	if (pndims)*pndims=outmatrix_ndims;
+	if (psize )*psize =outmatrix_size;
+	else xfree((void**)&outmatrix_size);
+
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(double* pscalar,const mxArray* dataref){{{1*/
+void FetchMatlabData(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 FetchMatlabData(int* pinteger,const mxArray* dataref){{{1*/
+void FetchMatlabData(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 FetchMatlabData(bool* pboolean,const mxArray* dataref){{{1*/
+void FetchMatlabData(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;
+}
+/*}}}*/
+/*FUNCTION FetchMatlabData(Parameters** pparameters, DataHandle dataref){{{1*/
+void FetchMatlabData(Parameters** pparameters, DataHandle dataref){
+
+	int i,j;
+	int count;
+
+	/*output: */
+	Param* param=NULL;
+	Parameters* parameters=NULL;
+
+	/*intermediary: */
+	int M,N;
+	double* tmatrix=NULL;
+	double* matrix=NULL;
+	char**  stringarray=NULL;
+	double** array=NULL;
+	int*     mdims_array=NULL;
+	int*     ndims_array=NULL;
+	int nfields;
+	char* name=NULL;
+	mxArray* pfield=NULL;
+	mxArray* pfield2=NULL;
+	int enum_type;
+
+
+	/*First, create parameters : */
+	parameters=new Parameters();
+
+	/*go through matlab params structure, and create Param object for each field: */
+
+	nfields=mxGetNumberOfFields(dataref);
+
+	for(count=0;count<nfields;count++){
+
+		/*Get i'th field: */
+		name=(char*)mxGetFieldNameByNumber(dataref,count);
+		enum_type=StringToEnumx(name);
+		pfield=mxGetFieldByNumber(dataref,0,count);
+		_assert_(pfield);
+		
+		/*Check type of field: */
+		if (mxIsClass(pfield,"double")){
+			
+			/*could be  DOUBLE, DOUBLEVEC or DOUBLEMAT, depends on dimensions: */
+			M=mxGetM(pfield);
+			N=mxGetN(pfield);
+
+			if (M==0 | N==0){
+				_error_("%s%i (%s) %s%i%s%i%s","array in parameters structure field ",count,name," is of size (",M,",",N,")");
+			}
+			if (M==1 && N==1){
+				/*we have a simple scalar: */
+				param= new DoubleParam(enum_type,*mxGetPr(pfield));
+				parameters->AddObject(param);
+
+			}
+			else{
+				if (N==1){
+					
+					/*vector: */
+					param= new DoubleVecParam(enum_type,mxGetPr(pfield),M);
+					parameters->AddObject(param);
+
+				}
+				else{
+					/*matrix: first, transpose, then plug into Param */
+					matrix=mxGetPr(pfield);
+					tmatrix=(double*)xmalloc(M*N*sizeof(double));
+					for (i=0;i<M;i++){
+						for(j=0;j<N;j++){
+							*(tmatrix+N*i+j)=*(matrix+M*j+i);
+						}
+					}
+
+					param= new DoubleMatParam(enum_type,tmatrix,M,N);
+					parameters->AddObject(param);
+	
+					/*Free ressources:*/
+					xfree((void**)&tmatrix);
+				}
+			}
+
+		}
+		else if (mxIsClass(pfield,"char")){
+			/* we have a string parameter:*/
+			
+			int stringlen;
+			char* string=NULL;
+			
+			stringlen = mxGetM(pfield)*mxGetN(pfield)+1;
+			string = (char*)xmalloc(sizeof(mxChar)*stringlen);
+			mxGetString(pfield,string,stringlen);
+
+			param= new StringParam(enum_type,string);
+			parameters->AddObject(param);
+
+			xfree((void**)&string);
+		}
+		else if (mxIsClass(pfield,"cell")){
+
+			/*This can be a string array, or a matrix array. Check the first 
+			 *element type to decide: */
+			pfield2=mxGetCell(pfield,0);
+			if (mxIsClass(pfield2,"char")){
+				
+				/*string array: */
+				M=mxGetM(pfield);
+				stringarray=(char**)xmalloc(M*sizeof(char*));
+
+				for(i=0;i<M;i++){
+					char* descriptor=NULL;
+					pfield2=mxGetCell(pfield,i);
+					FetchMatlabData(&descriptor,pfield2);
+					stringarray[i]=descriptor;
+				}
+
+				param= new StringArrayParam(enum_type,stringarray,M);
+				parameters->AddObject(param);
+
+				/*Free ressources:*/
+				for(i=0;i<M;i++){
+					char* descriptor=stringarray[i];
+					xfree((void**)&descriptor);
+				}
+				xfree((void**)&stringarray);
+
+			}
+			else{
+				
+				/*matrix array: */
+				M=mxGetM(pfield);
+				array=(double**)xmalloc(M*sizeof(double*));
+				mdims_array=(int*)xmalloc(M*sizeof(int));
+				ndims_array=(int*)xmalloc(M*sizeof(int));
+
+				for(i=0;i<M;i++){
+					double* matrix=NULL;
+					int     m,n;
+					pfield2=mxGetCell(pfield,i);
+					FetchMatlabData(&matrix,&m,&n,pfield2);
+					array[i]=matrix;
+					mdims_array[i]=m;
+					ndims_array[i]=n;
+				}
+
+				param= new DoubleMatArrayParam(enum_type,array,M,mdims_array,ndims_array);
+				parameters->AddObject(param);
+
+				/*Free ressources:*/
+				for(i=0;i<M;i++){
+					double* matrix=array[i];
+					xfree((void**)&matrix);
+				}
+				xfree((void**)&array);
+				xfree((void**)&mdims_array);
+				xfree((void**)&ndims_array);
+			}
+		}
+		else _error_("%s%i","unknow type in parameters structure field ",i);
+	}
+
+	/*Assign output pointers:*/
+	*pparameters=parameters;
+
+}
+/*}}}*/
+#endif
Index: /issm/trunk-jpl-damage/src/c/io/Matlab/OptionParse.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/io/Matlab/OptionParse.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/io/Matlab/OptionParse.cpp	(revision 11330)
@@ -0,0 +1,194 @@
+/*\file OptionParse.c
+ *\brief: functions to parse the mex options.
+ */
+#ifdef HAVE_CONFIG_H
+    #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../include/include.h"
+#include "./matlabio.h"
+
+#ifdef _SERIAL_
+#include <mex.h>
+
+/*FUNCTION OptionDoubleParse {{{1*/
+OptionDouble* OptionDoubleParse( char* name, const mxArray* prhs[]){
+
+	OptionDouble *odouble = NULL;
+
+	/*check and parse the name  */
+	odouble=new OptionDouble;
+	odouble->name =(char *) xmalloc((strlen(name)+1)*sizeof(char));
+	memcpy(odouble->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"double")){
+		_error_("Value of option \"%s\" must be class \"%s\", not class \"%s\".",odouble->name,"double",odouble->name,mxGetClassName(prhs[0]));
+	}
+
+	FetchMatlabData(&odouble->values,&odouble->numel,&odouble->ndims,&odouble->size,prhs[0]);
+
+	return(odouble);
+}/*}}}*/
+/*FUNCTION OptionLogicalParse {{{1*/
+OptionLogical* OptionLogicalParse( char* name, const mxArray* prhs[]){
+
+	OptionLogical *ological = NULL;
+
+	/*check and parse the name  */
+	ological=new OptionLogical;
+	ological->name =(char *) xmalloc((strlen(name)+1)*sizeof(char));
+	memcpy(ological->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"logical")){
+		_error_("Value of option \"%s\" must be class \"%s\", not class \"%s\".",ological->name,"logical",ological->name,mxGetClassName(prhs[0]));
+	}
+
+	FetchMatlabData(&ological->values,&ological->numel,&ological->ndims,&ological->size,prhs[0]);
+
+	return(ological);
+}/*}}}*/
+/*FUNCTION OptionCharParse {{{1*/
+OptionChar* OptionCharParse( char* name, const mxArray* prhs[]){
+
+	OptionChar  *ochar = NULL;
+
+	/*check and parse the name  */
+	ochar=new OptionChar;
+	ochar->name =(char *) xmalloc((strlen(name)+1)*sizeof(char));
+	memcpy(ochar->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"char")){
+		_error_("Value of option \"%s\" must be class \"%s\", not class \"%s\".",ochar->name,"char",ochar->name,mxGetClassName(prhs[0]));
+	}
+
+	FetchMatlabData(&ochar->values,&ochar->numel,&ochar->ndims,&ochar->size,prhs[0]);
+
+	return(ochar);
+}/*}}}*/
+/*FUNCTION OptionStructParse {{{1*/
+OptionStruct* OptionStructParse( char* name, const mxArray* prhs[]){
+
+	int            i;
+	char           namei[161];
+	OptionStruct  *ostruct    = NULL;
+	Option        *option     = NULL;
+	const mwSize  *ipt        = NULL;
+	const mxArray *structi;
+	mwIndex        sindex;
+
+	/*check and parse the name  */
+	ostruct=new OptionStruct;
+	ostruct->name =(char*)xmalloc((strlen(name)+1)*sizeof(char));
+	memcpy(ostruct->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"struct")){
+		_error_("Value of option \"%s\" must be class \"%s\", not class \"%s\".",ostruct->name,"struct",ostruct->name,mxGetClassName(prhs[0]));
+	}
+
+	ostruct->numel=mxGetNumberOfElements(prhs[0]);
+	ostruct->ndims=mxGetNumberOfDimensions(prhs[0]);
+	ipt           =mxGetDimensions(prhs[0]);
+	ostruct->size =(int *) xmalloc(ostruct->ndims*sizeof(int));
+	for (i=0; i<ostruct->ndims; i++) ostruct->size[i]=(int)ipt[i];
+	if (ostruct->numel) ostruct->values=(Options**) xmalloc(ostruct->numel*sizeof(Options *));
+
+	/*loop through and process each element of the struct array  */
+	for (sindex=0; sindex<ostruct->numel; sindex++) {
+		ostruct->values[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->values[sindex]->AddObject((Object*)option);
+			option=NULL;
+		}
+	}
+
+	return(ostruct);
+}/*}}}*/
+/*FUNCTION OptionCellParse {{{1*/
+OptionCell* OptionCellParse( char* name, const mxArray* prhs[]){
+
+	int            i;
+	int           *dims;
+	char           namei[161];
+	char           cstr[81];
+	OptionCell    *ocell      = NULL;
+	Option        *option     = NULL;
+	const mwSize  *ipt        = NULL;
+	const mxArray *celli;
+	mwIndex        cindex;
+
+	/*check and parse the name  */
+	ocell=new OptionCell;
+	ocell->name =(char *) xmalloc((strlen(name)+1)*sizeof(char));
+	memcpy(ocell->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"cell")){
+		_error_("Value of option \"%s\" must be class \"%s\", not class \"%s\".",ocell->name,"cell",ocell->name,mxGetClassName(prhs[0]));
+	}
+
+	ocell->numel=mxGetNumberOfElements(prhs[0]);
+	ocell->ndims=mxGetNumberOfDimensions(prhs[0]);
+	ipt         =mxGetDimensions(prhs[0]);
+	ocell->size =(int *) xmalloc(ocell->ndims*sizeof(int));
+	for (i=0; i<ocell->ndims; i++) ocell->size[i]=(int)ipt[i];
+	ocell->values=new Options;
+
+	/*loop through and process each element of the cell array  */
+	dims=(int *) xmalloc(ocell->ndims*sizeof(int));
+	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->values->AddObject((Object*)option);
+		option=NULL;
+	}
+	xfree((void**)&dims);
+
+	return(ocell);
+}/*}}}*/
+/*FUNCTION OptionParse{{{1*/
+Option* OptionParse(char* name, const mxArray* prhs[]){
+
+	Option *option = NULL;
+	mxArray       *lhs[1];
+
+	/*parse the value according to the matlab data type  */
+	if     (mxIsClass(prhs[0],"double"))  option=(Option*)OptionDoubleParse(name,prhs);
+	else if(mxIsClass(prhs[0],"logical")) option=(Option*)OptionLogicalParse(name,prhs);
+	else if(mxIsClass(prhs[0],"char"))    option=(Option*)OptionCharParse(name,prhs);
+	else if(mxIsClass(prhs[0],"struct"))  option=(Option*)OptionStructParse(name,prhs);
+	else if(mxIsClass(prhs[0],"cell"))    option=(Option*)OptionCellParse(name,prhs);
+	else {
+		_printf_(true,"  Converting value of option \"%s\" from unrecognized class \"%s\" to class \"%s\".\n",name,mxGetClassName(prhs[0]),"struct");
+		if (!mexCallMATLAB(1,lhs,1,(mxArray**)prhs,"struct")) {
+			option=(Option*)OptionStructParse(name,(const mxArray**)lhs);
+			mxDestroyArray(lhs[0]);
+		}
+		else _error_("Second argument value of option \"%s\" is of unrecognized class \"%s\".",name,mxGetClassName(prhs[0]));
+	}
+
+	return(option);
+}/*}}}*/
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/io/Matlab/WriteMatlabData.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/io/Matlab/WriteMatlabData.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/io/Matlab/WriteMatlabData.cpp	(revision 11330)
@@ -0,0 +1,212 @@
+/* \file WriteMatlabData.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 "../../include/include.h"
+#include "../../shared/shared.h"
+
+#ifdef _SERIAL_
+#include <mex.h>
+
+/*FUNCTION WriteMatlabData(mxArray** pdataref,DataSet* dataset){{{1*/
+void WriteMatlabData(mxArray** pdataref,DataSet* dataset){
+
+	mxArray* dataref=NULL;
+	char* marshalled_dataset=NULL;
+	int   marshalled_dataset_size;
+
+	/*Write a dataset: */
+	if(dataset){
+			/* marshall the dataset: */
+			marshalled_dataset=dataset->Marshall();
+			marshalled_dataset_size=dataset->MarshallSize();
+			
+			dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+			mxSetM(dataref,(mwSize)(marshalled_dataset_size/sizeof(double)));
+			mxSetN(dataref,(mwSize)1);
+			mxSetPr(dataref,(double*)marshalled_dataset);	
+	}
+	else{
+		/* return empty matrix: */
+		dataref=mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+	*pdataref=dataref;
+	
+}
+/*}}}*/
+/*FUNCTION WriteMatlabData(mxArray** pdataref,Mat matrix){{{1*/
+void WriteMatlabData(mxArray** pdataref,Mat matrix){
+		
+	mxArray* dataref=NULL;
+	
+	if(matrix){
+		
+		/*call toolkit routine: */
+		PetscMatrixToMatlabMatrix(&dataref,matrix);
+	}
+	else{
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteMatlabData(mxArray** pdataref,double* matrix, int M,int N){{{1*/
+void WriteMatlabData(mxArray** pdataref,double* matrix, int M,int N){
+	
+	mxArray* dataref=NULL;
+	mxArray* tdataref=NULL;
+		
+	if(matrix){
+		
+		/*data is a double* pointer. Copy into a matrix: */
+		tdataref = mxCreateDoubleMatrix(0,0,mxREAL);
+		mxSetM(tdataref,(mwSize)N);
+		mxSetN(tdataref,(mwSize)M);
+		mxSetPr(tdataref,(double*)matrix);
+
+		//transpose
+		mexCallMATLAB(1,&dataref,1,&tdataref, "transpose");
+	}
+	else{
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteMatlabData(mxArray** pdataref,int* matrix, int M,int N){{{1*/
+void WriteMatlabData(mxArray** pdataref,int* matrix, int M,int N){
+
+	mxArray* dataref=NULL;
+	mxArray* tdataref=NULL;
+
+	if(matrix){
+
+		/*convert to double matrix*/
+		double* doublematrix=(double*)xmalloc(M*N*sizeof(double));
+		for(int i=0;i<M*N;i++) doublematrix[i]=(double)matrix[i];
+
+		/*data is a double* pointer. Copy into a matrix: */
+		tdataref = mxCreateDoubleMatrix(0,0,mxREAL);
+		mxSetM(tdataref,(mwSize)N);
+		mxSetN(tdataref,(mwSize)M);
+		mxSetPr(tdataref,(double*)doublematrix);
+
+		//transpose
+		mexCallMATLAB(1,&dataref,1,&tdataref, "transpose");
+	}
+	else{
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteMatlabData(mxArray** pdataref,Vec vector){{{1*/
+void WriteMatlabData(mxArray** pdataref,Vec vector){
+	
+	mxArray* dataref=NULL;
+	
+	if(vector){
+		
+		/*call toolkit routine: */
+		PetscVectorToMatlabVector(&dataref,vector);
+	}
+	else{
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+	*pdataref=dataref;
+
+}
+/*}}}*/
+/*FUNCTION WriteMatlabData(mxArray** pdataref,double* vector, int M){{{1*/
+void WriteMatlabData(mxArray** pdataref,double* vector, int M){
+	
+	mxArray* dataref=NULL;
+
+	if(vector){
+
+		/*data is a double* pointer. Copy into a vector: */
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+		mxSetM(dataref,(mwSize)M);
+		mxSetN(dataref,(mwSize)1);
+		mxSetPr(dataref,vector);
+	}
+	else{
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteMatlabData(mxArray** pdataref,double scalar){{{1*/
+void WriteMatlabData(mxArray** pdataref,double scalar){
+
+	*pdataref=mxCreateDoubleScalar(scalar);
+}
+/*}}}*/
+/*FUNCTION WriteMatlabData(mxArray** pdataref,int integer){{{1*/
+void WriteMatlabData(mxArray** pdataref,int integer){
+
+		*pdataref=mxCreateDoubleScalar((double)integer);
+
+}
+/*}}}*/
+/*FUNCTION WriteMatlabData(mxArray** pdataref,int boolean){{{1*/
+void WriteMatlabData(mxArray** pdataref,bool boolean){
+
+	*pdataref=mxCreateDoubleScalar((double)boolean);
+
+}
+/*}}}*/
+/*FUNCTION WriteMatlabData(mxArray** pdataref,char* string){{{1*/
+void WriteMatlabData(mxArray** pdataref,char* string){
+
+		*pdataref=mxCreateString(string);
+}
+/*}}}*/
+/*FUNCTION WriteMatlabData(mxArray** pdataref,Parameters* parameters){{{1*/
+void WriteMatlabData(mxArray** pdataref,Parameters* parameters){
+
+	int i;
+
+	/*output: */
+	mxArray  *dataref     = NULL;
+	mwSize    nfields;
+	char    **fnames      = NULL;
+	mwSize    onebyone[2] = {1,1};
+	mwSize    ndim        = 2;
+
+	/*intermediary: */
+	Param*      param=NULL;
+
+	/*Recover data from the parameters dataset: */
+	nfields=(mwSize)parameters->Size();
+	fnames=(char**)xmalloc(nfields*sizeof(char*));
+	
+	/*Build structure in matlab workspace with all the parameter fields: */
+	for(i=0;i<nfields;i++){
+		param=(Param*)parameters->GetObjectByOffset(i);
+		param->GetParameterName(&fnames[i]);
+	}
+	/*Initialize structure: */
+	dataref=mxCreateStructArray( ndim,onebyone,nfields,(const char**)fnames);
+
+	/*Fill each field: */
+	for(i=0;i<nfields;i++){
+
+		param=(Param*)parameters->GetObjectByOffset(i);
+		param->SetMatlabField(dataref);
+	}
+		
+	/*Assign output pointers:*/
+	*pdataref=dataref;
+
+}
+/*}}}*/
+#endif
Index: /issm/trunk-jpl-damage/src/c/io/Matlab/matlabio.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/io/Matlab/matlabio.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/io/Matlab/matlabio.h	(revision 11330)
@@ -0,0 +1,55 @@
+/*\file matlabio.h
+ *\brief: I/O for ISSM in matlab mode
+ */
+
+#ifndef _MATLAB_IO_H_
+#define _MATLAB_IO_H_
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+class DataSet;
+class Parameters;
+
+#ifdef _SERIAL_
+#include <mex.h>
+void WriteMatlabData(mxArray** pdataref,DataSet* dataset);
+void WriteMatlabData(mxArray** pdataref,Mat matrix);
+void WriteMatlabData(mxArray** pdataref,double* matrix, int M,int N);
+void WriteMatlabData(mxArray** pdataref,int*    matrix, int M,int N);
+void WriteMatlabData(mxArray** pdataref,Vec vector);
+void WriteMatlabData(mxArray** pdataref,double* vector, int M);
+void WriteMatlabData(mxArray** pdataref,int integer);
+void WriteMatlabData(mxArray** pdataref,bool boolean);
+void WriteMatlabData(mxArray** pdataref,double scalar);
+void WriteMatlabData(mxArray** pdataref,char* string);
+void WriteMatlabData(DataHandle* pdataref,Parameters* parameters);
+
+void FetchMatlabData(DataSet** pdataset,const mxArray* dataref);
+void FetchMatlabData(double** pmatrix,int* pM,int *pN,const mxArray* dataref);
+void FetchMatlabData(double** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref);
+void FetchMatlabData(int** pmatrix,int* pM,int *pN,const mxArray* dataref);
+void FetchMatlabData(bool** pmatrix,int* pM,int *pN,const mxArray* dataref);
+void FetchMatlabData(bool** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref);
+void FetchMatlabData(Mat* pmatrix,const mxArray* dataref);
+void FetchMatlabData(int** pvector,int* pM,const mxArray* dataref);
+void FetchMatlabData(float** pvector,int* pM,const mxArray* dataref);
+void FetchMatlabData(double** pvector,int* pM,const mxArray* dataref);
+void FetchMatlabData(bool** pvector,int* pM,const mxArray* dataref);
+void FetchMatlabData(Vec* pvector,const mxArray* dataref);
+void FetchMatlabData(char** pstring,const mxArray* dataref);
+void FetchMatlabData(char** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref);
+void FetchMatlabData(double* pscalar,const mxArray* dataref);
+void FetchMatlabData(int* pinteger,const mxArray* dataref);
+void FetchMatlabData(bool* pbool,const mxArray* dataref);
+void FetchMatlabData(Parameters** pparameters, DataHandle dataref);
+
+Option* OptionParse(char* name, const mxArray* prhs[]);
+OptionDouble*   OptionDoubleParse( char* name, const mxArray* prhs[]);
+OptionLogical*  OptionLogicalParse( char* name, const mxArray* prhs[]);
+OptionChar*     OptionCharParse( char* name, const mxArray* prhs[]);
+OptionStruct*   OptionStructParse( char* name, const mxArray* prhs[]);
+OptionCell*     OptionCellParse( char* name, const mxArray* prhs[]);
+#endif
+#endif	/* _IO_H_ */
Index: /issm/trunk-jpl-damage/src/c/io/PrintfFunction.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/io/PrintfFunction.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/io/PrintfFunction.cpp	(revision 11330)
@@ -0,0 +1,64 @@
+/*\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. 
+ */
+
+#include <stdarg.h>
+#include <stdio.h>
+#include "../shared/shared.h"
+#include "../include/include.h"
+
+#ifdef _SERIAL_
+#include "mex.h"
+#endif
+
+int PrintfFunction(const char* format,...){
+	/*http://linux.die.net/man/3/vsnprintf*/
+
+	/*string to be printed: */
+	char *buffer = NULL;
+	int   n,size = 100;
+	int         string_size;
+	extern int  my_rank;
+	extern int  num_procs;
+                                                                                                                                                                                                     
+	//variable list of arguments
+	va_list args;
+
+	while(true){
+
+		/*allocate buffer for given string size*/
+		buffer=(char*)xmalloc(size*sizeof(char));
+
+		/* Try to print in the allocated space. */
+		va_start(args, format);
+#ifndef WIN32
+		n=vsnprintf(buffer,size,format,args);
+#else
+		n=vsnprintf(buffer,size,format,args);
+#endif
+		va_end(args);
+
+		/* If that worked, return the string. */
+		if(n>-1 && n<size) break;
+
+		/* Else try again with more space. */
+		if(n>-1)   /* glibc 2.1 */
+		 size=n+1; /* precisely what is needed */
+		else       /* glibc 2.0 */
+		 size*=2;  /* twice the old size */
+
+		xfree((void**)&buffer);
+	}
+
+	/*Ok, if we are running in parallel, get node 0 to print*/
+#if defined(_PARALLEL_)
+	if(my_rank==0)printf(buffer);
+#else
+	mexPrintf(buffer);
+#endif
+
+	/*Clean up and return*/
+	xfree((void**)&buffer);
+	return 1;
+}
Index: /issm/trunk-jpl-damage/src/c/io/io.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/io/io.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/io/io.h	(revision 11330)
@@ -0,0 +1,24 @@
+/*\file io.h
+ *\brief: I/O for ISSM
+ */
+
+#ifndef _IO_H_
+#define _IO_H_
+
+#ifdef HAVE_CONFIG_H //config.h {{{1
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif 
+//}}}
+
+#include "./Disk/diskio.h"
+
+#ifdef _SERIAL_
+#include "./Matlab/matlabio.h"
+#endif
+
+/*printf: */
+int PrintfFunction(const char* format,...);
+
+#endif	/* _IO_H_ */
Index: /issm/trunk-jpl-damage/src/c/issm.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/issm.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/issm.h	(revision 11330)
@@ -0,0 +1,25 @@
+/*!\file: issm.h
+ * \brief prototype wrapper for issm.h
+ */ 
+
+#ifndef _ISSM_H_
+#define  _ISSM_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./include/include.h"
+#include "./shared/shared.h"
+#include "./objects/objects.h"
+#include "./Container/Container.h"
+#include "./EnumDefinitions/EnumDefinitions.h"
+#include "./toolkits/toolkits.h"
+#include "./solutions/solutions.h"
+#include "./solvers/solvers.h"
+#include "./modules/modules.h"
+
+
+#endif //ifndef _ISSM_H_
Index: /issm/trunk-jpl-damage/src/c/modules/AddExternalResultx/AddExternalResultx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/AddExternalResultx/AddExternalResultx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/AddExternalResultx/AddExternalResultx.cpp	(revision 11330)
@@ -0,0 +1,18 @@
+/*!\file:  AddExternalResultx.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.
+ */ 
+
+#include "./AddExternalResultx.h"
+#include "../../Container/Container.h"
+#include "../../io/io.h"
+#include "../../objects/objects.h"
+		
+void AddExternalResultx( DataSet* results, int enumtype, double value){
+	/* Add new result in into results*/
+	results->AddObject(new DoubleExternalResult(results->Size()+1,enumtype,value,1,0));
+}
+void AddExternalResultx( DataSet* results, int enumtype, double* value, int nraws){
+	/* Add new result in into results*/
+	results->AddObject(new DoubleVecExternalResult(results->Size()+1,enumtype,value,nraws,1,0));
+}
Index: /issm/trunk-jpl-damage/src/c/modules/AddExternalResultx/AddExternalResultx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/AddExternalResultx/AddExternalResultx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/AddExternalResultx/AddExternalResultx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  AddExternalResultx.h
+ * \brief header file for outputing results
+ */ 
+
+#ifndef _ADDEXTERNALRESULTX_H
+#define _ADDEXTERNALRESULTX_H
+
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void AddExternalResultx(DataSet* results, int type, double value);
+void AddExternalResultx(DataSet* results, int type, double* value, int nraws);
+
+#endif  /* _ADDEXTERNALRESULT_H */
Index: /issm/trunk-jpl-damage/src/c/modules/AverageFilterx/AverageFilterx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/AverageFilterx/AverageFilterx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/AverageFilterx/AverageFilterx.cpp	(revision 11330)
@@ -0,0 +1,43 @@
+/*!\file:  AverageFilterx.cpp
+ * \brief  plug missing values of a double* array, using interpolation techniques. This 
+ * is an adaptation of Dr. Crippen's routine (Jet Propulsion Lab, see AverageFilterCrippen.c
+ * for more details.
+ */ 
+
+#include <stdio.h>
+#include <time.h>
+#include "./AverageFilterx.h"
+#include "../../shared/shared.h"
+
+int AverageFilterx(double** pimageout,double* image, int lines,int samps,int smooth){
+	
+	double      temp;
+	int         numvalues;
+	long			i, j;
+	int         pix1, pix2;
+
+	/*output: */
+	double*         imageout=NULL;
+
+	imageout=(double*)xmalloc(samps*lines*sizeof(double));
+
+  	for ( i = 0; i < lines; i++ ){
+  		for ( j = 0; j < samps; j++ ){
+			temp=0;
+			numvalues=0;
+			for ( pix1 = -smooth; pix1 < smooth+1; pix1++ ){
+				for ( pix2 = -smooth; pix2 < smooth+1; pix2++ ){
+					if( i+pix1 < 0 || i+pix1 > lines-1 || j+pix2 < 0 || j+pix2 > samps-1) continue;
+					numvalues=numvalues+1;
+					temp=temp+*(image+samps*(i+pix1)+j+pix2);
+				}
+			}
+			*(imageout+samps*(i)+j)=temp/numvalues;
+		}
+	}
+
+	/*Assign output pointers: */
+	*pimageout=imageout;
+
+	return 1;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/AverageFilterx/AverageFilterx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/AverageFilterx/AverageFilterx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/AverageFilterx/AverageFilterx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*
+	AverageFilterx.h
+*/
+
+#ifndef AVERAGEFILTERX_H
+#define AVERAGEFILTERX_H
+
+//#define _DEBUG_
+//#define _DEBUG2_
+
+/* local prototypes: */
+int AverageFilterx(double** pimageout,double* imagein, int lines,int samp,int smooth);
+	
+#endif /* AVERAGEFILTERX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 11330)
@@ -0,0 +1,77 @@
+/*!\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 "../../Container/Container.h"    
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../toolkits/toolkits.h"
+#include "../modules.h"
+
+			
+void AverageOntoPartitionx(double** paverage, Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vertex_response){
+
+	int     i,j,k;
+	int     dummy;
+
+	int     npart;
+	double *qmu_part  = NULL;
+	int     numberofvertices;
+
+	/*output: */
+	Vec partition_contributions=NULL;
+	Vec partition_areas=NULL;
+	Vec vec_average=NULL;
+	double* average=NULL;
+
+	/*First, recover qmu partition of vertices: */
+	parameters->FindParam(&qmu_part,&dummy,QmuPartitionEnum);
+
+	/*Some parameters: */
+	numberofvertices=vertices->NumberOfVertices();
+	parameters->FindParam(&npart,QmuNumberofpartitionsEnum);
+
+	/*average onto the separate areas. The result will be a npart sized vector. */
+
+	/*allocate: */
+	partition_contributions=NewVec(npart);
+	partition_areas=NewVec(npart);
+	vec_average=NewVec(npart);
+
+	/*loop on each element, and add contribution of the element to the partition (surface weighted average): */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->AverageOntoPartition(partition_contributions,partition_areas,vertex_response,qmu_part);
+	}
+
+	/*Assemble: */
+	VecAssemblyBegin(partition_contributions);
+	VecAssemblyEnd(partition_contributions);
+
+	VecAssemblyBegin(partition_areas);
+	VecAssemblyEnd(partition_areas);
+
+	/*We have the partition_areas and the partition_contributions for each partition -> compute the surfae weighted average: */
+	VecPointwiseDivide(vec_average,partition_contributions,partition_areas);
+
+	/*serialize:*/
+	VecToMPISerial(&average,vec_average);
+
+	/*Free ressources:*/
+	xfree((void**)&qmu_part);
+	VecFree(&partition_contributions);
+	VecFree(&partition_areas);
+	VecFree(&vec_average);
+
+	/*Assign output pointers:*/
+	*paverage=average;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  AverageOntoPartitionx.h
+ * \brief header file for averaging  dakota responses onto a vertices partition
+ */ 
+
+#ifndef _AVERAGEONTOPARTITIONXX_H
+#define _AVERAGEONTOPARTITIONXX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.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/trunk-jpl-damage/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp	(revision 11330)
@@ -0,0 +1,41 @@
+/*!\file BamgConvertMeshx
+ */
+
+#include "./BamgConvertMeshx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../objects/objects.h"
+
+using namespace bamg;
+using namespace std;
+
+int BamgConvertMeshx(BamgMesh* bamgmesh,BamgGeom* bamggeom,double* index,double* x,double* y,int nods,int nels){
+
+	/*Intermediary*/
+	int i,j,k;
+	int verbose=0;
+	int noerr=1;
+
+	/*Options*/
+	BamgOpts* bamgopts=NULL;
+	bamgopts=new BamgOpts();
+
+	// read mesh
+	if(verbose) printf("Reading mesh\n");
+	Mesh Th(index,x,y,nods,nels); 
+
+	//write mesh and geometry
+	if (verbose) printf("Write Geometry\n");
+	Th.Gh.WriteGeometry(bamggeom,bamgopts);
+	if (verbose) printf("Write Mesh\n");
+	Th.WriteMesh(bamgmesh,bamgopts);
+
+	//clean up
+	delete bamgopts;
+
+	/*No error return*/
+	return noerr;
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  BamgConvertMeshx.h
+ * \brief header file for Bamg module
+ */ 
+
+#ifndef _BAMGCONVERTMESHX_H
+#define _BAMGCONVERTMESHX_H
+
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+int BamgConvertMeshx(BamgMesh* bamgmesh,BamgGeom* bamggeom,double* index,double* x,double* y,int nods,int nels);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp	(revision 11330)
@@ -0,0 +1,20 @@
+/*!\file BamgTriangulatex
+ */
+
+#include "./BamgTriangulatex.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../objects/objects.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;
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/BamgTriangulatex/BamgTriangulatex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/BamgTriangulatex/BamgTriangulatex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/BamgTriangulatex/BamgTriangulatex.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  BamgTriangulatex.h
+ * \brief header file for Bamg module
+ */ 
+
+#ifndef _BAMGTRIANGULATEX_H
+#define _BAMGTRIANGULATEX_H
+
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+int BamgTriangulatex(int** pindex,int* pnels,double* x,double* y,int nods);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/Bamgx/Bamgx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Bamgx/Bamgx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Bamgx/Bamgx.cpp	(revision 11330)
@@ -0,0 +1,212 @@
+/*!\file Bamgx
+ * \brief: use Bamg capabilities.
+ */
+#include "./Bamgx.h"
+#include "../../objects/objects.h"
+#include "../../shared/shared.h"
+#include "../../include/include.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 noerr=1;
+	int i,j,num;
+	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 {{{1*/
+
+		//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 {{{1*/
+
+		// 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.MakeQuadTree();
+
+		//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 (!isnan(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 (!isnan(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 (!isnan(bamgopts->hmaxVertices[i])){
+					Metric M=BTh.vertices[i].m;
+					EigenMetric Vp(M/coef);
+					Vp.Minh(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 = %i\n",(Th.nbt-Th.nbtout-Th.nbq*2));
+			}
+			if (Th.nbq ){
+				printf("   new number of quads = %i\n",Th.nbq);
+			}
+		}
+
+		//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/trunk-jpl-damage/src/c/modules/Bamgx/Bamgx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Bamgx/Bamgx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Bamgx/Bamgx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  Bamgx.h
+ * \brief header file for Bamg module
+ */ 
+
+#ifndef _BAMGX_H
+#define _BAMGX_H
+
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+int     Bamgx(BamgMesh* bamgmesh_out,BamgGeom* bamggeom_out,BamgMesh* bamgmesh_in,BamgGeom* bamggeom_in,BamgOpts* bamgopts);
+
+#endif  /* _BAMGX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/Chacox/Chacox.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Chacox/Chacox.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Chacox/Chacox.cpp	(revision 11330)
@@ -0,0 +1,194 @@
+/* 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__,options[OPT_VWGTS]);
+		else if (!(int)options[OPT_VWGTS] &&  vwgts)
+			printf("%s -- Vertex weight flag=%d, so specified vertex weights ignored.\n",
+				   __FUNCT__,options[OPT_VWGTS]);
+	}
+
+	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__,options[OPT_EWGTS]);
+		else if (!(int)options[OPT_EWGTS] &&  ewgts)
+			printf("%s -- Edge weight flag=%d, so specified edge weights ignored.\n",
+				   __FUNCT__,options[OPT_EWGTS]);
+	}
+
+    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);
+
+
+	#endif //ifdef _HAVE_CHACO_
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Chacox/Chacox.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Chacox/Chacox.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Chacox/Chacox.h	(revision 11330)
@@ -0,0 +1,47 @@
+/*!\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 "../../Container/Container.h"
+#include "../../objects/objects.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/trunk-jpl-damage/src/c/modules/Chacox/chaco_seconds.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Chacox/chaco_seconds.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Chacox/chaco_seconds.cpp	(revision 11330)
@@ -0,0 +1,38 @@
+/*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/trunk-jpl-damage/src/c/modules/Chacox/input_parse.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Chacox/input_parse.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Chacox/input_parse.cpp	(revision 11330)
@@ -0,0 +1,265 @@
+/*!\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__,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",
+				   __FUNCT__,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",
+				   __FUNCT__,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",
+					   __FUNCT__,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",
+				   __FUNCT__,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",
+				   __FUNCT__,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",
+				   __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__,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",
+				   __FUNCT__,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);
+
+	#endif //#ifdef _HAVE_CHACO_ 
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Chacox/user_params.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Chacox/user_params.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Chacox/user_params.cpp	(revision 11330)
@@ -0,0 +1,154 @@
+/* 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/trunk-jpl-damage/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file ComputeBasalStressx
+ * \brief: compute pressure according to each element
+ */
+
+#include "./ComputeBasalStressx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void	ComputeBasalStressx( Vec* psigma,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,Parameters* parameters){
+
+	/*Intermediary*/
+	int i;
+	int      found=0;
+	double   numberofelements;
+	Element* element=NULL;
+
+	/*output: */
+	Vec sigma=NULL;
+
+	/*Recover numberofelements: */
+	parameters->FindParam(&numberofelements,MeshNumberofelementsEnum);
+
+	/*Allocate sigma on numberofelements: */
+	sigma=NewVec((int)numberofelements);
+
+	/*Compute basal stress for each element: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		element->ComputeBasalStress(sigma);
+	}
+
+	/*Assemble vector: */
+	VecAssemblyBegin(sigma);
+	VecAssemblyEnd(sigma);
+
+	/*Assign output pointers: */
+	*psigma=sigma;
+	
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  ComputeBasalStressx.h
+ * \brief header file pressure computation
+ */ 
+
+#ifndef _COMPUTEBASALSTRESSX_H
+#define _COMPUTEBASALSTRESSX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void	ComputeBasalStressx( Vec* pp_g,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters);
+
+#endif  /* _COMPUTEBASALSTRESSX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file ComputeStrainRatex
+ * \brief: compute pressure according to each element
+ */
+
+#include "./ComputeStrainRatex.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void	ComputeStrainRatex( Vec* peps,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,Parameters* parameters){
+
+	/*Intermediary*/
+	int i;
+	int      found=0;
+	int      numberofelements;
+	Element* element=NULL;
+
+	/*output: */
+	Vec eps=NULL;
+
+	/*Recover numberofelements: */
+	parameters->FindParam(&numberofelements,MeshNumberofelementsEnum);
+
+	/*Allocate eps on numberofelements (only 1 dof): */
+	eps=NewVec(numberofelements);
+
+	/*Compute basal stress for each element: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		element->ComputeStrainRate(eps);
+	}
+
+	/*Assemble vector: */
+	VecAssemblyBegin(eps);
+	VecAssemblyEnd(eps);
+
+	/*Assign output pointers: */
+	*peps=eps;
+	
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  ComputeStrainRate.h
+ * \brief header file pressure computation
+ */ 
+
+#ifndef _COMPUTESTRAINRATEX_H
+#define _COMPUTESTRAINRATEX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void	ComputeStrainRatex(Vec* eps_g,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters);
+
+#endif  /* _COMPUTESTRAINRATEX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 11330)
@@ -0,0 +1,53 @@
+/*!\file ConfigureObjectsx
+ * \brief: configure objects in elements and loads to link in with nodes
+ */
+
+#include "./ConfigureObjectsx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+int	ConfigureObjectsx( Elements* elements, Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
+
+	/*Intermediary*/
+	int noerr=1;
+	int i;
+	Element* element=NULL;
+	Load* load=NULL;
+	Node* node=NULL;
+	Material* material=NULL;
+	int configuration_type;
+
+	/*Get analysis type: */
+	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	
+	_printf_(VerboseMProcessor(),"      Configuring elements...\n");
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		element->Configure(elements,loads,nodes,materials,parameters);
+	}
+	_printf_(VerboseMProcessor(),"      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);
+		}
+	}
+	_printf_(VerboseMProcessor(),"      Configuring nodes...\n");
+	for (i=0;i<nodes->Size();i++){
+		node=(Node*)nodes->GetObjectByOffset(i);
+		if(node->InAnalysis(configuration_type)){
+			node->Configure(nodes,vertices);
+		}
+	}
+	
+	_printf_(VerboseMProcessor(),"      Configuring materials...\n");
+	for (i=0;i<materials->Size();i++){
+		material=(Material*)materials->GetObjectByOffset(i);
+		material->Configure(elements);
+	}
+	return noerr;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  ConfigureObjectsx.h
+ * \brief header file for degree of freedoms distribution routines.
+ */ 
+
+#ifndef _CONFIGUREOBJECTSX_H
+#define _CONFIGUREOBJECTSX_H
+
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+int ConfigureObjectsx( Elements* elements, Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials, Parameters* parameters);
+
+#endif  /* _CONFIGUREOBJECTSX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 11330)
@@ -0,0 +1,29 @@
+/*!\file:  ConstraintsStateLocal.h
+ * \brief local header files
+ */ 
+
+#ifndef _CONSTRAINTSSTATELOCAL_H
+#define _CONSTRAINTSSTATELOCAL_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/*melting: */
+void  ThermalConstraintsState(Loads* loads, int* pconverged, int* pnum_unstable_constraints,int analysis_type);
+
+/*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);
+
+/*rifts, trial and errors: */
+int    RiftIsPreStable(Loads* loads);
+void   RiftSetPreStable(Loads* loads);
+void   RiftPreConstrain(int* pnum_unstable_constraints,Loads* loads);
+void   RiftMaxPenetrationInInputs(Loads* loads);
+int    RiftPotentialUnstableConstraints(Loads* loads);
+int    RiftIsMaterialStable(Loads* loads);
+
+#endif  /* _CONSTRAINTSSTATEX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 11330)
@@ -0,0 +1,52 @@
+/*!\file ConstraintsStatex
+ * \brief: set up penalty constraints on loads
+ */
+
+#include "./ConstraintsStatex.h"
+#include "./ConstraintsStateLocal.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void ConstraintsStatex(int* pconverged, int* pnum_unstable_constraints, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters){
+
+	int i;
+
+	extern int num_procs;
+	extern int my_rank;
+	
+	/*output: */
+	int converged=0;
+	int num_unstable_constraints=0;
+	int min_mechanical_constraints=0; 
+	int analysis_type;
+
+	/*Display message*/
+	_printf_(VerboseModule(),"   Constraining penalties\n");
+
+	/*recover parameters: */
+	parameters->FindParam(&min_mechanical_constraints,DiagnosticRiftPenaltyThresholdEnum);
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Do we have penalties linked to rifts? In this case, run our special rifts penalty 
+	 * management routine, otherwise, skip : */
+	if (RiftIsPresent(loads,analysis_type)){
+		RiftConstraintsState(&converged,&num_unstable_constraints,loads,min_mechanical_constraints,analysis_type);
+	}
+	#ifdef _HAVE_THERMAL_
+	else if(ThermalIsPresent(loads,analysis_type)){
+		ThermalConstraintsState(loads,&converged,&num_unstable_constraints,analysis_type);
+	}
+	#endif
+	else{
+		/*Do nothing, no constraints management!:*/
+		num_unstable_constraints=0;
+		converged=1;
+	}
+		
+	/*Assign output pointers: */
+	*pconverged=converged;
+	*pnum_unstable_constraints=num_unstable_constraints;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStatex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 11330)
@@ -0,0 +1,17 @@
+/*!\file:  ConstraintsStatex.h
+ * \brief header file for penalty constraints module
+ */ 
+
+#ifndef _CONSTRAINTSSTATEX_H
+#define _CONSTRAINTSSTATEX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+int   ThermalIsPresent(Loads* loads,int analysis_type);
+int    RiftIsPresent(Loads* loads,int analysis_type);
+void ConstraintsStatex(int* pconverged, int* pnum_unstable_constraints, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters); 
+
+#endif  /* _CONSTRAINTSSTATEX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 11330)
@@ -0,0 +1,378 @@
+/*!\file RiftConstraintsState.cpp
+ * \brief: manage penalties for rifts 
+ */
+
+#include "./ConstraintsStateLocal.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../shared/shared.h"
+
+#define _ZIGZAGCOUNTER_
+
+/*current module: */
+/*RiftIsPresent(Loads* loads,int configuration_type){{{1*/
+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;
+			}
+		}
+	}
+
+	#ifdef _PARALLEL_
+	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);                
+	found=mpi_found;
+	#endif
+
+	return found;
+}
+/*}}}*/
+/*RiftConstraintsState(int* pconverged, int* pnum_unstable_constraints,Loads* loads,int min_mechanical_constraints,int configuration_type){{{1*/
+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;
+	int potential;
+
+	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){
+		_printf_(VerboseModule(),"   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){{{1*/
+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;
+			}
+		}
+	}
+
+	#ifdef _PARALLEL_
+	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,MPI_COMM_WORLD);                
+	num_unstable_constraints=sum_num_unstable_constraints;
+	#endif
+	
+	/*Assign output pointers: */
+	*pnum_unstable_constraints=num_unstable_constraints;
+
+}
+/*}}}*/
+/*RiftIsFrozen(Loads* loads,int configuration_type){{{1*/
+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! : */
+	#ifdef _PARALLEL_
+	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
+	MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);                
+	found=mpi_found;
+	#endif
+
+	return found;
+}
+/*}}}*/
+/*RiftFreezeConstraints(Loads* loads,int configuration_type){{{1*/
+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();
+			}
+
+		}
+	}
+
+}
+/*}}}*/
+
+/*diverse trials and errors: */
+/*RiftIsMaterialStable(Loads* loads){{{1*/
+int RiftIsMaterialStable(Loads* loads){
+
+	int i;
+	
+	Riftfront* riftfront=NULL;
+	int found=0;
+	int mpi_found=0;
+
+	/*go though loads, and if non-linearity of the material has converged, let all penalties know: */
+	for (i=0;i<loads->Size();i++){
+
+		if(RiftfrontEnum==loads->GetEnum(i)){
+
+			riftfront=(Riftfront*)loads->GetObjectByOffset(i);
+
+			if (riftfront->IsMaterialStable()){
+				found=1;
+				/*do not break! all penalties should get informed the non-linearity converged!*/
+			}
+		}
+	}
+
+	#ifdef _PARALLEL_
+	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);                
+	found=mpi_found;
+	#endif
+
+	return found;
+}
+/*}}}*/
+/*RiftIsPreStable(Loads* loads){{{1*/
+int RiftIsPreStable(Loads* loads){
+
+
+	int i;
+	
+	Riftfront* riftfront=NULL;
+	int found=0;
+	int mpi_found=0;
+
+	/*go though loads, and figure out if one of the penpair loads is still not stable: */
+	for (i=0;i<loads->Size();i++){
+
+		if(RiftfrontEnum==loads->GetEnum(i)){
+
+			riftfront=(Riftfront*)loads->GetObjectByOffset(i);
+
+			if (riftfront->PreStable()==0){
+				found=1;
+				break;
+			}
+		}
+	}
+
+	#ifdef _PARALLEL_
+	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);                
+	found=mpi_found;
+	#endif
+
+	if (found){
+		/*We found an unstable constraint. : */
+		return 0;
+	}
+	else{
+		return 1;
+	}
+}
+/*}}}*/
+/*RiftSetPreStable(Loads* loads){{{1*/
+void RiftSetPreStable(Loads* loads){
+
+
+	int i;
+	
+	Riftfront* riftfront=NULL;
+	int found=0;
+	int mpi_found=0;
+
+	/*go though loads, and set loads to pre stable.:*/
+	for (i=0;i<loads->Size();i++){
+
+		if(RiftfrontEnum==loads->GetEnum(i)){
+
+			riftfront=(Riftfront*)loads->GetObjectByOffset(i);
+			riftfront->SetPreStable();
+		}
+	}
+}
+/*}}}*/
+/*RiftPreConstrain(int* pnum_unstable_constraints,Loads* loads){{{1*/
+void RiftPreConstrain(int* pnum_unstable_constraints,Loads* loads){
+
+	int			i;
+	
+	/* generic object pointer: */
+	Riftfront* riftfront=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)){
+
+			riftfront=(Riftfront*)loads->GetObjectByOffset(i);
+
+			riftfront->PreConstrain(&unstable);
+
+			num_unstable_constraints+=unstable;
+		}
+	}
+
+	#ifdef _PARALLEL_
+	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,MPI_COMM_WORLD);                
+	num_unstable_constraints=sum_num_unstable_constraints;
+	#endif
+	
+	/*Assign output pointers: */
+	*pnum_unstable_constraints=num_unstable_constraints;
+
+}
+/*}}}*/
+/*RiftMaxPenetrationInInputs(Loads* loads){{{1*/
+void RiftMaxPenetrationInInputs(Loads* loads){
+
+	int			i;
+	
+	/* generic object pointer: */
+	Riftfront* riftfront=NULL;
+
+	/*rift penetration: */
+	double max_penetration=0;
+	double mpi_max_penetration;
+	double penetration;
+
+	/*Ok, we are going to find the node pairs which are not penetrating, even though they 
+	 * are penalised. We will release only the one with has least <0 penetration. : */
+
+	max_penetration=0;
+	for (i=0;i<loads->Size();i++){
+
+		if (RiftfrontEnum==loads->GetEnum(i)){
+
+			riftfront=(Riftfront*)loads->GetObjectByOffset(i);
+
+			riftfront->MaxPenetration(&penetration);
+
+			if (penetration>max_penetration)max_penetration=penetration;
+		}
+	}
+
+	#ifdef _PARALLEL_
+	MPI_Reduce (&max_penetration,&mpi_max_penetration,1,MPI_DOUBLE,MPI_MAX,0,MPI_COMM_WORLD );
+	MPI_Bcast(&mpi_max_penetration,1,MPI_DOUBLE,0,MPI_COMM_WORLD);                
+	max_penetration=mpi_max_penetration;
+	#endif
+
+	/*feed max_penetration to inputs: */
+	for(i=0;i<loads->Size();i++){
+		Load* load=(Load*)loads->GetObjectByOffset(i);
+		load->InputUpdateFromVector(&max_penetration,MaxPenetrationEnum,ConstantEnum);
+	}
+}
+/*}}}*/
+/*RiftPotentialUnstableConstraints(Loads* loads){{{1*/
+int RiftPotentialUnstableConstraints(Loads* loads){
+
+	int			i;
+	
+	/* generic object pointer: */
+	Riftfront* riftfront=NULL;
+
+	/*Ok, we are going to find the node pairs which are not penetrating, even though they 
+	 * are penalised. We will release only the one with has least <0 penetration. : */
+	int unstable=0;
+	int sum_num_unstable_constraints=0;
+	int num_unstable_constraints=0;
+
+	for (i=0;i<loads->Size();i++){
+
+		if (RiftfrontEnum==loads->GetEnum(i)){
+
+			riftfront=(Riftfront*)loads->GetObjectByOffset(i);
+
+			riftfront->PotentialUnstableConstraint(&unstable);
+
+			num_unstable_constraints+=unstable;
+		}
+	}
+
+	#ifdef _PARALLEL_
+	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,MPI_COMM_WORLD);                
+	num_unstable_constraints=sum_num_unstable_constraints;
+	#endif
+
+	return num_unstable_constraints;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ThermalConstraintsState.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ThermalConstraintsState.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ThermalConstraintsState.cpp	(revision 11330)
@@ -0,0 +1,51 @@
+/*!\file:  ThermalConstraintsState.cpp
+ * \brief  melting rate constraints
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ConstraintsStateLocal.h"
+
+void  ThermalConstraintsState(Loads* loads, int* pconverged, int* pnum_unstable_constraints,int configuration_type){
+
+	int i;
+
+	int unstable=0;
+	int num_unstable_constraints=0;
+	int converged=0;
+	int sum_num_unstable_constraints=0;
+
+	num_unstable_constraints=0;	
+
+	/*Enforce constraints: */
+	for(i=0;i<loads->Size();i++){
+		Object* object=(Object*)loads->GetObjectByOffset(i);
+		Load* load=(Load*)object;
+		if(load->InAnalysis(configuration_type)){
+			if(object->ObjectEnum()==PengridEnum){
+
+				Pengrid* pengrid=(Pengrid*)object;
+				pengrid->ConstraintActivate(&unstable);
+				num_unstable_constraints+=unstable;
+			}
+		}
+	}
+
+	#ifdef _PARALLEL_
+	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,MPI_COMM_WORLD);                
+	num_unstable_constraints=sum_num_unstable_constraints;
+	#endif
+
+	/*Have we converged? : */
+	if (num_unstable_constraints==0) converged=1;
+	else converged=0;
+
+	/*Assign output pointers: */
+	*pconverged=converged;
+	*pnum_unstable_constraints=num_unstable_constraints;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ThermalIsPresent.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ThermalIsPresent.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ThermalIsPresent.cpp	(revision 11330)
@@ -0,0 +1,37 @@
+/*!\file:  ThermalIsPresent.cpp
+ * \brief
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ConstraintsStateLocal.h"
+
+int ThermalIsPresent(Loads* loads,int configuration_type){
+
+	int i;
+	int found=0;
+	int mpi_found=0;
+
+	for(i=0;i<loads->Size();i++){
+		Object* object=(Object*)loads->GetObjectByOffset(i);
+		Load* load=(Load*)object;
+		if(load->InAnalysis(configuration_type)){
+			if (object->ObjectEnum()==PengridEnum){
+				found=1;
+				break;
+			}
+		}
+	}
+	
+	#ifdef _PARALLEL_
+	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);                
+	found=mpi_found;
+	#endif
+
+	return found;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 11330)
@@ -0,0 +1,78 @@
+/*! \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( Vec* pin_nod,Vec* pin_elem, double* index, double* x, double* y,Contour** contours,int numcontours,char* interptype,int nel,int nods, int edgevalue) {
+
+	int noerr=1;
+	int i;
+	int m,n;
+
+	/*Contour:*/
+	double*  in_nod_serial;
+	double   value;
+
+	/*threading: */
+	ContourToMeshxThreadStruct gate;
+	int num=1;
+	#ifdef _MULTITHREADING_
+	num=_NUMTHREADS_;
+	#endif
+
+
+	/*output: */
+	Vec in_nod=NULL;
+	Vec in_elem=NULL;
+
+	in_nod=NewVec(nods);
+	in_elem=NewVec(nel);
+
+	/*initialize thread parameters: */
+	gate.numcontours=numcontours;
+	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,num);
+
+	/*Assemble in_nod: */
+	VecAssemblyBegin(in_nod);
+	VecAssemblyEnd(in_nod);
+
+	/*Get in_nod serialised for next operation: */
+	VecToMPISerial(&in_nod_serial,in_nod);
+
+	/*Take care of the case where an element interpolation has been requested: */
+	if ((strcmp(interptype,"element")==0) || (strcmp(interptype,"element and node")==0)){
+		for (n=0;n<nel;n++){
+			if ( (in_nod_serial[ (int)*(index+3*n+0) -1] == 1) && (in_nod_serial[ (int)*(index+3*n+1) -1] == 1) && (in_nod_serial[ (int)*(index+3*n+2) -1] == 1) ){
+				value=1; VecSetValues(in_elem,1,&n,&value,INSERT_VALUES);
+			}
+		}
+	}
+
+	/*Assemble vectors: */
+	VecAssemblyBegin(in_elem);
+	VecAssemblyEnd(in_elem);
+
+	/*Assign output pointers: */
+	*pin_nod=in_nod;
+	*pin_elem=in_elem;
+
+	/*Free ressources:*/
+	xfree((void**)&in_nod_serial);
+
+	return noerr;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshx.h	(revision 11330)
@@ -0,0 +1,33 @@
+/*
+	ContourToMeshx.h
+*/
+
+
+#ifndef _CONTOURTOMESHX_H
+#define _CONTOURTOMESHX_H
+
+#include "../../shared/shared.h"
+#include "../../objects/objects.h"
+
+/*threading: */
+typedef struct{
+
+	int numcontours;
+	Contour** contours;
+	int nods;
+	int edgevalue;
+	Vec in_nod;
+	double* x;
+	double* y;
+
+} ContourToMeshxThreadStruct;
+
+
+/* local prototypes: */
+int ContourToMeshx( Vec* pin_nods,Vec* pin_elem, double* index, double* x, double* y,Contour** contours,int numcontours,char* interptype,int nel,int nods, int edgevalue);
+
+void* ContourToMeshxt(void* vContourToMeshxThreadStruct);
+
+
+#endif /* _CONTOURTOMESHX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp	(revision 11330)
@@ -0,0 +1,71 @@
+/*!\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){
+	
+	int noerr=1;
+
+	/*gate variables :*/
+	ContourToMeshxThreadStruct* gate=NULL;
+	pthread_handle* handle=NULL;
+	int     my_thread;
+	int     num_threads;
+	int     i0;
+	int     i1;
+
+	int i;
+
+	/*Contour:*/
+	Contour* contouri=NULL;
+	int      numnodes;
+	double*  xc=NULL;
+	double*  yc=NULL;
+
+
+	/*parameters: */
+	int numcontours;
+	Contour** contours=NULL;
+	int nods;
+	int edgevalue;
+	double* x=NULL;
+	double* y=NULL;
+	Vec in_nod=NULL;
+
+
+	/*recover handle and gate: */
+	handle=(pthread_handle*)vpthread_handle;
+	gate=(ContourToMeshxThreadStruct*)handle->gate;
+	my_thread=handle->id;
+	num_threads=handle->num;
+
+	/*recover parameters :*/
+	numcontours=gate->numcontours;
+	contours=gate->contours;
+	nods=gate->nods;
+	edgevalue=gate->edgevalue;
+	in_nod=gate->in_nod;
+	x=gate->x;
+	y=gate->y;
+
+	/*distribute indices across threads :*/
+	PartitionRange(&i0,&i1,nods,num_threads,my_thread);
+
+	/*Loop through all contours: */
+	for (i=0;i<numcontours;i++){
+		contouri=*(contours+i);
+		numnodes=contouri->nods;
+		xc=contouri->x;
+		yc=contouri->y;
+		IsInPoly(in_nod,xc,yc,numnodes,x,y,i0,i1,edgevalue);
+	}
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ContourToNodesx/ContourToNodesx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ContourToNodesx/ContourToNodesx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ContourToNodesx/ContourToNodesx.cpp	(revision 11330)
@@ -0,0 +1,39 @@
+/*! \file  ContourToNodesx.c
+ */
+
+#include "./ContourToNodesx.h"
+
+int ContourToNodesx( Vec* pflags,double* x, double* y, int nods, Contour** contours,int numcontours,int edgevalue){
+
+	int i;
+	int m,n;
+
+	/*Contour:*/
+	Contour* contouri=NULL;
+	int      numnodes;
+	double*  xc=NULL;
+	double*  yc=NULL;
+	double   value;
+
+	/*output: */
+	Vec flags=NULL;
+
+	flags=NewVec(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);
+	}
+
+	/*Assemble vector: */
+	VecAssemblyBegin(flags);
+	VecAssemblyEnd(flags);
+
+	/*Assign output pointers: */
+	*pflags=flags;
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ContourToNodesx/ContourToNodesx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ContourToNodesx/ContourToNodesx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ContourToNodesx/ContourToNodesx.h	(revision 11330)
@@ -0,0 +1,16 @@
+/*
+	ContourToNodesx.h
+*/
+
+
+#ifndef _CONTOURTONODESX_H
+#define _CONTOURTONODESX_H
+
+#include "../../shared/shared.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+int ContourToNodesx( Vec* pflags,double* x, double* y, int nods, Contour** contours,int numcontours,int edgevalue);
+
+#endif /* _CONTOURTONODESX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp	(revision 11330)
@@ -0,0 +1,26 @@
+/*!\file ControlInputGetGradientx
+ * \brief retrieve gradient from inputs in elements
+ */
+
+#include "./ControlInputGetGradientx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void ControlInputGetGradientx( Vec* pgradient, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name){
+
+	Vec gradient=NULL;
+	gradient=NewVec(vertices->NumberOfVertices());
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->ControlInputGetGradient(gradient,name);
+	}
+
+	VecAssemblyBegin(gradient);
+	VecAssemblyEnd(gradient);
+
+	/*Assign output pointers:*/
+	*pgradient=gradient;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.h	(revision 11330)
@@ -0,0 +1,12 @@
+/*!\file:  ControlInputGetGradientx.h
+ */ 
+
+#ifndef _CONTROLINPUTGETGRADIENTX_H
+#define _CONTROLINPUTGETGRADIENTX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+void	ControlInputGetGradientx( Vec* pgradient, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int name);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp	(revision 11330)
@@ -0,0 +1,18 @@
+/*!\file ControlInputScaleGradientx
+ * \brief retrieve gradient from inputs in elements
+ */
+
+#include "./ControlInputScaleGradientx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void ControlInputScaleGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name,double scale){
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->ControlInputScaleGradient(name,scale);
+	}
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h	(revision 11330)
@@ -0,0 +1,12 @@
+/*!\file:  ControlInputScaleGradientx.h
+ */ 
+
+#ifndef _CONTROLINPUTSSCALEGRADIENTX_H
+#define _CONTROLINPUTSSCALEGRADIENTX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+void	ControlInputScaleGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int name,double scale);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 11330)
@@ -0,0 +1,29 @@
+/*!\file ControlInputSetGradientx
+ * \brief retrieve gradient from inputs in elements
+ */
+
+#include "./ControlInputSetGradientx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name,double* gradient){
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->ControlInputSetGradient(gradient,name);
+	}
+
+}
+void ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name,Vec gradient){
+
+	/*Serialize gradient*/
+	double* serial_gradient=NULL;
+	VecToMPISerial(&serial_gradient,gradient);
+
+	ControlInputSetGradientx(elements,nodes,vertices, loads, materials, parameters, name,serial_gradient);
+
+	/*Clean up and return*/
+	xfree((void**)&serial_gradient);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  ControlInputSetGradientx.h
+ */ 
+
+#ifndef _CONTROLINPUTSSETGRADIENTX_H
+#define _CONTROLINPUTSSETGRADIENTX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+void	ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int name,double* gradient);
+void	ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int name,Vec gradient);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.cpp	(revision 11330)
@@ -0,0 +1,39 @@
+/*!\file CostFunctionx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./CostFunctionx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../Responsex/Responsex.h"
+
+void CostFunctionx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+
+	/*Intermediary*/
+	int    i;
+	int     num_responses;
+	double S;
+	Element* element=NULL;
+	int*     responses=NULL;
+
+	/*output: */
+	double J,Jplus;
+	
+	/*Recover parameters*/
+	parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+
+	/*Get response*/
+	J=0;
+	for(int i=0;i<num_responses;i++){
+		Responsex(&Jplus,elements,nodes,vertices,loads,materials,parameters,EnumToStringx(responses[i]),false,i); //False means DO NOT process units
+		J+=Jplus;
+	}
+
+	/*Assign output pointers: */
+	xfree((void**)&responses);
+	*pJ=J;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  CostFunctionx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _COSTFUNCTIONX_H
+#define _COSTFUNCTIONX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void CostFunctionx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp	(revision 11330)
@@ -0,0 +1,43 @@
+/*!\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 "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void CreateNodalConstraintsx( Vec* pys, Nodes* nodes,int configuration_type){
+
+	int i;
+	
+	/*intermediary: */
+	int  numberofdofs;
+
+	/*output: */
+	Vec ys=NULL;
+
+	/*figure out how many dofs we have: */
+	numberofdofs=nodes->NumberOfDofs(configuration_type,SsetEnum);
+
+	/*allocate:*/
+	ys=NewVec(numberofdofs);
+
+	/*go through all nodes, and for the ones corresponding to this configuration_type, fill the 
+	 * constraints vector with the constraint values: */
+	for (i=0;i<nodes->Size();i++){
+		Node* node=(Node*)nodes->GetObjectByOffset(i);
+		if (node->InAnalysis(configuration_type)){
+			node->CreateNodalConstraints(ys);
+		}
+	}
+
+	/*Assemble: */
+	VecAssemblyBegin(ys);
+	VecAssemblyEnd(ys);
+
+	/*Assign output pointers: */
+	*pys=ys;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  CreateNodalConstraintsx.h
+ */ 
+
+#ifndef _CREATENODALCONSTRAINTSX_H
+#define _CREATENODALCONSTRAINTSX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void CreateNodalConstraintsx( Vec* pys, Nodes* nodes,int configuration_type);
+
+#endif  /* _CREATENODALCONSTRAINTSX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.cpp	(revision 11330)
@@ -0,0 +1,120 @@
+/*!\file DakotaResponsesx
+ * \brief: update datasets using  parameter inputs
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./DakotaResponsesx.h"
+#include "../../Container/Container.h"    
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../toolkits/toolkits.h"
+#include "../modules.h"
+
+
+void DakotaResponsesx(double* d_responses,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,char** responses_descriptors,int numresponsedescriptors,int d_numresponses){
+
+	int        i,j,k;
+	extern int my_rank;
+	bool       process_units = true;
+
+	/*intermediary: */
+	char   root[50];
+	int    index;
+	int    npart;
+	double femmodel_response;
+	int    flag;
+	double* vertex_response=NULL;
+	double* qmu_response=NULL;
+
+	double* responses_pointer=NULL;
+
+	/*retrieve npart: */
+	parameters->FindParam(&npart,QmuNumberofpartitionsEnum);
+
+	/*save the d_responses pointer: */
+	responses_pointer=d_responses;
+
+	//watch out, we have more d_numresponses than numresponsedescriptors, because the responses have been expanded if they were scaled. 
+	//because we don't know the d_responses descriptors (the scaled ones) we can't key off them, so we will key off the responses_descriptors: */
+		
+	for(i=0;i<numresponsedescriptors;i++){
+		
+		flag=DescriptorIndex(root,&index,responses_descriptors[i]);
+
+		if(flag==ScaledEnum){
+
+			/*this response was scaled. pick up the response from the inputs: */
+			GetVectorFromInputsx(&vertex_response,elements,nodes, vertices, loads, materials, parameters, StringToEnumx(root),VertexEnum);
+
+			/*Now, average it onto the partition nodes: */
+			AverageOntoPartitionx(&qmu_response,elements,nodes,vertices,loads,materials,parameters,vertex_response);
+
+			/*Copy onto our dakota responses: */
+			if(my_rank==0){
+				/*plug response: */
+				for(i=0;i<npart;i++)responses_pointer[i]=qmu_response[i];
+
+				/*increment response_pointer :*/
+				responses_pointer+=npart;
+			}
+
+			/*Free ressources:*/
+			xfree((void**)&vertex_response);
+			xfree((void**)&qmu_response);
+
+		}
+		else if (flag==IndexedEnum){
+
+			/*indexed response: plug index into parameters and call response module: */
+			parameters->SetParam(index,IndexEnum);
+
+			//Responsex(responses_pointer,elements,nodes, vertices,loads,materials, parameters,root,process_units);
+			Responsex(&femmodel_response,elements,nodes, vertices,loads,materials, parameters,root,process_units,0);//0 is the index for weights
+			
+			if(my_rank==0){
+				/*plug response: */
+				responses_pointer[0]=femmodel_response;
+
+				/*increment response_pointer :*/
+				responses_pointer++;
+			}
+		}
+		else if (flag==NodalEnum){
+			_error_(" nodal response functions not supported yet!");
+
+			/*increment response_pointer :*/
+			responses_pointer++;
+		}
+		else if (flag==RegularEnum){
+			
+			/*perfectly normal response function: */
+			Responsex(&femmodel_response,elements,nodes, vertices,loads,materials, parameters,root,process_units,0);//0 is the weight index
+
+			if(my_rank==0){
+				/*plug response: */
+				responses_pointer[0]=femmodel_response;
+
+				/*increment response_pointer :*/
+				responses_pointer++;
+			}
+		}
+		else _error_("%s%i%s"," flag type ",flag," not supported yet for response analysis");
+	}
+
+
+	/*Synthesize echo: {{{*/
+	if(my_rank==0){
+		printf("   responses: %i: ",d_numresponses);
+		for(i=0;i<d_numresponses-1;i++)printf("%g|",d_responses[i]);
+		printf("%g",d_responses[d_numresponses-1]);
+		printf("\n");
+	}
+	/*}}}*/
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  DakotaResponsesx.h
+ * \brief header file for computing dakota responses
+ */ 
+
+#ifndef _DAKOTARESPONSESXX_H
+#define _DAKOTARESPONSESXX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+void DakotaResponsesx(double* d_responses,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,char** responses_descriptors,int numresponsedescriptors,int d_numresponses);
+
+#endif  /* _DAKOTARESPONSESXX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/Dakotax/DakotaFree.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Dakotax/DakotaFree.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Dakotax/DakotaFree.cpp	(revision 11330)
@@ -0,0 +1,58 @@
+/*!\file: DakotaFree.cpp
+ * \brief DakotaFree: free allocations on other cpus, not done by Dakota.
+
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../Container/Container.h"    
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../modules.h"
+
+
+void DakotaFree(double** pvariables,char*** pvariables_descriptors,char*** presponses_descriptors,int numvariables,int numresponses){
+
+	int i;
+	extern 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;
+
+
+	/*Free variables and variables_descriptors only on cpu !=0*/
+	if(my_rank!=0){
+		xfree((void**)&variables);
+		for(i=0;i<numvariables;i++){
+			string=variables_descriptors[i];
+			xfree((void**)&string);
+		}
+		xfree((void**)&variables_descriptors);
+	}
+	
+	//responses descriptors on every cpu
+	for(i=0;i<numresponses;i++){
+		string=responses_descriptors[i];
+		xfree((void**)&string);
+	}
+	//rest of dynamic allocations.
+	xfree((void**)&responses_descriptors);
+
+	/*Assign output pointers:*/
+	*pvariables=variables;
+	*pvariables_descriptors=variables_descriptors;
+	*presponses_descriptors=responses_descriptors;
+}
+
Index: /issm/trunk-jpl-damage/src/c/modules/Dakotax/DakotaMPI_Bcast.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Dakotax/DakotaMPI_Bcast.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Dakotax/DakotaMPI_Bcast.cpp	(revision 11330)
@@ -0,0 +1,66 @@
+/*!\file: DakotaMPI_Bcast
+ * \brief: broadcast variables_descriptors, variables, numvariables and numresponses
+ * from cpu 0 to all other cpus.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Dakotax.h"
+
+void DakotaMPI_Bcast(double** pvariables, char*** pvariables_descriptors,int* pnumvariables, int* pnumresponses){
+
+	int i;
+	extern 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 inputs from pointers: */
+	variables=*pvariables;
+	variables_descriptors=*pvariables_descriptors;
+	numvariables=*pnumvariables;
+	numresponses=*pnumresponses;
+
+	/*numvariables: */
+	MPI_Bcast(&numvariables,1,MPI_INT,0,MPI_COMM_WORLD); 
+	
+	/*variables:*/
+	if(my_rank!=0)variables=(double*)xmalloc(numvariables*sizeof(double));
+	MPI_Bcast(variables,numvariables,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+
+	/*variables_descriptors: */
+	if(my_rank!=0){
+		variables_descriptors=(char**)xmalloc(numvariables*sizeof(char*));
+	}
+	for(i=0;i<numvariables;i++){
+		if(my_rank==0){
+			string=variables_descriptors[i];
+			string_length=(strlen(string)+1)*sizeof(char);
+		}
+		MPI_Bcast(&string_length,1,MPI_INT,0,MPI_COMM_WORLD); 
+		if(my_rank!=0)string=(char*)xmalloc(string_length);
+		MPI_Bcast(string,string_length,MPI_CHAR,0,MPI_COMM_WORLD); 
+		if(my_rank!=0)variables_descriptors[i]=string;
+	}
+
+	/*numresponses: */
+	MPI_Bcast(&numresponses,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+	/*Assign output pointers:*/
+	*pnumvariables=numvariables;
+	*pvariables=variables;
+	*pvariables_descriptors=variables_descriptors;
+	*pnumresponses=numresponses;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Dakotax/Dakotax.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Dakotax/Dakotax.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Dakotax/Dakotax.cpp	(revision 11330)
@@ -0,0 +1,150 @@
+/*!\file:  Dakotax.cpp
+ * \brief: wrapper to the Dakota capabilities. qmu fires up Dakota, and registers a Dakota Pluggin
+ * which will be in charge of running the solution sequences repeteadly, to garner statistics. 
+ *
+ * This routine deals with running ISSM and Dakota in library mode. In library mode, Dakota does not 
+ * run as an execuatble. Its capabilities are linked into the ISSM software. ISSM calls dakota routines 
+ * directly from the dakota library. qmu.cpp is the code that is in charge of calling those routines. 
+ *
+ * Dakota has its own way of running in parallel (for embarassingly parallel jobs). We do not want that, 
+ * as ISSM knows exactly how to run "really parallel" jobs that use all CPUS. To bypass Dakota's parallelism, 
+ * we overloaded the constructor for the parallel library (see the Dakota patch in the externalpackages/dakota
+ * directory). This overloaded constructor fires up Dakota serially on CPU 0 only! We take care of broadcasting 
+ * to the other CPUS, hence ISSM is running in parallel, and Dakota serially on CPU0. 
+ *
+ * Now, how does CPU 0 drive all other CPUS to carry out sensitivity analysese? By synchronizing its call to 
+ * our ISSM cores (diagnostic_core, thermal_core, transient_core, etc ...) on CPU 0 with all other CPUS. 
+ * This explains the structure of qmu.cpp, where cpu 0 runs Dakota, the Dakota pluggin fires up SpawnCore.cpp, 
+ * while the other CPUS are waiting for a broadcast from CPU0, once they get it, they also fire up 
+ * SpawnCore. In the end, SpawnCore is fired up on all CPUS, with CPU0 having Dakota inputs, that it will 
+ * broacast to other CPUS. 
+ *
+ * Now, how does dakota call the SpawnCore routine? The SpawnCore 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 SpawnCore from CPU0. 
+ *
+ */ 
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Dakotax.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../objects/DakotaPlugin.h"
+
+#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+#include "ParallelLibrary.H"
+#include "ProblemDescDB.H"
+#include "DakotaStrategy.H"
+#include "DakotaModel.H"
+#include "DakotaInterface.H"
+
+#endif
+
+#ifdef _SERIAL_
+void Dakotax(mxArray* femmodel){ 
+#else
+void Dakotax(FemModel* femmodel){ 
+#endif
+
+
+	#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+	
+	extern int         my_rank;
+	char*              dakota_input_file  = NULL;
+	char*              dakota_output_file = NULL;
+	char*              dakota_error_file  = NULL;
+	int                status=0;
+	Dakota::ModelLIter ml_iter;
+	Parameters* parameters                = NULL;
+
+	/*Retrieve parameters: */
+	#ifdef _SERIAL_
+	FetchMatlabData((Parameters**)&parameters,mxGetField((mxArray*)femmodel,0,"parameters"));
+	#else
+	parameters=femmodel->parameters;
+	#endif
+
+	/*Recover dakota_input_file, dakota_output_file and dakota_error_file, in the parameters dataset in parallel */
+	parameters->FindParam(&dakota_input_file,QmuInNameEnum);
+	parameters->FindParam(&dakota_output_file,QmuOutNameEnum);
+	parameters->FindParam(&dakota_error_file,QmuErrNameEnum);
+
+	#ifdef _PARALLEL_
+	if(my_rank==0){
+	#endif
+	
+		// Instantiate/initialize the parallel library and problem description
+		// database objects.
+		#ifdef _SERIAL_
+			Dakota::ParallelLibrary parallel_lib; //use Dakota's standard library mode constructor
+		#else
+			Dakota::ParallelLibrary parallel_lib("serial"); //use our own ISSM Dakota library mode constructor, which only fires up Dakota on CPU 0. 
+		#endif
+		Dakota::ProblemDescDB problem_db(parallel_lib); 
+
+		// Manage input file parsing, output redirection, and restart processing
+		// without a CommandLineHandler.  This version relies on parsing of an
+		// input file.
+		problem_db.manage_inputs(dakota_input_file);
+		// specify_outputs_restart() is only necessary if specifying non-defaults
+		parallel_lib.specify_outputs_restart(dakota_output_file,dakota_error_file,NULL,NULL);
+
+		// Instantiate the Strategy object (which instantiates all Model and
+		// Iterator objects) using the parsed information in problem_db.
+		Dakota::Strategy selected_strategy(problem_db);
+
+		// convenience function for iterating over models and performing any
+		// interface plug-ins
+		Dakota::ModelList& models = problem_db.model_list();
+
+		for (ml_iter = models.begin(); ml_iter != models.end(); ml_iter++) {
+
+			Dakota::Interface& interface = ml_iter->interface();
+
+			//set DB nodes to the existing Model specification
+			problem_db.set_db_model_nodes(ml_iter->model_id());
+
+			// Serial case: plug in derived Interface object without an analysisComm
+			interface.assign_rep(new SIM::DakotaPlugin(problem_db,(void*)femmodel), false);
+		}
+	
+		// Execute the strategy
+		problem_db.lock(); // prevent run-time DB queries
+		selected_strategy.run_strategy();
+		
+		#ifdef _PARALLEL_
+		//Warn other cpus that we are done running the dakota iterator, by setting the counter to -1:
+		SpawnCore(NULL,0, NULL,NULL,0,femmodel,-1);
+		#endif
+
+	#ifdef _PARALLEL_
+	}
+	else{
+
+		for(;;){
+			if(!SpawnCore(NULL,0, NULL,NULL,0,femmodel,0))break; //counter came in at -1 on cpu0, bail out.
+		}
+	}
+	#endif //#ifdef _PARALLEL_
+
+	/*Free ressources:*/
+	xfree((void**)&dakota_input_file);
+	xfree((void**)&dakota_error_file);
+	xfree((void**)&dakota_output_file);
+
+	#ifdef _SERIAL_
+	delete parameters;
+	#endif
+
+	#endif //#ifdef _HAVE_DAKOTA_
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Dakotax/Dakotax.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Dakotax/Dakotax.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Dakotax/Dakotax.h	(revision 11330)
@@ -0,0 +1,26 @@
+/*!\file:  Dakotax.h
+ * \brief header file for Qmu engine using Dakota
+ */ 
+
+#ifndef _DAKOTAX_H
+#define _DAKOTAX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+int SpawnCore(double* responses, int numresponses, double* variables, char** variables_descriptors,int numvariables, void* femmodel,int counter);
+int  DescriptorIndex(char* root, int* pindex,char* descriptor);
+
+#ifdef _SERIAL_
+void Dakotax(mxArray* femmodel);
+void SpawnCoreSerial(double* responses, int numresponses, double* variables, char** variables_descriptors,int numvariables, mxArray* femmodel,int counter);
+#else
+void Dakotax(FemModel* femmodel);
+void SpawnCoreParallel(double* responses, int numresponses, double* variables, char** variables_descriptors,int numvariables, FemModel* femmodel,int counter);
+#endif
+void DakotaResponses(double* responses,char** responses_descriptors,int numresponses,FemModel* femmodel);
+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);
+
+#endif  /* _DAKOTAX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/Dakotax/DescriptorIndex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Dakotax/DescriptorIndex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Dakotax/DescriptorIndex.cpp	(revision 11330)
@@ -0,0 +1,71 @@
+/*!\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 "../../shared/shared.h"
+#include "../../EnumDefinitions/EnumDefinitions.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_("%s%s%s"," descriptor ",descriptor," is not correctly formatted!");
+
+	if (strncmp(pch,"scaled",6)==0){
+		/*we have a scaled variable. recover the root: */
+		pch = strtok (NULL, "_");
+		if(!pch)_error_("%s%s%s"," scaled descriptor ",descriptor," is not correctly formatted!");
+		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_("%s%s%s"," indexed descriptor ",descriptor," is not correctly formatted!");
+		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
+		/*now recover  the index: */
+		pch = strtok (NULL, "_");
+		if(!pch)_error_("%s%s%s"," indexed descriptor ",descriptor," is not correctly formatted!");
+		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_("%s%s%s"," nodal descriptor ",descriptor," is not correctly formatted!");
+		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
+		/*now recover  the index: */
+		pch = strtok (NULL, "_");
+		if(!pch)_error_("%s%s%s"," nodal descriptor ",descriptor," is not correctly formatted!");
+		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/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCore.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCore.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCore.cpp	(revision 11330)
@@ -0,0 +1,32 @@
+/*!\file:  SpawnCore.cpp
+ * \brief: branch into SpawnCoreMatlab and SpawnCoreParallel.
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+
+#include "../../objects/objects.h"
+#include "../../io/io.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "./Dakotax.h"
+#include "../../include/include.h"
+
+int SpawnCore(double* responses, int numresponses, double* variables, char** variables_descriptors,int numvariables, void* femmodel,int counter){
+
+	/*Branch into a serial SpawnCore and a parallel SpawnCore: */
+
+	#ifdef _SERIAL_
+		SpawnCoreSerial(responses, numresponses, variables, variables_descriptors,numvariables, (mxArray*)femmodel, counter);
+	#else
+		/*Call SpawnCoreParallel unless counter=-1 on cpu0, in which case, bail out and return 0: */
+		MPI_Bcast(&counter,1,MPI_INT,0,MPI_COMM_WORLD); 
+		if(counter==-1)return 0;
+		SpawnCoreParallel(responses, numresponses, variables, variables_descriptors,numvariables, (FemModel*)femmodel,counter);
+	#endif
+	return 1;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCoreParallel.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCoreParallel.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCoreParallel.cpp	(revision 11330)
@@ -0,0 +1,87 @@
+/*!\file:  SpawnCoreParallel.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. 
+ * SpawnCoreParallel is called by all CPUS, with CPU 0 holding Dakota variable values, along 
+ * with variable descriptors. 
+ *
+ * SpawnCoreParallel 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. 
+ *
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+
+#include "../../objects/objects.h"
+#include "../../io/io.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../io/io.h"
+#include "../../shared/shared.h"
+#include "./Dakotax.h"
+#include "../../include/include.h"
+#include "../../solutions/solutions.h"
+#include "../modules.h"
+
+void SpawnCoreParallel(double* d_responses, int d_numresponses, double* d_variables, char** d_variables_descriptors,int d_numvariables, FemModel* femmodel,int counter){
+
+	/*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 i;
+	extern int my_rank;
+	
+	char   **responses_descriptors     = NULL; //these are our!  there are only numresponsedescriptors of them, not d_numresponses!!!
+	int      numresponsedescriptors;
+	char    *string                    = NULL;
+	int      string_length;
+	int      solution_type;
+	bool     control_analysis          = false;
+	void (*solutioncore)(FemModel*)    = NULL;
+
+	/*synchronize all cpus, as CPU 0 is probably late (it is starting the entire dakota strategy!) : */
+	MPI_Barrier(MPI_COMM_WORLD);
+	_printf_(VerboseQmu(),"qmu iteration: %i\n",counter);
+	
+	/*retrieve parameters: */
+	femmodel->parameters->FindParam(&responses_descriptors,&numresponsedescriptors,QmuResponsedescriptorsEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+
+	/* only cpu 0, running dakota is providing us with variables and variables_descriptors and numresponses: broadcast onto other cpus: */
+	DakotaMPI_Bcast(&d_variables,&d_variables_descriptors,&d_numvariables,&d_numresponses);
+
+	/*Modify core inputs in objects contained in femmodel, to reflect the dakota variables inputs: */
+	InputUpdateFromDakotax(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,d_variables,d_variables_descriptors,d_numvariables);
+
+	/*Determine solution sequence: */
+	_printf_(VerboseQmu(),"%s%s%s\n","Starting ",EnumToStringx(solution_type)," core:");
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	#ifdef _HAVE_CONTROL_
+	if(control_analysis)solutioncore=&control_core;
+	#else
+	_error_("ISSM was not compiled with control capabilities, exiting!");
+	#endif
+
+	/*Run the core solution sequence: */
+	solutioncore(femmodel);
+
+	/*compute responses: */
+	_printf_(VerboseQmu(),"compute dakota responses:\n");
+	DakotaResponsesx(d_responses,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,responses_descriptors,numresponsedescriptors,d_numresponses);
+	
+	/*Free ressources:*/
+	DakotaFree(&d_variables,&d_variables_descriptors,&responses_descriptors, d_numvariables, numresponsedescriptors);
+}
+
Index: /issm/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCoreSerial.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCoreSerial.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCoreSerial.cpp	(revision 11330)
@@ -0,0 +1,69 @@
+/*!\file:  SpawnCoreSerial.cpp
+ * \brief: run core ISSM solution using Dakota inputs. Call the Serial core solution, using mexCallMATLAB
+ * \sa SpawnCore.cpp SpawnCoreParallel.cpp
+ *
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../objects/objects.h"
+#include "../../io/io.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "./Dakotax.h"
+#include "../../include/include.h"
+
+void SpawnCoreSerial(double* responses, int numresponses, double* variables, char** variables_descriptors,int numvariables, mxArray* femmodel, int counter){
+
+	int i;
+
+	//inputs to matlab routine
+	mxArray* mxvariables=NULL;
+	double*  variables_copy=NULL;
+	mxArray* mxvariabledescriptors=NULL;
+	mxArray* mxcounter=NULL;
+	mwSize   dims[2]={0};
+
+	//mexCallMATLAB arrays
+	mxArray* array[4];
+
+	//output from SpawnCore in matlab routine.
+	mxArray* mxresponses=NULL;
+
+	/*Create variables and variable descriptors mxArrays that we will feed to the core solution for update of the inputs: */
+	mxvariables=mxCreateDoubleMatrix(numvariables,1,mxREAL);
+	variables_copy=(double*)xmalloc(numvariables*sizeof(double));
+	memcpy(variables_copy,variables,numvariables*sizeof(double));
+	mxSetPr(mxvariables,variables_copy);
+
+	dims[0]=numvariables;
+	dims[1]=1;
+	mxvariabledescriptors=mxCreateCellArray(2,dims);
+	for(i=0;i<numvariables;i++){
+		mxSetCell(mxvariabledescriptors,i,mxCreateString(variables_descriptors[i]));
+	}
+
+	mxcounter=mxCreateDoubleScalar((double)counter);
+
+	//call SpwanCore matlab routine.
+	array[0]=femmodel;
+	array[1]=mxvariables;
+	array[2]=mxvariabledescriptors;
+	array[3]=mxcounter;
+
+	mexCallMATLAB(1,&mxresponses,4,array,"SpawnCore");
+
+	/*copy responses back to dakota: */
+	memcpy(responses,mxGetPr(mxresponses),numresponses*sizeof(double));
+
+	//destroy constructed arrays: 
+	mxDestroyArray(mxvariables);
+	mxDestroyArray(mxvariabledescriptors);
+	mxDestroyArray(mxresponses);
+	mxDestroyArray(mxcounter);
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file DragCoefficientAbsGradientx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./DragCoefficientAbsGradientx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void DragCoefficientAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+
+	/*Intermediary*/
+	int i;
+	Element* element=NULL;
+
+	/*output: */
+	double J=0;
+	double J_sum;
+
+	/*Compute Misfit: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		J+=element->DragCoefficientAbsGradient(process_units,weight_index);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  DragCoefficientAbsGradientx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _DRAGCOEFFABSGRADX_H
+#define _DRAGCOEFFABSGRADX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void DragCoefficientAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp	(revision 11330)
@@ -0,0 +1,97 @@
+/*!\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 "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+int hascommondedge(double* element1,double* element2);
+
+void	ElementConnectivityx( double** pelementconnectivity, double* elements, int nel, double* nodeconnectivity, int nods, int width){
+
+	int i,j,k,n;
+
+	/*intermediary: */
+	int    maxels;
+	double element;
+	double connectedelement;
+	int    connectedelementindex;
+	int    node;
+	int    index;
+	int    num_elements;
+
+	/*output: */
+	double* elementconnectivity=NULL;
+
+	/*maxels: */
+	maxels=width-1;
+	/*Allocate connectivity: */
+	elementconnectivity=(double*)xcalloc(nel*3,sizeof(double));
+
+	/*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<nel;n++){
+
+		element=(double)(n+1); //matlab indexing
+
+		for(i=0;i<3;i++){
+		
+			node=(int)*(elements+n*3+i); //already matlab indexed, elements comes directly from the workspace.
+			index=node-1;
+
+			num_elements=(int)*(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=(int)(connectedelement-1); //go from matlab indexing to c indexing.
+				
+				if(hascommondedge(elements+n*3+0,elements+connectedelementindex*3+0)){
+					/*Ok, this connected element has a commond edge  with element, plug it into elementconnectivity, unless 
+					 *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(double* element1,double* element2){
+
+	int i,j;
+	int count;
+
+	count=0;
+	for(i=0;i<3;i++){
+		for(j=0;j<3;j++){
+			if (*(element1+i)==*(element2+j))count++;
+		}
+	}
+	if (count==2)return 1;
+	else return 0;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ElementConnectivityx/ElementConnectivityx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ElementConnectivityx/ElementConnectivityx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ElementConnectivityx/ElementConnectivityx.h	(revision 11330)
@@ -0,0 +1,12 @@
+/*!\file:  ElementConnectivityx.h
+ * \brief header file for element connectivity computation
+ */ 
+
+#ifndef _ELEMENTCONNECTIVITYX_H
+#define _ELEMENTCONNECTIVITYX_H
+
+/* local prototypes: */
+void	ElementConnectivityx( double** pelementconnectivity, double* elements, int nel, double* nodeconnectivity, int nods, int width);
+
+#endif  /* _ELEMENTCONNECTIVITYX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.cpp	(revision 11330)
@@ -0,0 +1,52 @@
+/*!\file ElementResponsex
+ * \brief: compute element input  on one element only
+ */
+
+#include "./ElementResponsex.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void ElementResponsex( double* presponse, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int response_enum,bool process_units){
+	
+
+	extern int my_rank;
+	int i;
+
+	int found=0;
+	int sumfound=0;
+	int cpu_found=-1;
+	int index;
+	double response;
+	Element* element=NULL;
+
+	/*retrieve element we are interested in: */
+	parameters->FindParam(&index,IndexEnum);
+
+	/*now, go through our elements, and retrieve the one with this id: index: */
+	for(i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		if (element->Id()==index){
+			found=1;
+			cpu_found=my_rank;
+			break;
+		}
+	}
+
+	/*Broadcast whether we found the element: */
+	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
+	if(!sumfound)_error_("%s%i%s","could not find material with id",index," to compute ElementResponse");
+
+	/*Ok, we found the element, compute responseocity: */
+	if(my_rank==cpu_found){
+		element->ElementResponse(&response,response_enum,IuToExtEnum);
+	}
+
+	/*Broadcast and plug into response: */
+	MPI_Allreduce ( &cpu_found,&cpu_found,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
+	MPI_Bcast(&response,1,MPI_DOUBLE,cpu_found,MPI_COMM_WORLD); 
+
+	*presponse=response;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  ElementResponsex.h
+ * \brief header file for computing input average over one element
+ */ 
+
+#ifndef _ELEMENTRESPONSEX_H
+#define _ELEMENTRESPONSEX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void ElementResponsex( double* presponse, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int response_enum,bool process_units);
+
+#endif  /* _ELEMENTRESPONSEX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/EnumToStringx/EnumToStringx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/EnumToStringx/EnumToStringx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/EnumToStringx/EnumToStringx.cpp	(revision 11330)
@@ -0,0 +1,458 @@
+/*
+* \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 "../../shared/shared.h"
+#include "../../include/include.h"
+#include "./EnumToStringx.h"
+
+const char* EnumToStringx(int en){
+
+	switch(en){
+
+		case AutodiffForwardEnum : return "AutodiffForward";
+		case AutodiffIsautodiffEnum : return "AutodiffIsautodiff";
+		case AutodiffReverseEnum : return "AutodiffReverse";
+		case BalancethicknessSpcthicknessEnum : return "BalancethicknessSpcthickness";
+		case BalancethicknessStabilizationEnum : return "BalancethicknessStabilization";
+		case BalancethicknessThickeningRateEnum : return "BalancethicknessThickeningRate";
+		case BasalforcingsGeothermalfluxEnum : return "BasalforcingsGeothermalflux";
+		case BasalforcingsMeltingRateCorrectionEnum : return "BasalforcingsMeltingRateCorrection";
+		case BasalforcingsMeltingRateEnum : return "BasalforcingsMeltingRate";
+		case BathymetryEnum : return "Bathymetry";
+		case BedEnum : return "Bed";
+		case ConstantsGEnum : return "ConstantsG";
+		case ConstantsReferencetemperatureEnum : return "ConstantsReferencetemperature";
+		case ConstantsYtsEnum : return "ConstantsYts";
+		case DiagnosticAbstolEnum : return "DiagnosticAbstol";
+		case DiagnosticIcefrontEnum : return "DiagnosticIcefront";
+		case DiagnosticMaxiterEnum : return "DiagnosticMaxiter";
+		case DiagnosticNumRequestedOutputsEnum : return "DiagnosticNumRequestedOutputs";
+		case DiagnosticPenaltyFactorEnum : return "DiagnosticPenaltyFactor";
+		case DiagnosticReferentialEnum : return "DiagnosticReferential";
+		case DiagnosticReltolEnum : return "DiagnosticReltol";
+		case DiagnosticRequestedOutputsEnum : return "DiagnosticRequestedOutputs";
+		case DiagnosticRestolEnum : return "DiagnosticRestol";
+		case DiagnosticRiftPenaltyLockEnum : return "DiagnosticRiftPenaltyLock";
+		case DiagnosticRiftPenaltyThresholdEnum : return "DiagnosticRiftPenaltyThreshold";
+		case DiagnosticShelfDampeningEnum : return "DiagnosticShelfDampening";
+		case DiagnosticSpcvxEnum : return "DiagnosticSpcvx";
+		case DiagnosticSpcvyEnum : return "DiagnosticSpcvy";
+		case DiagnosticSpcvzEnum : return "DiagnosticSpcvz";
+		case DiagnosticStokesreconditioningEnum : return "DiagnosticStokesreconditioning";
+		case DiagnosticVertexPairingEnum : return "DiagnosticVertexPairing";
+		case DiagnosticViscosityOvershootEnum : return "DiagnosticViscosityOvershoot";
+		case FlowequationBordermacayealEnum : return "FlowequationBordermacayeal";
+		case FlowequationBorderpattynEnum : return "FlowequationBorderpattyn";
+		case FlowequationBorderstokesEnum : return "FlowequationBorderstokes";
+		case FlowequationElementEquationEnum : return "FlowequationElementEquation";
+		case FlowequationIshutterEnum : return "FlowequationIshutter";
+		case FlowequationIsmacayealpattynEnum : return "FlowequationIsmacayealpattyn";
+		case FlowequationIsstokesEnum : return "FlowequationIsstokes";
+		case FlowequationVertexEquationEnum : return "FlowequationVertexEquation";
+		case FrictionCoefficientEnum : return "FrictionCoefficient";
+		case FrictionPEnum : return "FrictionP";
+		case FrictionQEnum : return "FrictionQ";
+		case GeometryHydrostaticRatioEnum : return "GeometryHydrostaticRatio";
+		case HydrologyCREnum : return "HydrologyCR";
+		case HydrologyKnEnum : return "HydrologyKn";
+		case HydrologyNEnum : return "HydrologyN";
+		case HydrologyPEnum : return "HydrologyP";
+		case HydrologyQEnum : return "HydrologyQ";
+		case HydrologySpcwatercolumnEnum : return "HydrologySpcwatercolumn";
+		case HydrologyStabilizationEnum : return "HydrologyStabilization";
+		case InversionControlParametersEnum : return "InversionControlParameters";
+		case InversionCostFunctionEnum : return "InversionCostFunction";
+		case InversionCostFunctionThresholdEnum : return "InversionCostFunctionThreshold";
+		case InversionCostFunctionsCoefficientsEnum : return "InversionCostFunctionsCoefficients";
+		case InversionCostFunctionsEnum : return "InversionCostFunctions";
+		case InversionGradientOnlyEnum : return "InversionGradientOnly";
+		case InversionGradientScalingEnum : return "InversionGradientScaling";
+		case InversionIscontrolEnum : return "InversionIscontrol";
+		case InversionTaoEnum : return "InversionTao";
+		case InversionMaxParametersEnum : return "InversionMaxParameters";
+		case InversionMaxiterPerStepEnum : return "InversionMaxiterPerStep";
+		case InversionMinParametersEnum : return "InversionMinParameters";
+		case InversionNstepsEnum : return "InversionNsteps";
+		case InversionNumControlParametersEnum : return "InversionNumControlParameters";
+		case InversionNumCostFunctionsEnum : return "InversionNumCostFunctions";
+		case InversionStepThresholdEnum : return "InversionStepThreshold";
+		case InversionThicknessObsEnum : return "InversionThicknessObs";
+		case InversionVelObsEnum : return "InversionVelObs";
+		case InversionVxObsEnum : return "InversionVxObs";
+		case InversionVyObsEnum : return "InversionVyObs";
+		case InversionVzObsEnum : return "InversionVzObs";
+		case MaskElementonfloatingiceEnum : return "MaskElementonfloatingice";
+		case MaskElementongroundediceEnum : return "MaskElementongroundedice";
+		case MaskElementonwaterEnum : return "MaskElementonwater";
+		case MaskVertexonfloatingiceEnum : return "MaskVertexonfloatingice";
+		case MaskVertexongroundediceEnum : return "MaskVertexongroundedice";
+		case MaskVertexonwaterEnum : return "MaskVertexonwater";
+		case MaterialsBetaEnum : return "MaterialsBeta";
+		case MaterialsHeatcapacityEnum : return "MaterialsHeatcapacity";
+		case MaterialsLatentheatEnum : return "MaterialsLatentheat";
+		case MaterialsMeltingpointEnum : return "MaterialsMeltingpoint";
+		case MaterialsMixedLayerCapacityEnum : return "MaterialsMixedLayerCapacity";
+		case MaterialsRheologyBEnum : return "MaterialsRheologyB";
+		case MaterialsRheologyBbarEnum : return "MaterialsRheologyBbar";
+		case MaterialsRheologyLawEnum : return "MaterialsRheologyLaw";
+		case MaterialsRheologyNEnum : return "MaterialsRheologyN";
+		case MaterialsRhoIceEnum : return "MaterialsRhoIce";
+		case MaterialsRhoWaterEnum : return "MaterialsRhoWater";
+		case MaterialsMuWaterEnum : return "MaterialsMuWater";
+		case MaterialsThermalExchangeVelocityEnum : return "MaterialsThermalExchangeVelocity";
+		case MaterialsThermalconductivityEnum : return "MaterialsThermalconductivity";
+		case MeshAverageVertexConnectivityEnum : return "MeshAverageVertexConnectivity";
+		case MeshDimensionEnum : return "MeshDimension";
+		case MeshEdgesEnum : return "MeshEdges";
+		case MeshElementconnectivityEnum : return "MeshElementconnectivity";
+		case MeshElementonbedEnum : return "MeshElementonbed";
+		case MeshElementonsurfaceEnum : return "MeshElementonsurface";
+		case MeshElements2dEnum : return "MeshElements2d";
+		case MeshElementsEnum : return "MeshElements";
+		case MeshLowerelementsEnum : return "MeshLowerelements";
+		case MeshNumberofedgesEnum : return "MeshNumberofedges";
+		case MeshNumberofelements2dEnum : return "MeshNumberofelements2d";
+		case MeshNumberofelementsEnum : return "MeshNumberofelements";
+		case MeshNumberoflayersEnum : return "MeshNumberoflayers";
+		case MeshNumberofvertices2dEnum : return "MeshNumberofvertices2d";
+		case MeshNumberofverticesEnum : return "MeshNumberofvertices";
+		case MeshUpperelementsEnum : return "MeshUpperelements";
+		case MeshVertexonbedEnum : return "MeshVertexonbed";
+		case MeshVertexonsurfaceEnum : return "MeshVertexonsurface";
+		case MeshXEnum : return "MeshX";
+		case MeshYEnum : return "MeshY";
+		case MeshZEnum : return "MeshZ";
+		case MiscellaneousNameEnum : return "MiscellaneousName";
+		case PrognosticHydrostaticAdjustmentEnum : return "PrognosticHydrostaticAdjustment";
+		case PrognosticMinThicknessEnum : return "PrognosticMinThickness";
+		case PrognosticPenaltyFactorEnum : return "PrognosticPenaltyFactor";
+		case PrognosticSpcthicknessEnum : return "PrognosticSpcthickness";
+		case PrognosticStabilizationEnum : return "PrognosticStabilization";
+		case PrognosticVertexPairingEnum : return "PrognosticVertexPairing";
+		case QmuIsdakotaEnum : return "QmuIsdakota";
+		case QmuMassFluxSegmentsEnum : return "QmuMassFluxSegments";
+		case QmuNumberofpartitionsEnum : return "QmuNumberofpartitions";
+		case QmuNumberofresponsesEnum : return "QmuNumberofresponses";
+		case QmuPartitionEnum : return "QmuPartition";
+		case QmuResponsedescriptorsEnum : return "QmuResponsedescriptors";
+		case QmuVariabledescriptorsEnum : return "QmuVariabledescriptors";
+		case RiftsNumriftsEnum : return "RiftsNumrifts";
+		case RiftsRiftstructEnum : return "RiftsRiftstruct";
+		case SettingsIoGatherEnum : return "SettingsIoGather";
+		case SettingsLowmemEnum : return "SettingsLowmem";
+		case SettingsOutputFrequencyEnum : return "SettingsOutputFrequency";
+		case SettingsResultsAsPatchesEnum : return "SettingsResultsAsPatches";
+		case SettingsWaitonlockEnum : return "SettingsWaitonlock";
+		case SteadystateMaxiterEnum : return "SteadystateMaxiter";
+		case SteadystateNumRequestedOutputsEnum : return "SteadystateNumRequestedOutputs";
+		case SteadystateReltolEnum : return "SteadystateReltol";
+		case SteadystateRequestedOutputsEnum : return "SteadystateRequestedOutputs";
+		case SurfaceEnum : return "Surface";
+		case SurfaceforcingsAblationRateEnum : return "SurfaceforcingsAblationRate";
+		case SurfaceforcingsAccumulationRateEnum : return "SurfaceforcingsAccumulationRate";
+		case SurfaceforcingsMassBalanceEnum : return "SurfaceforcingsMassBalance";
+		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 ThicknessEnum : return "Thickness";
+		case TimesteppingCflCoefficientEnum : return "TimesteppingCflCoefficient";
+		case TimesteppingFinalTimeEnum : return "TimesteppingFinalTime";
+		case TimesteppingTimeAdaptEnum : return "TimesteppingTimeAdapt";
+		case TimesteppingTimeStepEnum : return "TimesteppingTimeStep";
+		case TransientIsdiagnosticEnum : return "TransientIsdiagnostic";
+		case TransientIsgroundinglineEnum : return "TransientIsgroundingline";
+		case TransientIsprognosticEnum : return "TransientIsprognostic";
+		case TransientIsthermalEnum : return "TransientIsthermal";
+		case TransientNumRequestedOutputsEnum : return "TransientNumRequestedOutputs";
+		case TransientRequestedOutputsEnum : return "TransientRequestedOutputs";
+		case SolutionTypeEnum : return "SolutionType";
+		case AnalysisTypeEnum : return "AnalysisType";
+		case ConfigurationTypeEnum : return "ConfigurationType";
+		case AdjointBalancethicknessAnalysisEnum : return "AdjointBalancethicknessAnalysis";
+		case AdjointHorizAnalysisEnum : return "AdjointHorizAnalysis";
+		case AdjointSolutionEnum : return "AdjointSolution";
+		case AnalysisCounterEnum : return "AnalysisCounter";
+		case BalancethicknessAnalysisEnum : return "BalancethicknessAnalysis";
+		case BalancethicknessSolutionEnum : return "BalancethicknessSolution";
+		case BedSlopeAnalysisEnum : return "BedSlopeAnalysis";
+		case BedSlopeSolutionEnum : return "BedSlopeSolution";
+		case BedSlopeXAnalysisEnum : return "BedSlopeXAnalysis";
+		case BedSlopeYAnalysisEnum : return "BedSlopeYAnalysis";
+		case DiagnosticHorizAnalysisEnum : return "DiagnosticHorizAnalysis";
+		case DiagnosticHutterAnalysisEnum : return "DiagnosticHutterAnalysis";
+		case DiagnosticSolutionEnum : return "DiagnosticSolution";
+		case DiagnosticVertAnalysisEnum : return "DiagnosticVertAnalysis";
+		case EnthalpyAnalysisEnum : return "EnthalpyAnalysis";
+		case EnthalpySolutionEnum : return "EnthalpySolution";
+		case FlaimAnalysisEnum : return "FlaimAnalysis";
+		case FlaimSolutionEnum : return "FlaimSolution";
+		case HydrologyAnalysisEnum : return "HydrologyAnalysis";
+		case HydrologySolutionEnum : return "HydrologySolution";
+		case MeltingAnalysisEnum : return "MeltingAnalysis";
+		case NoneAnalysisEnum : return "NoneAnalysis";
+		case PrognosticAnalysisEnum : return "PrognosticAnalysis";
+		case PrognosticSolutionEnum : return "PrognosticSolution";
+		case SteadystateSolutionEnum : return "SteadystateSolution";
+		case SurfaceSlopeAnalysisEnum : return "SurfaceSlopeAnalysis";
+		case SurfaceSlopeSolutionEnum : return "SurfaceSlopeSolution";
+		case SurfaceSlopeXAnalysisEnum : return "SurfaceSlopeXAnalysis";
+		case SurfaceSlopeYAnalysisEnum : return "SurfaceSlopeYAnalysis";
+		case ThermalAnalysisEnum : return "ThermalAnalysis";
+		case ThermalSolutionEnum : return "ThermalSolution";
+		case TransientSolutionEnum : return "TransientSolution";
+		case ApproximationEnum : return "Approximation";
+		case HutterApproximationEnum : return "HutterApproximation";
+		case MacAyealApproximationEnum : return "MacAyealApproximation";
+		case MacAyealPattynApproximationEnum : return "MacAyealPattynApproximation";
+		case MacAyealStokesApproximationEnum : return "MacAyealStokesApproximation";
+		case NoneApproximationEnum : return "NoneApproximation";
+		case PattynApproximationEnum : return "PattynApproximation";
+		case PattynStokesApproximationEnum : return "PattynStokesApproximation";
+		case StokesApproximationEnum : return "StokesApproximation";
+		case ConstraintsEnum : return "Constraints";
+		case LoadsEnum : return "Loads";
+		case MaterialsEnum : return "Materials";
+		case NodesEnum : return "Nodes";
+		case ParametersEnum : return "Parameters";
+		case VerticesEnum : return "Vertices";
+		case ResultsEnum : return "Results";
+		case BoolInputEnum : return "BoolInput";
+		case BoolParamEnum : return "BoolParam";
+		case ControlInputEnum : return "ControlInput";
+		case DatasetInputEnum : return "DatasetInput";
+		case DofIndexingEnum : return "DofIndexing";
+		case DoubleInputEnum : return "DoubleInput";
+		case DoubleMatArrayParamEnum : return "DoubleMatArrayParam";
+		case DoubleMatParamEnum : return "DoubleMatParam";
+		case DoubleParamEnum : return "DoubleParam";
+		case DoubleVecParamEnum : return "DoubleVecParam";
+		case ElementEnum : return "Element";
+		case ElementResultEnum : return "ElementResult";
+		case ExternalResultEnum : return "ExternalResult";
+		case FileParamEnum : return "FileParam";
+		case HookEnum : return "Hook";
+		case IcefrontEnum : return "Icefront";
+		case InputEnum : return "Input";
+		case IntInputEnum : return "IntInput";
+		case IntParamEnum : return "IntParam";
+		case IntVecParamEnum : return "IntVecParam";
+		case MacAyeal2dIceFrontEnum : return "MacAyeal2dIceFront";
+		case MacAyeal3dIceFrontEnum : return "MacAyeal3dIceFront";
+		case MaticeEnum : return "Matice";
+		case MatparEnum : return "Matpar";
+		case NodeEnum : return "Node";
+		case NumericalfluxEnum : return "Numericalflux";
+		case ParamEnum : return "Param";
+		case PattynIceFrontEnum : return "PattynIceFront";
+		case PengridEnum : return "Pengrid";
+		case PenpairEnum : return "Penpair";
+		case PentaEnum : return "Penta";
+		case PentaP1InputEnum : return "PentaP1Input";
+		case PetscMatParamEnum : return "PetscMatParam";
+		case PetscVecParamEnum : return "PetscVecParam";
+		case RiftfrontEnum : return "Riftfront";
+		case SegmentEnum : return "Segment";
+		case SegmentRiftfrontEnum : return "SegmentRiftfront";
+		case SpcDynamicEnum : return "SpcDynamic";
+		case SpcStaticEnum : return "SpcStatic";
+		case SpcTransientEnum : return "SpcTransient";
+		case StokesIceFrontEnum : return "StokesIceFront";
+		case StringArrayParamEnum : return "StringArrayParam";
+		case StringParamEnum : return "StringParam";
+		case TriaEnum : return "Tria";
+		case TriaP1InputEnum : return "TriaP1Input";
+		case VertexEnum : return "Vertex";
+		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 BedSlopeXEnum : return "BedSlopeX";
+		case BedSlopeYEnum : return "BedSlopeY";
+		case BoundaryEnum : return "Boundary";
+		case ConstantEnum : return "Constant";
+		case ConvergedEnum : return "Converged";
+		case ExtToIuEnum : return "ExtToIu";
+		case FillEnum : return "Fill";
+		case FractionIncrementEnum : return "FractionIncrement";
+		case FrictionEnum : return "Friction";
+		case GroundinglineMeltingRateEnum : return "GroundinglineMeltingRate";
+		case InternalEnum : return "Internal";
+		case IuToExtEnum : return "IuToExt";
+		case MassFluxEnum : return "MassFlux";
+		case MaxPenetrationEnum : return "MaxPenetration";
+		case MeltingOffsetEnum : return "MeltingOffset";
+		case MisfitEnum : return "Misfit";
+		case NumberNodeToElementConnectivityEnum : return "NumberNodeToElementConnectivity";
+		case PressureEnum : return "Pressure";
+		case PressurePicardEnum : return "PressurePicard";
+		case QmuPressureEnum : return "QmuPressure";
+		case QmuVxEnum : return "QmuVx";
+		case QmuVyEnum : return "QmuVy";
+		case QmuVzEnum : return "QmuVz";
+		case QmuThicknessEnum : return "QmuThickness";
+		case QmuBedEnum : return "QmuBed";
+		case QmuSurfaceEnum : return "QmuSurface";
+		case QmuMeltingEnum : return "QmuMelting";
+		case ResetPenaltiesEnum : return "ResetPenalties";
+		case SegmentOnIceShelfEnum : return "SegmentOnIceShelf";
+		case SurfaceAbsVelMisfitEnum : return "SurfaceAbsVelMisfit";
+		case SurfaceAreaEnum : return "SurfaceArea";
+		case SurfaceAverageVelMisfitEnum : return "SurfaceAverageVelMisfit";
+		case SurfaceLogVelMisfitEnum : return "SurfaceLogVelMisfit";
+		case SurfaceLogVxVyMisfitEnum : return "SurfaceLogVxVyMisfit";
+		case SurfaceRelVelMisfitEnum : return "SurfaceRelVelMisfit";
+		case SurfaceSlopeXEnum : return "SurfaceSlopeX";
+		case SurfaceSlopeYEnum : return "SurfaceSlopeY";
+		case TemperatureEnum : return "Temperature";
+		case TemperatureOldEnum : return "TemperatureOld";
+		case TemperaturePicardEnum : return "TemperaturePicard";
+		case ThicknessAbsMisfitEnum : return "ThicknessAbsMisfit";
+		case TypeEnum : return "Type";
+		case VelEnum : return "Vel";
+		case VelocityEnum : return "Velocity";
+		case VxAverageEnum : return "VxAverage";
+		case VxEnum : return "Vx";
+		case VxPicardEnum : return "VxPicard";
+		case VyAverageEnum : return "VyAverage";
+		case VyEnum : return "Vy";
+		case VyPicardEnum : return "VyPicard";
+		case VzEnum : return "Vz";
+		case VzMacAyealEnum : return "VzMacAyeal";
+		case VzPattynEnum : return "VzPattyn";
+		case VzPicardEnum : return "VzPicard";
+		case VzStokesEnum : return "VzStokes";
+		case VxMeshEnum : return "VxMesh";
+		case VyMeshEnum : return "VyMesh";
+		case VzMeshEnum : return "VzMesh";
+		case EnthalpyEnum : return "Enthalpy";
+		case EnthalpyPicardEnum : return "EnthalpyPicard";
+		case ThicknessAbsGradientEnum : return "ThicknessAbsGradient";
+		case StepResponsesEnum : return "StepResponses";
+		case IntMatParamEnum : return "IntMatParam";
+		case RheologyBbarAbsGradientEnum : return "RheologyBbarAbsGradient";
+		case DragCoefficientAbsGradientEnum : return "DragCoefficientAbsGradient";
+		case TransientInputEnum : return "TransientInput";
+		case OutputfilenameEnum : return "Outputfilename";
+		case WaterfractionEnum : return "Waterfraction";
+		case WatercolumnEnum : return "Watercolumn";
+		case BasalFrictionEnum : return "BasalFriction";
+		case ViscousHeatingEnum : return "ViscousHeating";
+		case QmuTemperatureEnum : return "QmuTemperature";
+		case HydrologyWaterVxEnum : return "HydrologyWaterVx";
+		case HydrologyWaterVyEnum : return "HydrologyWaterVy";
+		case StressTensorEnum : return "StressTensor";
+		case StressTensorxxEnum : return "StressTensorxx";
+		case StressTensorxyEnum : return "StressTensorxy";
+		case StressTensorxzEnum : return "StressTensorxz";
+		case StressTensoryyEnum : return "StressTensoryy";
+		case StressTensoryzEnum : return "StressTensoryz";
+		case StressTensorzzEnum : return "StressTensorzz";
+		case IceVolumeEnum : return "IceVolume";
+		case P0Enum : return "P0";
+		case P1Enum : return "P1";
+		case P1DGEnum : return "P1DG";
+		case BoolElementResultEnum : return "BoolElementResult";
+		case BoolExternalResultEnum : return "BoolExternalResult";
+		case DoubleElementResultEnum : return "DoubleElementResult";
+		case DoubleExternalResultEnum : return "DoubleExternalResult";
+		case DoubleMatExternalResultEnum : return "DoubleMatExternalResult";
+		case DoubleVecExternalResultEnum : return "DoubleVecExternalResult";
+		case IntExternalResultEnum : return "IntExternalResult";
+		case JEnum : return "J";
+		case PatchEnum : return "Patch";
+		case PatchNodesEnum : return "PatchNodes";
+		case PatchVerticesEnum : return "PatchVertices";
+		case PentaP1ElementResultEnum : return "PentaP1ElementResult";
+		case PetscVecExternalResultEnum : return "PetscVecExternalResult";
+		case StringExternalResultEnum : return "StringExternalResult";
+		case TimeEnum : return "Time";
+		case TriaP1ElementResultEnum : return "TriaP1ElementResult";
+		case WaterColumnOldEnum : return "WaterColumnOld";
+		case MinVelEnum : return "MinVel";
+		case MaxVelEnum : return "MaxVel";
+		case MinVxEnum : return "MinVx";
+		case MaxVxEnum : return "MaxVx";
+		case MaxAbsVxEnum : return "MaxAbsVx";
+		case MinVyEnum : return "MinVy";
+		case MaxVyEnum : return "MaxVy";
+		case MaxAbsVyEnum : return "MaxAbsVy";
+		case MinVzEnum : return "MinVz";
+		case MaxVzEnum : return "MaxVz";
+		case MaxAbsVzEnum : return "MaxAbsVz";
+		case RelativeEnum : return "Relative";
+		case AbsoluteEnum : return "Absolute";
+		case IncrementalEnum : return "Incremental";
+		case AgressiveMigrationEnum : return "AgressiveMigration";
+		case NoneEnum : return "None";
+		case SoftMigrationEnum : return "SoftMigration";
+		case StokesSolverEnum : return "StokesSolver";
+		case AdjointEnum : return "Adjoint";
+		case ColinearEnum : return "Colinear";
+		case ControlSteadyEnum : return "ControlSteady";
+		case FsetEnum : return "Fset";
+		case Gradient1Enum : return "Gradient1";
+		case Gradient2Enum : return "Gradient2";
+		case Gradient3Enum : return "Gradient3";
+		case GradientEnum : return "Gradient";
+		case GroundinglineMigrationEnum : return "GroundinglineMigration";
+		case GsetEnum : return "Gset";
+		case IndexEnum : return "Index";
+		case IndexedEnum : return "Indexed";
+		case IntersectEnum : return "Intersect";
+		case NodalEnum : return "Nodal";
+		case OldGradientEnum : return "OldGradient";
+		case OutputFilePointerEnum : return "OutputFilePointer";
+		case PetscOptionsAnalysesEnum : return "PetscOptionsAnalyses";
+		case PetscOptionsStringsEnum : return "PetscOptionsStrings";
+		case QmuErrNameEnum : return "QmuErrName";
+		case QmuInNameEnum : return "QmuInName";
+		case QmuOutNameEnum : return "QmuOutName";
+		case RegularEnum : return "Regular";
+		case ScaledEnum : return "Scaled";
+		case SeparateEnum : return "Separate";
+		case SsetEnum : return "Sset";
+		case VerboseEnum : return "Verbose";
+		case TriangleInterpEnum : return "TriangleInterp";
+		case BilinearInterpEnum : return "BilinearInterp";
+		case NearestInterpEnum : return "NearestInterp";
+		case XYEnum : return "XY";
+		case XYZPEnum : return "XYZP";
+		case OptionEnum : return "Option";
+		case OptionCellEnum : return "OptionCell";
+		case OptionCharEnum : return "OptionChar";
+		case OptionStructEnum : return "OptionStruct";
+		case OptionDoubleEnum : return "OptionDouble";
+		case OptionLogicalEnum : return "OptionLogical";
+		case PatersonEnum : return "Paterson";
+		case ArrheniusEnum : return "Arrhenius";
+		default : return "unknown";
+
+	}
+}
+void EnumToStringx(char** pstring,int enum_in){
+	char *string = NULL;
+	int   len = 0;
+
+	len=strlen(EnumToStringx(enum_in));
+	string=(char*)xmalloc((len+1)*sizeof(char));
+	memcpy(string,EnumToStringx(enum_in),(len+1)*sizeof(char));
+
+	/*Assign output pointer*/
+	*pstring=string;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/EnumToStringx/EnumToStringx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/EnumToStringx/EnumToStringx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/EnumToStringx/EnumToStringx.h	(revision 11330)
@@ -0,0 +1,11 @@
+/*
+ * \file EnumToStringx
+ * \brief: convert Enum To String
+ */
+
+#ifndef _ENUM_TO_STRINGX_
+
+const char* EnumToStringx(int enum_in);
+void EnumToStringx(char** string,int enum_in);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 11330)
@@ -0,0 +1,282 @@
+/*!\file Exp2Kmlx
+ * \brief exp to kml conversion routines.
+ */
+
+#include "./Exp2Kmlx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../modules.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;
+
+	FILE*   fid=NULL;
+
+	clock_t clock0,clock1;
+	time_t  time0, time1;
+
+	clock0=clock();
+	time0 =time(NULL);
+	_printf_(true,"\nExp2Kmlx Module -- %s",ctime(&time0));
+
+/*  read exp file  */
+
+	if (!DomainOutlineRead(&nprof,&pnvert,&pprofx,&pprofy,&closed,filexp,false))
+		_error_("Error reading exp file.");
+
+/*  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 && !closed[0]) {
+		_printf_(true,"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();
+
+		lat=(double *) xmalloc(pnvert[i]*sizeof(double));
+		lon=(double *) xmalloc(pnvert[i]*sizeof(double));
+		Xy2llx(lat,lon,pprofx[i],pprofy[i],pnvert[i],sgn,cm,sp);
+
+		kring->ncoord    =pnvert[i];
+		kring->coords    =(double (*)[3]) xmalloc(pnvert[i]*3*sizeof(double));
+		for (j=0; j<pnvert[i]; j++) {
+			kring->coords[j][0]=lon[j];
+			kring->coords[j][1]=lat[j];
+			kring->coords[j][2]=0.;
+		}
+		xfree((void**)&lon);
+		xfree((void**)&lat);
+
+		(kpoly ->outer     )->AddObject((Object*)kring);
+		kring =NULL;
+
+		for (i=1; i<nprof; i++) {
+			if (!closed[i]) {
+				_printf_(true,"Warning -- Inner profile %d is not closed with \"holes\" specified, so it will be ignored.\n",i+1);
+				continue;
+			}
+
+			kring =new KML_LinearRing();
+
+			lat=(double *) xmalloc(pnvert[i]*sizeof(double));
+			lon=(double *) xmalloc(pnvert[i]*sizeof(double));
+			Xy2llx(lat,lon,pprofx[i],pprofy[i],pnvert[i],sgn,cm,sp);
+			kring->ncoord    =pnvert[i];
+			kring->coords    =(double (*)[3]) xmalloc(pnvert[i]*3*sizeof(double));
+			for (j=0; j<pnvert[i]; j++) {
+				kring->coords[j][0]=lon[j];
+				kring->coords[j][1]=lat[j];
+				kring->coords[j][2]=0.;
+			}
+			xfree((void**)&lon);
+			xfree((void**)&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 (closed[i]) {
+				sprintf(kplace->name      ,"Polygon %d",i+1);
+				kplace->visibility=true;
+				sprintf(kplace->styleurl  ,"#BlackLineRandomPoly");
+
+				kpoly =new KML_Polygon();
+				kring =new KML_LinearRing();
+
+				lat=(double *) xmalloc(pnvert[i]*sizeof(double));
+				lon=(double *) xmalloc(pnvert[i]*sizeof(double));
+				Xy2llx(lat,lon,pprofx[i],pprofy[i],pnvert[i],sgn,cm,sp);
+
+				kring->ncoord    =pnvert[i];
+				kring->coords    =(double (*)[3]) xmalloc(pnvert[i]*3*sizeof(double));
+				for (j=0; j<pnvert[i]; j++) {
+					kring->coords[j][0]=lon[j];
+					kring->coords[j][1]=lat[j];
+					kring->coords[j][2]=0.;
+				}
+				xfree((void**)&lon);
+				xfree((void**)&lat);
+
+				(kpoly ->outer     )->AddObject((Object*)kring);
+				kring =NULL;
+
+				(kplace->geometry  )->AddObject((Object*)kpoly);
+				kpoly =NULL;
+			}
+
+			else {
+				sprintf(kplace->name      ,"LineString %d",i+1);
+				kplace->visibility=true;
+				sprintf(kplace->styleurl  ,"#RandomLineEmptyPoly");
+
+				kline =new KML_LineString();
+
+				lat=(double *) xmalloc(pnvert[i]*sizeof(double));
+				lon=(double *) xmalloc(pnvert[i]*sizeof(double));
+				Xy2llx(lat,lon,pprofx[i],pprofy[i],pnvert[i],sgn,cm,sp);
+
+				kline->ncoord    =pnvert[i];
+				kline->coords    =(double (*)[3]) xmalloc(pnvert[i]*3*sizeof(double));
+				for (j=0; j<pnvert[i]; j++) {
+					kline->coords[j][0]=lon[j];
+					kline->coords[j][1]=lat[j];
+					kline->coords[j][2]=0.;
+				}
+				xfree((void**)&lon);
+				xfree((void**)&lat);
+
+				(kplace->geometry  )->AddObject((Object*)kline);
+				kline =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  */
+
+	_printf_(true,"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=nprof-1; i>=0; i--) {
+		xfree((void**)&(pprofy[i]));
+		xfree((void**)&(pprofx[i]));
+	}
+	xfree((void**)&pnvert);
+
+	clock1=clock();
+	time1 =time(NULL);
+	_printf_(true,"Exp2Kmlx Module -- %f CPU seconds; %f elapsed seconds.\n\n",
+			 ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+
+	return(iret);
+}
+
Index: /issm/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.h	(revision 11330)
@@ -0,0 +1,20 @@
+/*!\file:  Exp2Kmlx.h
+ * \brief header file for exp to kml conversion routines.
+ */ 
+
+#ifndef _EXP2KMLX_H
+#define _EXP2KMLX_H
+
+#include <float.h>    /*  DBL_MAX  */
+#include "../../Container/Container.h"
+#include "../../objects/objects.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/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 11330)
@@ -0,0 +1,46 @@
+/*!\file GetSolutionFromInputsx
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./GetSolutionFromInputsx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void	GetSolutionFromInputsx( Vec* psolution, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters){
+
+	/*intermediary: */
+	int gsize;
+	int i;
+	Element* element=NULL;
+
+	int configuration_type;
+
+	/*output: */
+	Vec solution=NULL;
+
+	/*retrive parameters: */
+	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	/*Get size of vector: */
+	gsize=nodes->NumberOfDofs(configuration_type,GsetEnum);
+	if (gsize==0) _error_("Allocating a Vec of size 0 as gsize=0 for configuration: %s",EnumToStringx(configuration_type));
+	
+	/*Initialize solution: */
+	solution=NewVec(gsize);
+	
+	/*Go through elements and plug solution: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		element->GetSolutionFromInputs(solution);
+	}
+
+	/*Assemble vector: */
+	VecAssemblyBegin(solution);
+	VecAssemblyEnd(solution);
+
+	/*Assign output pointers:*/
+	*psolution=solution;
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  GetSolutionFromInputsx.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _GETSOLUTIONFROMINPUTSXX_H
+#define _GETSOLUTIONFROMINPUTSXX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void GetSolutionFromInputsx( Vec* psolution, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters);
+
+#endif  /* _GETSOLUTIONFROMINPUTSXX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 11330)
@@ -0,0 +1,62 @@
+/*!\file GetVectorFromInputsx
+ * \brief retrieve vector from inputs in elements
+ */
+
+#include "./GetVectorFromInputsx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void GetVectorFromInputsx( Vec* pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name, int type){
+
+
+	int i;
+	Vec vector=NULL;
+
+	if(type==VertexEnum){
+
+		/*Allocate vector*/
+		vector=NewVec(vertices->NumberOfVertices());
+
+		/*Look up in elements*/
+		for(i=0;i<elements->Size();i++){
+			Element* element=(Element*)elements->GetObjectByOffset(i);
+			element->GetVectorFromInputs(vector,name);
+		}
+
+		/*Look up in materials*/
+		for(i=0;i<materials->Size();i++){
+			Material* material=(Material*)materials->GetObjectByOffset(i);
+			material->GetVectorFromInputs(vector,name);
+		}
+	}
+	else{
+		_error_("%s%s%s"," vector type: ",EnumToStringx(type)," not supported yet!");
+	}
+
+	VecAssemblyBegin(vector);
+	VecAssemblyEnd(vector);
+
+	/*Assign output pointers:*/
+	*pvector=vector;
+
+}
+
+void GetVectorFromInputsx( double** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name, int type){
+	
+	/*output: */
+	double* vector=NULL;
+	
+	/*intermediary: */
+	Vec vec_vector=NULL;
+
+	GetVectorFromInputsx( &vec_vector, elements,nodes, vertices, loads, materials, parameters, name, type);
+	VecToMPISerial(&vector,vec_vector);
+
+	/*Free ressources:*/
+	VecFree(&vec_vector);
+
+	/*Assign output pointers:*/
+	*pvector=vector;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  GetVectorFromInputsx.h
+ */ 
+
+#ifndef _GETVECTORFROMINPUTSXX_H
+#define _GETVECTORFROMINPUTSXX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void	GetVectorFromInputsx( Vec* pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int name,int type);
+void	GetVectorFromInputsx( double** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int name,int type);
+
+#endif  /* _GETVECTORFROMINPUTSXX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.cpp	(revision 11330)
@@ -0,0 +1,38 @@
+/*!\file Gradjx
+ * \brief: compute inverse method gradient
+ */
+
+#include "./Gradjx.h"
+#include "../modules.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void Gradjx( Vec* pgradient, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int control_type){
+
+	int  i;
+	int  dim;
+	int  numberofvertices;
+	Vec  gradient = NULL;
+	
+	/*retrieve some parameters: */
+	parameters->FindParam(&dim,MeshDimensionEnum);
+	numberofvertices=vertices->NumberOfVertices();
+
+	/*Allocate gradient: */
+	gradient=NewVec(numberofvertices);
+
+	/*Compute gradients: */
+	for (i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->Gradj(gradient,control_type);
+	}
+
+	/*Assemble vector: */
+	VecAssemblyBegin(gradient);
+	VecAssemblyEnd(gradient);
+
+	/*Assign output pointers: */
+	*pgradient=gradient;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  Gradjx.h
+ * \brief header file for inverse methods gradient computation
+ */ 
+
+#ifndef _GRADJX_H
+#define _GRADJX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void Gradjx(Vec* pgrad_g, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,  Parameters* parameters, int control_type);
+
+#endif  /* _GRADJX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 11330)
@@ -0,0 +1,180 @@
+/*!\file GroundinglineMigrationx
+ * \brief: migration grounding line position.
+ */
+
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../Container/Container.h"
+#include "./GroundinglineMigrationx.h"
+
+void GroundinglineMigrationx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters){
+
+	int      i, migration_style,analysis_type;
+	double*  vertices_potentially_ungrounding = NULL;
+	double*  vertices_ungrounding             = NULL;
+	double*  old_floatingice                  = NULL;
+	Vec      vec_old_floatingice              = NULL;
+	Element* element                          = NULL;
+	
+	_printf_(VerboseModule(),"   Migrating grounding line\n");
+	
+	/*retrieve parameters: */
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	if(migration_style==NoneEnum) return;
+	if(migration_style!=AgressiveMigrationEnum && migration_style!=SoftMigrationEnum) _error_("%s not supported yet!",EnumToStringx(migration_style));
+
+	if(migration_style==SoftMigrationEnum){
+		/*Create flag for grounded vertices above the hydrostatic equilibrium: */
+		vertices_potentially_ungrounding=PotentialSheetUngrounding(elements,vertices,parameters);
+
+		/*propagate ice shelf into connex areas of the ice sheet that potentially want to unground: */
+		vertices_ungrounding=PropagateFloatingiceToGroundedNeighbors(elements,nodes,vertices,parameters,vertices_potentially_ungrounding);
+	}
+
+	/*Create vector with vertices initially floating and serialize*/
+	vec_old_floatingice=CreateNodesOnFloatingIce(nodes,analysis_type);
+	VecToMPISerial(&old_floatingice,vec_old_floatingice);
+
+	/*Migrate grounding line : */
+	for(i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		element->MigrateGroundingLine(old_floatingice,vertices_ungrounding);
+	}
+
+	/*free ressouces: */
+	VecFree(&vec_old_floatingice);
+	xfree((void**)&vertices_potentially_ungrounding);
+	xfree((void**)&vertices_ungrounding);
+	xfree((void**)&old_floatingice);
+}
+
+/*FUNCTION CreateNodesOnFloatingIce {{{1*/
+Vec CreateNodesOnFloatingIce(Nodes* nodes,int configuration_type){ 
+
+	int     i,numnods;
+	Vec   vec_nodes_on_floatingice = NULL;
+	Node *node                     = NULL;
+
+	/*First, initialize nodes_on_floatingice, which will track which nodes have changed status: */
+	numnods=nodes->NumberOfNodes(configuration_type);
+	vec_nodes_on_floatingice=NewVec(numnods);
+
+	/*Loop through nodes, and fill vec_nodes_on_floatingice: */
+	for(i=0;i<nodes->Size();i++){
+		node=(Node*)nodes->GetObjectByOffset(i);
+		if(node->InAnalysis(configuration_type)){
+			if(node->IsFloating()){
+				VecSetValue(vec_nodes_on_floatingice,node->Sid(),1.0,INSERT_VALUES);
+			}
+		}
+	}
+
+	/*Assemble vector: */
+	VecAssemblyBegin(vec_nodes_on_floatingice);
+	VecAssemblyEnd(vec_nodes_on_floatingice);
+
+	return vec_nodes_on_floatingice;
+}
+/*%}}}*/
+/*FUNCTION PotentialSheetUngrounding {{{1*/
+double*    PotentialSheetUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters){ 
+
+	int      i,numberofvertices;
+	double*  vertices_potentially_ungrounding      = NULL;
+	Vec      vec_vertices_potentially_ungrounding  = NULL;
+	Element* element                               = NULL;
+
+	/*Initialize vector with number of vertices*/
+	numberofvertices=vertices->NumberOfVertices();
+	vec_vertices_potentially_ungrounding=NewVec(numberofvertices); //grounded vertex that could start floating
+
+	/*Fill vector vertices_potentially_floating: */
+	for(i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		element->PotentialSheetUngrounding(vec_vertices_potentially_ungrounding);
+	}
+
+	/*Assemble vector and serialize */
+	VecAssemblyBegin(vec_vertices_potentially_ungrounding);
+	VecAssemblyEnd(vec_vertices_potentially_ungrounding);
+	VecToMPISerial(&vertices_potentially_ungrounding,vec_vertices_potentially_ungrounding);
+
+	/*free ressouces and return: */
+	VecFree(&vec_vertices_potentially_ungrounding);
+	return vertices_potentially_ungrounding;
+}
+/*}}}*/
+/*FUNCTION PropagateFloatingiceToGroundedNeighbors {{{1*/
+double*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,double* vertices_potentially_ungrounding){ 
+
+	int      i,analysis_type;
+	int      numberofvertices;
+	int      nflipped,local_nflipped;
+	double*  nodes_on_floatingice                  = NULL;
+	double*  elements_neighboring_floatingce      = NULL;
+	Vec      vec_elements_neighboring_floatingice = NULL;
+	Vec      vec_nodes_on_floatingice              = NULL;
+	Node*    node                                  = NULL;
+	Element* element                               = NULL;
+
+
+	/*recover parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	numberofvertices=vertices->NumberOfVertices();
+
+	/*recover vec_nodes_on_floatingice*/
+	vec_nodes_on_floatingice=CreateNodesOnFloatingIce(nodes,analysis_type);
+	VecToMPISerial(&nodes_on_floatingice,vec_nodes_on_floatingice);
+
+	nflipped=1; //bootstrap
+	while(nflipped){
+		
+		/*Vector of size number of elements*/
+		vec_elements_neighboring_floatingice=NewVec(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=(Element*)elements->GetObjectByOffset(i);
+			VecSetValue(vec_elements_neighboring_floatingice,element->Sid(),element->IsNodeOnShelfFromFlags(nodes_on_floatingice)?1.0:0.0,INSERT_VALUES);
+		}
+
+		/*Assemble vector and serialize: */
+		VecAssemblyBegin(vec_elements_neighboring_floatingice);
+		VecAssemblyEnd(vec_elements_neighboring_floatingice);
+		VecToMPISerial(&elements_neighboring_floatingce,vec_elements_neighboring_floatingice);
+
+		/*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=(Element*)elements->GetObjectByOffset(i);
+			if(elements_neighboring_floatingce[element->Sid()]){
+				local_nflipped+=element->UpdatePotentialSheetUngrounding(vertices_potentially_ungrounding,vec_nodes_on_floatingice,nodes_on_floatingice);
+			}
+		}
+		VecAssemblyBegin(vec_nodes_on_floatingice);
+		VecAssemblyEnd(vec_nodes_on_floatingice);
+		
+		MPI_Allreduce(&local_nflipped,&nflipped,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
+		_printf_(VerboseConvergence(),"   Additional number of vertices allowed to unground: %i\n",nflipped);
+
+		/*Avoid leaks: */
+		xfree((void**)&elements_neighboring_floatingce);
+		xfree((void**)&nodes_on_floatingice);
+
+		/*Assemble and serialize:*/
+		VecFree(&vec_elements_neighboring_floatingice);
+		VecToMPISerial(&nodes_on_floatingice,vec_nodes_on_floatingice); 
+	}
+
+	/*Free ressources:*/
+	VecFree(&vec_nodes_on_floatingice);
+	xfree((void**)&elements_neighboring_floatingce);
+
+	return nodes_on_floatingice;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h	(revision 11330)
@@ -0,0 +1,19 @@
+/*!\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);
+
+Vec        CreateNodesOnFloatingIce(Nodes* nodes,int configuration_type);
+double*    PotentialSheetUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters);
+double*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,double* vertices_potentially_ungrounding);
+#endif  /* _GROUNDINGLINEMIGRATIONX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/HoleFillerx/HoleFillerx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/HoleFillerx/HoleFillerx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/HoleFillerx/HoleFillerx.cpp	(revision 11330)
@@ -0,0 +1,368 @@
+/*!\file:  HoleFillerx.cpp
+ * \brief  plug missing values of a double* array, using interpolation techniques. This 
+ * is an adaptation of Dr. Crippen's routine (Jet Propulsion Lab)
+ */ 
+
+#include <stdio.h>
+#include <time.h>
+#include "./HoleFillerx.h"
+#include "../../shared/shared.h"
+
+int HoleFillerx(double** pimageout,double* image, int lines,int samps,int smooth){
+	
+	FILE 			*fp1;
+	unsigned long	filesize;
+	long			infinit;
+	double          temp;
+	long			i, j, k, l, ii, jj, bytes;
+	long			iii, jjj;
+	long			test, prevlines, prevpix, test1, test2, thresh,counter;
+	long			bell, cycles, leftovers;
+	float			howlong;
+	float			nsteps, ssteps, wsteps, esteps;
+	float			nwsteps, nesteps, swsteps, sesteps;
+	float			north, south, east, west;
+	float			nw, sw, ne, se, elev, range;
+	float			nnesteps, enesteps, esesteps, ssesteps;
+	float			sswsteps, wswsteps, wnwsteps, nnwsteps;
+	float			nne, ene, ese, sse;
+	float			ssw, wsw, wnw, nnw;	
+	float			sum;
+	
+	time_t			t1, t2;
+
+	/*output: */
+	double*         imageout=NULL;
+
+	double*         image2=NULL;
+	double*         image3=NULL;
+	double*         image4=NULL;
+
+	/*Added to original routine: */
+	int             imageoutsize;
+
+	 /*^^^^^^^^^^^^^  Remove pixels close to the holes ^^^^^^^^^^^^^*/
+	image2 = (double*) xmalloc( lines*samps*sizeof(double));
+	memcpy(image2,image,lines*samps*sizeof(double));
+	
+  	for ( i = 0; i < lines; i++ ){
+  		for ( j = 0; j < samps; j++ ){
+ 			if ( *(image+i*samps+j) == 0 ){ 
+  				if ( (j > 3) && (j < samps-4) && (i > 3) && (i < lines-4)){
+					for ( k = 0; k < 4; k++ ){
+						for ( l = 0; l < 4; l++ ){
+							*(image2+samps*(i+k)+j+l)=0;
+							*(image2+samps*(i-k)+j+l)=0;
+							*(image2+samps*(i+k)+j-l)=0;
+							*(image2+samps*(i-k)+j-l)=0;
+
+						}
+					}
+				}
+			}
+		}
+	}
+
+	image3 = (double*) xmalloc( lines*samps*sizeof(double));
+	memcpy(image3,image2,lines*samps*sizeof(double));
+
+	#ifdef _DEBUG2_
+		counter=0;
+		for ( i = 0; i < lines; i++ ) {
+			for ( j = 0; j < samps; j++ ){
+				if ( *(image2+i*samps+j) != 0 ) { 
+					counter++;
+				}
+			}
+		}
+		printf( "\n" );
+		printf("Number of zeroes remaining: %10ld",lines*samps-counter);
+		fflush( stdout );
+	#endif
+
+	goto afterfirst2;
+
+	again2:	
+	
+	#ifdef _DEBUG2_
+		counter=0;
+		for ( i = 0; i < lines; i++ ) {
+			for ( j = 0; j < samps; j++ ){
+				if ( *(image2+i*samps+j) != 0 ) { 
+					counter++;
+				}
+			}
+		}
+		//        n u m b e r   o f   z e r o e s   r e m a i n i n g :   1 2 3 4 5 6 7 8 9 10        
+		printf( "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b" );
+		printf("Number of zeroes remaining: %10ld",lines*samps-counter);
+		fflush( stdout );
+	#endif
+	
+	afterfirst2:
+
+/***************** FIRST RUN *********************/
+/*
+fprintf ( stdout, "First  Application:  " ); time(&t2); printf( ctime(&t2) );
+*/
+	for ( i = 0; i < lines; i++ ){
+		for ( j = 0; j < samps; j++ ){
+			if ( *(image2+i*samps+j) != 0 ){ 
+				*(image3+samps*i+j) = *(image2+i*samps+j); 
+				continue; 
+			} 
+
+	/* Count All Neighbors Test */
+			test = 0;		
+			for ( ii = i-1; ii < i+2; ii++ ){
+				for ( jj = j-1; jj < j+2; jj++ ){
+					if (( ii < 0 ) || ( ii >= lines )) continue;
+					if (( jj < 0 ) || ( jj >= samps )) continue;
+					if ( *(image2+ii*samps+jj) != 0 ) test += 1;			
+				}
+			}
+			if ( test < 3 ){ 
+				*(image3+samps*i+j) = 0; 
+				continue; 
+			} 
+
+			/* For void edge pixels: */			
+			
+			nsteps = 0.0; ssteps = 0.0; esteps = 0.0; wsteps = 0.0;
+			nwsteps = 0.0; nesteps = 0.0; swsteps = 0.0; sesteps = 0.0;
+			north = 0.0; south = 0.0; east = 0.0; west = 0.0;
+			nw = 0.0; ne = 0.0; sw = 0.0; se = 0.0;
+
+			nnesteps = 0.0; enesteps = 0.0; esesteps = 0.0; ssesteps = 0.0;
+			sswsteps = 0.0; wswsteps = 0.0; wnwsteps = 0.0; nnwsteps = 0.0;
+			nne = 0.0; ene = 0.0; ese = 0.0; sse = 0.0;
+			ssw = 0.0; wsw = 0.0; wnw = 0.0; nnw = 0.0;
+
+
+/** NSEW **/
+			for ( ii = i - 1; ii >= 0; ii-- ){   /* North */
+				if ( ii <= 0 ) { north = 0; nsteps = 0; break;}
+				if ( *(image2+ii*samps+j) != 0 ){ north = *(image2+ii*samps+j); nsteps = i - ii; break;}
+			}
+
+			for ( ii = i + 1; ii < lines; ii++ ){ /* South */ 
+				if ( ii >= lines-1 ){ south = 0; ssteps = 0; break;}
+				if ( *(image2+ii*samps+j) != 0 ){ south = *(image2+ii*samps+j); ssteps = ii - i; break;}
+			}
+				
+			for ( jj = j - 1; jj >= 0; jj-- ){   /* West */
+				if ( jj <= 0 ) { west = 0; wsteps = 0; break;}
+				if ( *(image2+i*samps+jj) != 0 ){ west = *(image2+i*samps+jj); wsteps = j - jj; break;}
+			}
+				
+			for ( jj = j + 1; jj < samps; jj++ ){ /* East */
+				if ( jj >= samps-1 ){ east = 0; esteps = 0; break;}
+				if ( *(image2+i*samps+jj) != 0 ){ east = *(image2+i*samps+jj); esteps = jj - j; break;}
+			}
+
+				
+/** Diagonals  **/						
+			/* Southeast */
+			for ( k = 1; k < infinit; k++ ){
+				ii = i + k; jj = j + k;
+				if (( ii == lines ) || ( jj == samps )){ se = 0; sesteps = 0; break;}
+				if ( *(image2+ii*samps+jj) != 0 ){ se = *(image2+ii*samps+jj); sesteps = 1.4142 * k; break;}
+			}
+			
+			/* Northeast */
+			for ( k = 1; k < infinit; k++ ){
+				ii = i - k; jj = j + k;
+				if (( ii == -1 ) || ( jj == samps )){ ne = 0; nesteps = 0; break;}
+				if ( *(image2+ii*samps+jj) != 0 ){ ne = *(image2+ii*samps+jj); nesteps = 1.4142 * k; break;}
+			}
+			
+			/* Northwest */
+			for ( k = 1; k < infinit; k++ ){
+				ii = i - k; jj = j - k;
+				if (( ii == -1 ) || ( jj == -1 )){ nw = 0; nwsteps = 0; break;}
+				if ( *(image2+ii*samps+jj) != 0 ){ nw = *(image2+ii*samps+jj); nwsteps = 1.4142 * k; break;}
+			}
+			
+			/* Southwest */
+			for ( k = 1; k < infinit; k++ ){
+				ii = i + k; jj = j - k;
+				if (( ii == lines ) || ( jj == -1 )){ sw = 0; swsteps = 0; break;}
+				if ( *(image2+ii*samps+jj) != 0 ){ sw = *(image2+ii*samps+jj); swsteps = 1.4142 * k; break;}
+			}
+
+/** Other 8 **/
+			/* NNE */
+			for ( k = 1; k < infinit; k++ ){
+				ii = i - (k*2); jj = j + k;
+				if (( ii <= -1 ) || ( jj >= samps )){ nne = 0; nnesteps = 0; break;}
+				if ( *(image2+ii*samps+jj) != 0 ){ nne = *(image2+ii*samps+jj); nnesteps = 2.2361 * k; break;}
+			}
+			
+			/* ENE */
+			for ( k = 1; k < infinit; k++ ){
+				ii = i - k; jj = j + (k*2);
+				if (( ii <= -1 ) || ( jj >= samps )){ ene = 0; enesteps = 0; break;}
+				if ( *(image2+ii*samps+jj) != 0 ){ ene = *(image2+ii*samps+jj); enesteps = 2.2361 * k; break;}
+			}
+			
+			/* ESE */
+			for ( k = 1; k < infinit; k++ ){
+				ii = i + k; jj = j + (k*2);
+				if (( ii >= lines ) || ( jj >= samps )){ ese = 0; esesteps = 0; break;}
+				if ( *(image2+ii*samps+jj) != 0 ){ ese = *(image2+ii*samps+jj); esesteps = 2.2361 * k; break;}
+			}
+			
+			/* SSE */
+			for ( k = 1; k < infinit; k++ ){
+				ii = i + (k*2); jj = j + k;
+				if (( ii >= lines ) || ( jj >= samps )){ sse = 0; ssesteps = 0; break;}
+				if ( *(image2+ii*samps+jj) != 0 ){ sse = *(image2+ii*samps+jj); ssesteps = 2.2361 * k; break;}
+			}
+
+			/* SSW */
+			for ( k = 1; k < infinit; k++ ){
+				ii = i + (k*2); jj = j - k;
+				if (( ii >= lines ) || ( jj <= -1 )){ ssw = 0; sswsteps = 0; break;}
+				if ( *(image2+ii*samps+jj) != 0 ){ ssw = *(image2+ii*samps+jj); sswsteps = 2.2361 * k; break;}
+			}
+			
+			/* WSW */
+			for ( k = 1; k < infinit; k++ ){
+				ii = i + k; jj = j - (k*2);
+				if (( ii >= lines ) || ( jj <= -1 )){ wsw = 0; wswsteps = 0; break;}
+				if ( *(image2+ii*samps+jj) != 0 ){ wsw = *(image2+ii*samps+jj); wswsteps = 2.2361 * k; break;}
+			}
+			
+			/* WNW */
+			for ( k = 1; k < infinit; k++ ){
+				ii = i - k; jj = j - (k*2);
+				if (( ii <= -1 ) || ( jj <= -1 )){ wnw = 0; wnwsteps = 0; break;}
+				if ( *(image2+ii*samps+jj) != 0 ){ wnw = *(image2+ii*samps+jj); wnwsteps = 2.2361 * k; break;}
+			}
+			
+			/* NNW */
+			for ( k = 1; k < infinit; k++ ){
+				ii = i - (k*2); jj = j - k;
+				if (( ii <= -1 ) || ( jj <= -1 )){ nnw = 0; nnwsteps = 0; break;}
+				if ( *(image2+ii*samps+jj) != 0 ){ nnw = *(image2+ii*samps+jj); nnwsteps = 2.2361 * k; break;}
+			}
+			
+			elev = 0; range = 0;
+/*NSEW*/			
+			if ( nsteps > 0.5 ){ elev += north /  nsteps; range +=  1.00 /  nsteps;}
+			if ( ssteps > 0.5 ){ elev += south /  ssteps; range +=  1.00 /  ssteps;}
+			if ( esteps > 0.5 ){ elev +=  east /  esteps; range +=  1.00 /  esteps;}
+			if ( wsteps > 0.5 ){ elev +=  west /  wsteps; range +=  1.00 /  wsteps;}
+/*Diag*/
+			if ( nwsteps > 0.5 ){ elev +=    nw / nwsteps; range +=  1.00 / nwsteps;}
+			if ( nesteps > 0.5 ){ elev +=    ne / nesteps; range +=  1.00 / nesteps;}
+			if ( swsteps > 0.5 ){ elev +=    sw / swsteps; range +=  1.00 / swsteps;}
+			if ( sesteps > 0.5 ){ elev +=    se / sesteps; range +=  1.00 / sesteps;}
+			
+/*Other 8*/
+			if ( nnesteps > 0.5 ){ elev += nne / nnesteps; range +=  1.00 / nnesteps;}
+			if ( enesteps > 0.5 ){ elev += ene / enesteps; range +=  1.00 / enesteps;}
+			if ( esesteps > 0.5 ){ elev += ese / esesteps; range +=  1.00 / esesteps;}
+			if ( ssesteps > 0.5 ){ elev += sse / ssesteps; range +=  1.00 / ssesteps;}
+			if ( sswsteps > 0.5 ){ elev += ssw / sswsteps; range +=  1.00 / sswsteps;}
+			if ( wswsteps > 0.5 ){ elev += wsw / wswsteps; range +=  1.00 / wswsteps;}
+			if ( wnwsteps > 0.5 ){ elev += wnw / wnwsteps; range +=  1.00 / wnwsteps;}
+			if ( nnwsteps > 0.5 ){ elev += nnw / nnwsteps; range +=  1.00 / nnwsteps;}
+									
+			//temp = ( elev / range ) + 0.5 ;
+			temp = ( elev / range );
+			//+ 0.5 ;
+			//if ( temp > 10000 ) temp = 10000;
+			//if ( temp <     0 ) temp =     0;
+			
+			#ifdef _DEBUG2_
+				//printf("%g %g %g \n",temp,elev,range);
+			#endif
+
+			*(image3+samps*i+j) = temp ;			
+		}
+	}
+
+
+
+	for ( i = 0; i < lines; i++ ){
+		for ( j = 0; j < samps; j++ ){
+			*(image2+samps*i+j)= *(image3+samps*i+j);
+		}
+	}
+
+
+	for ( i = 0; i < lines; i++ ){
+		for ( j = 0; j < samps; j++ ){
+			if ( *(image2+samps*i+j) == 0 ) goto again2;
+		}
+	}
+	
+	if ( smooth == 0 ) goto there2;		
+		
+		
+/************************ SMOOTH THE RESULT ***********************/		
+		
+	image4 = (double*) xmalloc( lines*samps*sizeof(double));
+	memcpy(image4,image3,lines*samps*sizeof(double));
+
+
+	for ( i = 0; i < lines; i++ ) {
+		for ( j = 0; j < samps; j++ ) {
+			if ( *(image4+i*samps+j) != 0 ) { *(image3+i*samps+j) = *(image2+i*samps+j) ; continue; }
+
+
+			for ( k = 1; k < infinit; k++ ) { /* Find the smallest box size with data */ 
+				for ( ii = i-k; ii <= i+k; ii++ ){
+					if ( ii <      0 ) continue;
+					if ( ii >= lines ) break;
+					for ( jj = j-k; jj <= j+k; jj++ ) {
+						if ( jj <      0 ) continue;
+						if ( jj >= samps ) continue;
+						if ( *(image4+ii*samps+jj) != 0 ) goto k_nowset;
+					}
+				}
+			}
+		
+			k_nowset:
+			k = k / 4; if ( k < 1 ) k = 1; /* Errrrr.  Make it fourth size */
+			sum = 0;
+			for ( ii = i-k; ii <= i+k; ii++ ) {
+				if ( ii <      0 ) iii = -1 - ii; else iii = ii;
+				if ( ii >= lines ) iii = lines - (ii - lines + 1);
+				for ( jj = j-k; jj <= j+k; jj++ ) {
+					if ( jj <      0 ) jjj = -1 - jj; else jjj = jj;
+					if ( jj >= samps ) jjj = samps - (jj - samps + 1);
+					sum += *(image2+samps*iii+jjj) ;
+				}
+			}
+			k = (k*2)+1;
+			*(image3+samps*i+j) = ( sum / k / k ) ;//+ 0.5;
+		}
+
+	}
+
+		
+there2:		
+
+
+	/*Allocate output image: */
+	imageout=(double*)xmalloc(samps*lines*sizeof(double));
+	memcpy(imageout,image3,lines*samps*sizeof(double));
+
+	time(&t2);	
+	
+	#ifdef _DEBUG2_
+		printf( "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b" );
+		printf("Number of zeroes remaining:          0\n\n");
+		printf ( "\n");
+	#endif
+	
+	end:
+
+	/*Assign output pointers: */
+	*pimageout=imageout;
+
+	return 1;
+	
+}
Index: /issm/trunk-jpl-damage/src/c/modules/HoleFillerx/HoleFillerx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/HoleFillerx/HoleFillerx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/HoleFillerx/HoleFillerx.h	(revision 11330)
@@ -0,0 +1,16 @@
+/*
+	HoleFillerx.h
+*/
+
+
+#ifndef HOLEFILLERX_H
+#define HOLEFILLERX_H
+
+//#define _DEBUG_
+//#define _DEBUG2_
+
+/* local prototypes: */
+int HoleFillerx(double** pimageout,double* imagein, int lines,int samp,int smooth);
+	
+#endif /* HOLEFILLERX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.cpp	(revision 11330)
@@ -0,0 +1,26 @@
+/*!\file IceVolumex
+ * \brief: compute total ice volume
+ */
+
+#include "./IceVolumex.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void IceVolumex(double* pV, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+
+	double local_ice_volume = 0;
+	double total_ice_volume;
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		local_ice_volume+=element->IceVolume();
+	}
+	MPI_Reduce(&local_ice_volume,&total_ice_volume,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&total_ice_volume,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+
+	/*Assign output pointers: */
+	*pV=total_ice_volume;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  IceVolumex.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _ICEVOLUMEX_H
+#define _ICEVOLUMEX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void IceVolumex(double* pV, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp	(revision 11330)
@@ -0,0 +1,20 @@
+/*!\file InputArtificialNoisex
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./InputArtificialNoisex.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void InputArtificialNoisex( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int enum_name,double min,double max){
+
+	int i;
+
+	/*Update elements, nodes, loads and materials from inputs: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->InputArtificialNoise(enum_name,min,max);
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  InputArtificialNoisex.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _INPUTARTIFICIALNOISEX_H
+#define _INPUTARTIFICIALNOISEX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void	InputArtificialNoisex( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int enum_name,double min,double max);
+
+#endif  /* _UPDATEINPUTSFROMVECTORXX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 11330)
@@ -0,0 +1,18 @@
+/*!\file InputControlUpdatex
+ * \brief: Y=Y+aX operation on inputs.
+ */
+
+#include "./InputControlUpdatex.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void InputControlUpdatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,double 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=(Element*)elements->GetObjectByOffset(i);
+		element->InputControlUpdate(scalar,save_parameter);
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InputControlUpdatex/InputControlUpdatex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputControlUpdatex/InputControlUpdatex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputControlUpdatex/InputControlUpdatex.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  InputControlUpdatex.h
+ * \brief header file for field extrusion
+ */ 
+
+#ifndef _INPUTCONTROLUPDATEX_H
+#define _INPUTCONTROLUPDATEX_H
+
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void InputControlUpdatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters, double scalar,bool save_parameter);
+
+#endif 
Index: /issm/trunk-jpl-damage/src/c/modules/InputConvergencex/InputConvergencex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputConvergencex/InputConvergencex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputConvergencex/InputConvergencex.cpp	(revision 11330)
@@ -0,0 +1,46 @@
+/*!\file InputConvergencex
+ */
+
+#include "./InputConvergencex.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+bool InputConvergencex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int* enums, int num_enums, int* criterionenums, double* criterionvalues,int num_criterionenums){
+
+	/*intermediary:*/
+	int         i;
+	bool        converged;
+	int         num_notconverged=0;
+	int         total_notconverged;
+	double     *eps       = NULL;
+	Element*    element=NULL;
+
+	/*allocate dynamic memory: */
+	eps=(double*)xmalloc(num_criterionenums*sizeof(double));
+
+	/*Go through elements, and ask them to do the job: */
+	for(i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		converged=element->InputConvergence(eps,enums,num_enums,criterionenums,criterionvalues,num_criterionenums);
+		if(!converged) num_notconverged++;
+	}
+
+	/*In parallel, we need to gather the converged status: */
+	#ifdef _PARALLEL_
+	MPI_Allreduce ( (void*)&num_notconverged,(void*)&total_notconverged,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
+	num_notconverged=total_notconverged;
+	#endif
+	_printf_(VerboseConvergence(),"      #elements above convergence criterion = %i\n",num_notconverged);
+
+	/*Free ressources:*/
+	xfree((void**)&eps);
+
+	/*return: */
+	if (num_notconverged){
+		return false;}
+	else{
+		return true;}
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InputConvergencex/InputConvergencex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputConvergencex/InputConvergencex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputConvergencex/InputConvergencex.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  InputConvergencex.h
+ */ 
+
+#ifndef _INPUTCONVERGENCEX_H
+#define _INPUTCONVERGENCEX_H
+
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+bool InputConvergencex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int* enums, int num_enums, int* criterionenums, double* criterionvalues,int num_criterionenums);
+
+#endif  /* _INPUTCONVERGENCEX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/InputDuplicatex/InputDuplicatex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputDuplicatex/InputDuplicatex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputDuplicatex/InputDuplicatex.cpp	(revision 11330)
@@ -0,0 +1,24 @@
+/*!\file InputDuplicatex
+ * \brief: duplicte  an input inside the elements, onto another, and wipe it off.
+ */
+
+#include "./InputDuplicatex.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void InputDuplicatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int original_enum, int new_enum){
+	
+	/*Go through elemnets, and ask to reinitialie the input: */
+	int      i;
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->InputDuplicate(original_enum,new_enum);
+	}
+	for(i=0;i<materials->Size();i++){
+		Material* material=(Material*)materials->GetObjectByOffset(i);
+		//material->InputDuplicate(original_enum,new_enum);
+	}
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InputDuplicatex/InputDuplicatex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputDuplicatex/InputDuplicatex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputDuplicatex/InputDuplicatex.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  InputDuplicatex.h
+ * \brief header file for field extrusion
+ */ 
+
+#ifndef _INPUTDUPLICATEX_H
+#define _INPUTDUPLICATEX_H
+
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void InputDuplicatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int reinitialized_enum, int original_enum);
+
+#endif  /* _INPUTDUPLICATEX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/InputScalex/InputScalex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputScalex/InputScalex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputScalex/InputScalex.cpp	(revision 11330)
@@ -0,0 +1,22 @@
+/*!\file InputScalex
+ * \brief: duplicte  an input inside the elements, onto another, and wipe it off.
+ */
+
+#include "./InputScalex.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void InputScalex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type, double scale_factor){
+
+	/*intermediary:*/
+	int      i;
+
+	/*Go through elemnets, and ask to reinitialie the input: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->InputScale(enum_type,scale_factor);
+	}
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InputScalex/InputScalex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputScalex/InputScalex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputScalex/InputScalex.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  InputScalex.h
+ * \brief header file for field extrusion
+ */ 
+
+#ifndef _SCALEINPUTX_H
+#define _SCALEINPUTX_H
+
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void InputScalex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type, double scale_factor);
+
+#endif  /* _SCALEINPUTX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/InputToResultx/InputToResultx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputToResultx/InputToResultx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputToResultx/InputToResultx.cpp	(revision 11330)
@@ -0,0 +1,24 @@
+/*!\file InputToResultx
+ * \brief: transfer an input to the results  dataset inside the elements
+ */
+
+#include "./InputToResultx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void InputToResultx(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type,int step, double time){
+
+	/*intermediary:*/
+	int      i;
+	Element *element = NULL;
+
+	/*Go through elemnets, and ask each element to transfer the enum_type input into the results dataset, with step and time information: */
+	for(i=0;i<elements->Size();i++){
+
+		element=(Element*)elements->GetObjectByOffset(i);
+		element->InputToResult(enum_type,step,time);
+	}
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InputToResultx/InputToResultx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputToResultx/InputToResultx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputToResultx/InputToResultx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  InputToResultx.h
+ * \brief header file for field extrusion
+ */ 
+
+#ifndef _INPUTTORESULTX_H
+#define _INPUTTORESULTX_H
+
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void InputToResultx(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type,int step=1, double time=0);
+
+#endif  /* _INPUTTORESULTX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 11330)
@@ -0,0 +1,71 @@
+/*!\file InputUpdateFromConstantx
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./InputUpdateFromConstantx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool   constant, int name){
+
+	int i;
+
+	/*Elements and loads drive the update: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->InputUpdateFromConstant(constant,name);
+	}
+
+	for(i=0;i<loads->Size();i++){
+		Load* load=(Load*)loads->GetObjectByOffset(i);
+		load->InputUpdateFromConstant(constant,name);
+	}
+	
+	for(i=0;i<materials->Size();i++){
+		Material* material=(Material*)materials->GetObjectByOffset(i);
+		material->InputUpdateFromConstant(constant,name);
+	}
+}
+void InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int    constant, int name){
+	
+	int i;
+
+	/*Elements and loads drive the update: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->InputUpdateFromConstant(constant,name);
+	}
+
+	for(i=0;i<loads->Size();i++){
+		Load* load=(Load*)loads->GetObjectByOffset(i);
+		load->InputUpdateFromConstant(constant,name);
+	}
+	
+	for(i=0;i<materials->Size();i++){
+		Material* material=(Material*)materials->GetObjectByOffset(i);
+		material->InputUpdateFromConstant(constant,name);
+	}
+}
+void InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double constant, int name){
+
+	int i;
+
+	/*Elements and loads drive the update: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->InputUpdateFromConstant(constant,name);
+	}
+
+	for(i=0;i<loads->Size();i++){
+		Load* load=(Load*)loads->GetObjectByOffset(i);
+		load->InputUpdateFromConstant(constant,name);
+	}
+	
+	for(i=0;i<materials->Size();i++){
+		Material* material=(Material*)materials->GetObjectByOffset(i);
+		material->InputUpdateFromConstant(constant,name);
+	}
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 11330)
@@ -0,0 +1,17 @@
+/*!\file:  InputUpdateFromConstantx.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _UPDATEINPUTSFROMCONSTANTXX_H
+#define _UPDATEINPUTSFROMCONSTANTXX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void		InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters, bool   constant, int name);
+void		InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters, int    constant, int name);
+void		InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters, double constant, int name);
+
+#endif  /* _UPDATEINPUTSFROMCONSTANTXX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 11330)
@@ -0,0 +1,111 @@
+/*!\file InputUpdateFromDakotax
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./InputUpdateFromDakotax.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../modules.h"
+
+void  InputUpdateFromDakotax(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials*  materials,Parameters* parameters,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: */
+	parameters->FindParam(&npart,QmuNumberofpartitionsEnum);
+	parameters->FindParam(&qmu_part,&dummy,QmuPartitionEnum);
+	numberofvertices=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=(double*)xmalloc(npart*sizeof(double));
+			for(j=0;j<npart;j++){
+				distributed_values[j]=variables[i+j];
+			}
+
+			/*Now, pick up the parameter corresponding to root: */
+			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(MPI_COMM_WORLD,"Parameter matrix:");
+				PetscSynchronizedFlush(MPI_COMM_WORLD);
+				for(l=0;l<ncols;l++){
+					PetscSynchronizedPrintf(MPI_COMM_WORLD," time %i\n",l);
+					PetscSynchronizedFlush(MPI_COMM_WORLD);
+
+					for(k=0;k<numberofvertices;k++){
+						PetscSynchronizedPrintf(MPI_COMM_WORLD," node %i value %g\n",k+1,*(parameter+k*ncols+l));
+						PetscSynchronizedFlush(MPI_COMM_WORLD);
+					}
+				}
+				PetscSynchronizedPrintf(MPI_COMM_WORLD," descriptor: %s root %s enum: %i\n",descriptor,root,StringToEnumx(root));
+				PetscSynchronizedFlush(MPI_COMM_WORLD);
+			#endif
+			  
+
+			/*Update inputs using the parameter matrix: */
+			InputUpdateFromMatrixDakotax( elements,nodes, vertices,loads, materials,  parameters, 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: */
+			xfree((void**)&parameter);
+			xfree((void**)&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( elements,nodes, vertices,loads, materials,  parameters, variables[i],StringToEnumx(descriptor));
+		}
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&qmu_part);
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  InputUpdateFromDakotax.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _INPUTUPDATEFROMDAKOTAXX_H
+#define _INPUTUPDATEFROMDAKOTAXX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+void  InputUpdateFromDakotax(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials*  materials,Parameters* parameters,double* variables,char* *variables_descriptors,int numvariables);
+
+#endif  /* _INPUTUPDATEFROMDAKOTAXX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp	(revision 11330)
@@ -0,0 +1,41 @@
+/*!\file InputUpdateFromMatrixDakotax
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./InputUpdateFromMatrixDakotax.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../modules.h"
+
+void InputUpdateFromMatrixDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* matrix,int nrows,int ncols, int name, int type){
+
+	int i;
+	int numberofvertices;
+
+	numberofvertices=vertices->NumberOfVertices();
+
+	if((ncols==1) && (nrows==numberofvertices)) InputUpdateFromVectorDakotax( elements,nodes, vertices,loads, materials,  parameters,matrix, name,type);
+	else{
+
+		/*Update elements, nodes, loads and materials from inputs: */
+		for(i=0;i<elements->Size();i++){
+			Element* element=(Element*)elements->GetObjectByOffset(i);
+			element->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
+		}
+		for(i=0;i<nodes->Size();i++){
+			Node* node=(Node*)nodes->GetObjectByOffset(i);
+			node->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
+		}
+		for(i=0;i<loads->Size();i++){
+			Load* load=(Load*)loads->GetObjectByOffset(i);
+			load->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
+		}
+		for(i=0;i<materials->Size();i++){
+			Material* material=(Material*)materials->GetObjectByOffset(i);
+			material->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
+		}
+	}
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  InputUpdateFromMatrixDakotax.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _UPDATEINPUTSFROMMATRIXDAKOTAXX_H
+#define _UPDATEINPUTSFROMMATRIXDAKOTAXX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void InputUpdateFromMatrixDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* matrix,int nrows,int ncols, int name, int type);
+
+#endif  /* _UPDATEINPUTSFROMMATRIXDAKOTAXX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 11330)
@@ -0,0 +1,39 @@
+/*!\file InputUpdateFromSolutionx
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./InputUpdateFromSolutionx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vec solution){
+
+	double* serial_solution=NULL;
+
+	/*Serialize solution, so that elements can index into it on every CPU: */
+	VecToMPISerial(&serial_solution,solution);
+
+	/*Call overloaded form of InputUpdateFromSolutionx: */
+	InputUpdateFromSolutionx( elements, nodes,  vertices,  loads,  materials,  parameters,serial_solution);
+
+	/*Free ressources:*/
+	xfree((void**)&serial_solution);
+
+}
+
+
+void InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* solution){
+
+	/*Intermediary*/
+	int i;
+	Element* element=NULL;
+
+	/*Elements drive the update: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		element->InputUpdateFromSolution(solution);
+	}
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 11330)
@@ -0,0 +1,20 @@
+/*!\file:  InputUpdateFromSolutionx.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _UPDATEINPUTSFROMSOLUTIONXX_H
+#define _UPDATEINPUTSFROMSOLUTIONXX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void		InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vec solution);
+void        InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* solution);
+
+//with timestep
+void		InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vec solution,int timestep);
+void        InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* solution, int timestep);
+
+#endif  /* _UPDATEINPUTSFROMSOLUTIONXX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 11330)
@@ -0,0 +1,91 @@
+/*!\file InputUpdateFromVectorDakotax
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./InputUpdateFromVectorDakotax.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vec vector, int name, int type){
+
+	double* serial_vector=NULL;
+
+	VecToMPISerial(&serial_vector,vector);
+
+	InputUpdateFromVectorDakotax( elements,nodes, vertices, loads, materials, parameters,serial_vector,name, type);
+
+	/*Free ressources:*/
+	xfree((void**)&serial_vector);
+}
+
+	
+void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vector, int name, int type){
+
+	int i;
+
+	/*Update elements, nodes, loads and materials from inputs: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->InputUpdateFromVectorDakota(vector,name,type);
+	}
+	for(i=0;i<nodes->Size();i++){
+		Node* node=(Node*)nodes->GetObjectByOffset(i);
+		node->InputUpdateFromVectorDakota(vector,name,type);
+	}
+	for(i=0;i<loads->Size();i++){
+		Load* load=(Load*)loads->GetObjectByOffset(i);
+		load->InputUpdateFromVectorDakota(vector,name,type);
+	}
+	for(i=0;i<materials->Size();i++){
+		Material* material=(Material*)materials->GetObjectByOffset(i);
+		material->InputUpdateFromVectorDakota(vector,name,type);
+	}
+}
+
+void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int* vector, int name, int type){
+	
+	int i;
+
+	/*Update elements, nodes, loads and materials from inputs: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->InputUpdateFromVectorDakota(vector,name,type);
+	}
+	for(i=0;i<nodes->Size();i++){
+		Node* node=(Node*)nodes->GetObjectByOffset(i);
+		node->InputUpdateFromVectorDakota(vector,name,type);
+	}
+	for(i=0;i<loads->Size();i++){
+		Load* load=(Load*)loads->GetObjectByOffset(i);
+		load->InputUpdateFromVectorDakota(vector,name,type);
+	}
+	for(i=0;i<materials->Size();i++){
+		Material* material=(Material*)materials->GetObjectByOffset(i);
+		material->InputUpdateFromVectorDakota(vector,name,type);
+	}
+}
+
+void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool* vector, int name, int type){
+
+	int i;
+
+	/*Update elements, nodes, loads and materials from inputs: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->InputUpdateFromVectorDakota(vector,name,type);
+	}
+	for(i=0;i<nodes->Size();i++){
+		Node* node=(Node*)nodes->GetObjectByOffset(i);
+		node->InputUpdateFromVectorDakota(vector,name,type);
+	}
+	for(i=0;i<loads->Size();i++){
+		Load* load=(Load*)loads->GetObjectByOffset(i);
+		load->InputUpdateFromVectorDakota(vector,name,type);
+	}
+	for(i=0;i<materials->Size();i++){
+		Material* material=(Material*)materials->GetObjectByOffset(i);
+		material->InputUpdateFromVectorDakota(vector,name,type);
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 11330)
@@ -0,0 +1,18 @@
+/*!\file:  InputUpdateFromVectorDakotax.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _UPDATEINPUTSFROMVECTORDAKOTAXX_H
+#define _UPDATEINPUTSFROMVECTORDAKOTAXX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void	InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vec vector, int name,int type);
+void	InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,double* vector, int name,int type);
+void	InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int* vector, int name,int type);
+void	InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,bool* vector, int name,int type);
+
+#endif  /* _UPDATEINPUTSFROMVECTORDAKOTAXX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 11330)
@@ -0,0 +1,91 @@
+/*!\file InputUpdateFromVectorx
+ * \brief: update datasets using  parameter inputs
+ */
+
+#include "./InputUpdateFromVectorx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vec vector, int name, int type){
+
+	double* serial_vector=NULL;
+
+	VecToMPISerial(&serial_vector,vector);
+
+	InputUpdateFromVectorx( elements,nodes, vertices, loads, materials, parameters,serial_vector,name, type);
+
+	/*Free ressources:*/
+	xfree((void**)&serial_vector);
+}
+
+	
+void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vector, int name, int type){
+
+	int i;
+
+	/*Update elements, nodes, loads and materials from inputs: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->InputUpdateFromVector(vector,name,type);
+	}
+	for(i=0;i<nodes->Size();i++){
+		Node* node=(Node*)nodes->GetObjectByOffset(i);
+		node->InputUpdateFromVector(vector,name,type);
+	}
+	for(i=0;i<loads->Size();i++){
+		Load* load=(Load*)loads->GetObjectByOffset(i);
+		load->InputUpdateFromVector(vector,name,type);
+	}
+	for(i=0;i<materials->Size();i++){
+		Material* material=(Material*)materials->GetObjectByOffset(i);
+		material->InputUpdateFromVector(vector,name,type);
+	}
+}
+
+void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int* vector, int name, int type){
+	
+	int i;
+
+	/*Update elements, nodes, loads and materials from inputs: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->InputUpdateFromVector(vector,name,type);
+	}
+	for(i=0;i<nodes->Size();i++){
+		Node* node=(Node*)nodes->GetObjectByOffset(i);
+		node->InputUpdateFromVector(vector,name,type);
+	}
+	for(i=0;i<loads->Size();i++){
+		Load* load=(Load*)loads->GetObjectByOffset(i);
+		load->InputUpdateFromVector(vector,name,type);
+	}
+	for(i=0;i<materials->Size();i++){
+		Material* material=(Material*)materials->GetObjectByOffset(i);
+		material->InputUpdateFromVector(vector,name,type);
+	}
+}
+
+void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool* vector, int name, int type){
+
+	int i;
+
+	/*Update elements, nodes, loads and materials from inputs: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->InputUpdateFromVector(vector,name,type);
+	}
+	for(i=0;i<nodes->Size();i++){
+		Node* node=(Node*)nodes->GetObjectByOffset(i);
+		node->InputUpdateFromVector(vector,name,type);
+	}
+	for(i=0;i<loads->Size();i++){
+		Load* load=(Load*)loads->GetObjectByOffset(i);
+		load->InputUpdateFromVector(vector,name,type);
+	}
+	for(i=0;i<materials->Size();i++){
+		Material* material=(Material*)materials->GetObjectByOffset(i);
+		material->InputUpdateFromVector(vector,name,type);
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 11330)
@@ -0,0 +1,18 @@
+/*!\file:  InputUpdateFromVectorx.h
+ * \brief header file for updating datasets from inputs
+ */ 
+
+#ifndef _UPDATEINPUTSFROMVECTORXX_H
+#define _UPDATEINPUTSFROMVECTORXX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vec vector, int name,int type);
+void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,double* vector, int name,int type);
+void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int* vector, int name,int type);
+void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,bool* vector, int name,int type);
+
+#endif  /* _UPDATEINPUTSFROMVECTORXX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 11330)
@@ -0,0 +1,315 @@
+/*!\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 "../../include/include.h"
+/*}}}*/
+
+/*InterpFromGridToMeshx{{{*/
+int InterpFromGridToMeshx( Vec* 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: */
+	Vec data_mesh=NULL;
+	
+	/*Intermediary*/
+	double* x=NULL;
+	double* y=NULL;
+	double  x_grid,y_grid;
+	int     i;
+
+	/*threading: */
+	InterpFromGridToMeshxThreadStruct gate;
+	int num=1;
+	#ifdef _MULTITHREADING_
+	num=_NUMTHREADS_;
+	#endif
+
+	/*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=NewVec(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=(double*)xmalloc(N*sizeof(double));
+		y=(double*)xmalloc(M*sizeof(double));
+		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=(double*)xmalloc(N*sizeof(double));
+		y=(double*)xmalloc(M*sizeof(double));
+		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: */
+	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.M=M;
+	gate.N=N;
+	gate.interp=interpenum;
+
+	/*launch the thread manager with InterpFromGridToMeshxt as a core: */
+	LaunchThread(InterpFromGridToMeshxt,(void*)&gate,num);
+
+	/*Assign output pointers:*/
+	*pdata_mesh=data_mesh;
+}
+/*}}}*/
+/*InterpFromGridToMeshxt {{{1*/
+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;
+	Vec     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;
+
+	/*partition loop across threads: */
+	PartitionRange(&i0,&i1,nods,num_threads,my_thread);
+	for (i=i0;i<i1;i++) {
+
+		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 %s not supported yet\n",EnumToStringx(interpenum));
+					return NULL; /*WARNING: no error because it would blow up the multithreading!*/
+			}
+			if(isnan(data_value)) data_value=default_value;
+		}
+		else{
+			data_value=default_value;
+		}
+
+		VecSetValue(data_mesh,i,data_value,INSERT_VALUES);
+	}
+}/*}}}*/
+
+/*findindices {{{1*/
+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{{{1*/
+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{{{1*/
+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{{{1*/
+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/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file InterpFromGridToMeshx.h
+ * \brief: header file for Data interpolation routines.
+ */
+
+#ifndef _INTERPFROMGRIDTOMESHX_H
+#define _INTERPFROMGRIDTOMESHX_H
+
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.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;
+	Vec     data_mesh;
+} InterpFromGridToMeshxThreadStruct;
+
+int    InterpFromGridToMeshx( Vec* 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/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 11330)
@@ -0,0 +1,116 @@
+/*!\file:  InterpFromMesh2dx.cpp
+ * \brief  "c" core code for interpolating values from a structured grid.
+ */ 
+
+#include "./InterpFromMesh2dx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../objects/objects.h"
+#include "../modules.h"
+
+int InterpFromMesh2dx( Vec* pdata_prime,double* index_data, double* x_data, double* y_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, int nods_prime,
+		double* default_values,int num_default_values,Contour** contours,int numcontours){
+
+	
+	/*Output*/
+	Vec data_prime=NULL;
+
+	/*Intermediary*/
+	int i,j;
+	int interpolation_type;
+	bool debug;
+	double area;
+	double area_1,area_2,area_3;
+	double data_value;
+	double xmin,xmax;
+	double ymin,ymax;
+
+	/*contours: */
+	Vec    vec_incontour=NULL;
+	double*    incontour=NULL;
+
+	/*threading: */
+	InterpFromMesh2dxThreadStruct gate;
+	int num=1;
+
+	#ifdef _MULTITHREADING_
+	num=_NUMTHREADS_;
+	#endif
+
+	/*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=NewVec(nods_prime);
+	if(num_default_values){
+		if(num_default_values==1)for (i=0;i<nods_prime;i++) VecSetValue(data_prime,i,default_values[0],INSERT_VALUES);
+		else for (i=0;i<nods_prime;i++) VecSetValue(data_prime,i,default_values[i],INSERT_VALUES);
+	}
+
+	/*Build indices of contour: */
+	if(numcontours){
+		ContourToNodesx( &vec_incontour,x_prime,y_prime,nods_prime,contours,numcontours,1);
+		VecToMPISerial(&incontour,vec_incontour);
+	}
+	else{
+		 incontour=(double*)xmalloc(nods_prime*sizeof(double));
+		 for (i=0;i<nods_prime;i++) incontour[i]=1;
+	}
+
+	/*initialize thread parameters: */
+	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,num);
+
+	/*Assign output pointers:*/
+	 xfree((void**)&incontour);
+	*pdata_prime=data_prime;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 11330)
@@ -0,0 +1,41 @@
+/*!\file InterpFromMesh2dx.h
+ * \brief: header file for Data interpolation routines.
+ */
+
+#ifndef _INTERPFROMMESH2DX_H
+#define _INTERPFROMMESH2DX_H
+
+#include "../../objects/objects.h"
+#include "../../toolkits/toolkits.h"
+
+
+/*threading: */
+typedef struct{
+
+	int interpolation_type;
+	bool debug;
+	int  nels_data;
+	double* index_data;
+	double* x_data;
+	double* y_data;
+	double* data;
+	double xmin,xmax;
+	double ymin,ymax;
+	int    nods_prime;
+	Vec    data_prime;
+	double* x_prime;
+	double* y_prime;
+	double* default_values;
+	int     num_default_values;
+	double*    incontour;
+
+
+} InterpFromMesh2dxThreadStruct;
+
+int InterpFromMesh2dx( Vec* pdata_prime,double* index_data, double* x_data, double* y_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, int nods_prime,
+		double* default_values,int num_default_values,Contour** contours,int numcontours);
+
+void* InterpFromMesh2dxt(void* vInterpFromMesh2dxThreadStruct);
+
+#endif /* _INTERPFROMMESH2DX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 11330)
@@ -0,0 +1,129 @@
+/*!\file:  InterpFromMesh2dxt.cpp
+ * \brief  thread core for InterpFromMesh2dxt code
+ */ 
+
+#include "./InterpFromMesh2dx.h"
+#include "../../shared/shared.h"
+
+void* InterpFromMesh2dxt(void* vpthread_handle){
+
+	/*gate variables :*/
+	InterpFromMesh2dxThreadStruct* gate=NULL;
+	pthread_handle* handle=NULL;
+	int     my_thread;
+	int     num_threads;
+	
+	int interpolation_type;
+	bool debug;
+	int  nels_data;
+	double* index_data=NULL;
+	double* x_data=NULL;
+	double* y_data=NULL;
+	double* data=NULL;
+	double xmin,xmax;
+	double ymin,ymax;
+	int    nods_prime;
+	Vec    data_prime=NULL;
+	double* x_prime=NULL;
+	double* y_prime=NULL;
+	double* default_values=NULL;
+	int     num_default_values;
+	double*    incontour=NULL;
+
+	/*intermediary: */
+	int     i0;
+	int     i1;
+	int     i,j;
+	double  area;
+	double  area_1,area_2,area_3;
+	double  data_value;
+
+	/*recover handle and gate: */
+	handle=(pthread_handle*)vpthread_handle;
+	gate=(InterpFromMesh2dxThreadStruct*)handle->gate;
+	my_thread=handle->id;
+	num_threads=handle->num;
+	
+	/*recover parameters :*/
+	interpolation_type=gate->interpolation_type;
+	debug=gate->debug;
+	nels_data=gate->nels_data;
+	index_data=gate->index_data;
+	x_data=gate->x_data;
+	y_data=gate->y_data;
+	data=gate->data;
+	xmin=gate->xmin;
+	xmax=gate->xmax;
+	ymin=gate->ymin;
+	ymax=gate->ymax;
+	nods_prime=gate->nods_prime;
+	data_prime=gate->data_prime;
+	x_prime=gate->x_prime;
+	y_prime=gate->y_prime;
+	default_values=gate->default_values;
+	num_default_values=gate->num_default_values;
+	incontour=gate->incontour;
+
+	/*partition loop across threads: */
+	PartitionRange(&i0,&i1,nels_data,num_threads,my_thread);
+
+	/*Loop over the elements*/
+	if (debug && my_thread==0) printf("      interpolation progress:   %5.2lf %%",0.0);
+
+	for (i=i0;i<i1;i++){
+
+		/*display current iteration*/
+		if (debug && my_thread==0 && fmod((double)i,(double)100)==0) printf("\b\b\b\b\b\b\b%5.2lf %%",(double)i/nels_data*100*num_threads);
+
+		/*if 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 (isnan(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*/
+					VecSetValue(data_prime,j,data_value,INSERT_VALUES);
+				}
+			}
+		}
+	}
+	if (debug && my_thread==0) printf("\b\b\b\b\b\b\b%5.2lf %%\n",100.0);
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 11330)
@@ -0,0 +1,176 @@
+/*!\file:  InterpFromMeshToGridx.cpp
+ * \brief  "c" core code for interpolating values from a structured grid.
+ */ 
+
+#include "./InterpFromMeshToGridx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+
+void InterpFromMeshToGridx(double** px_m,double** py_m,double** pgriddata,double* index_mesh, double* x_mesh, double* y_mesh, int nods,int nels, double* data_mesh, int data_length, double xmin,double ymax,double xposting,double yposting,int nlines,int ncols,double default_value) {
+
+	/*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,ymin;
+	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=(double*)xcalloc(nlines*ncols,sizeof(double));
+	x_grid=(double*)xcalloc(ncols,sizeof(double));
+	y_grid=(double*)xcalloc(nlines,sizeof(double));
+
+	/*Set debug to 1 if there are lots of elements*/
+	debug=(bool)((double)ncols*nlines*nels >= pow((double)10,(double)10));
+
+	/*figure out if x or y are flipped*/
+	if (xposting<0) xflip=1;
+	else xflip=0;
+	if (yposting<0) yflip=1;
+	else yflip=0;
+
+	/*Compute coordinates lists*/
+	ymin=ymax-(nlines-1)*yposting;
+	for(i=0;i<nlines;i++)   y_grid[i]= ymin + yposting*i;
+	for(i=0;i<ncols; i++)   x_grid[i]= xmin + xposting*i;
+
+	/*Initialize coordintes and griddata*/
+	for(i=0;i<nlines;i++){
+		for(j=0;j<ncols; j++){
+			griddata[i*ncols+j]=default_value;
+		}
+	}
+	
+	/*Get extreme coordinates of the grid*/
+	if (xflip){
+		x_grid_min=x_grid[ncols-1]; x_grid_max=x_grid[0];
+	}
+	else{
+		x_grid_min=x_grid[0]; x_grid_max=x_grid[ncols-1];
+	}
+	if (yflip){
+		y_grid_min=y_grid[nlines-1]; y_grid_max=y_grid[0];
+	}
+	else{
+		y_grid_min=y_grid[0]; y_grid_max=y_grid[nlines-1];
+	}
+
+	/*Loop over the elements*/
+	if (debug) printf("      interpolation progress:   %5.2lf %%",0.0);
+	for (n=0;n<nels;n++){
+
+		/*display current iteration*/
+		if (debug && fmod((double)n,(double)100)==0) printf("\b\b\b\b\b\b\b%5.2lf %%",(double)n/nels*100);
+
+		/*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, (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, (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, (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, (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 (isnan(data_value)) data_value=default_value;
+
+					/*insert value and go to the next point*/
+					griddata[i*ncols+j]=data_value;
+				}
+			}
+		}
+	}
+	if (debug) printf("\b\b\b\b\b\b\b%5.2lf %%\n",100.0);
+
+	/*Assign output pointers:*/
+	*pgriddata=griddata;
+	*px_m=x_grid;
+	*py_m=y_grid;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h	(revision 11330)
@@ -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/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 11330)
@@ -0,0 +1,146 @@
+/*!\file InterpFromMeshToMesh2dx
+ */
+
+#include "./InterpFromMeshToMesh2dx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../objects/objects.h"
+#include "../modules.h"
+
+using namespace bamg;
+using namespace std;
+
+int InterpFromMeshToMesh2dx(double** pdata_interp,double* index_data,double* x_data,double* y_data,int nods_data,int nels_data,
+			double* data,int data_rows,int data_cols,double* x_interp,double* y_interp,int nods_interp,double* default_values,int num_default_values, Contour** contours, int numcontours){
+	
+	/*Output*/
+	double* data_interp=NULL;
+
+	/*Intermediary*/
+	R2     r;
+	I2     I;
+	int    i,j,k;
+	int    it;
+	int    i0,i1,i2;
+	double areacoord[3];
+	double aa,bb;
+	double data_value;
+	Icoor2 dete[3];
+	int verbose=0;
+
+	/*default values: */
+	Vec    vec_incontour=NULL;
+	double*    incontour=NULL;
+	bool   skip_bamg=false;
+
+
+	/*Checks*/
+	if (data_cols<=0){
+		_error_("data provided has a negative number of columns");
+	}
+	if (data_rows!=nods_data && data_rows!=nels_data){
+		_error_("data provided should have either %i or %i lines (not %i)",nods_data,nels_data,data_rows);
+	}
+	if((num_default_values) && (data_cols>1)){
+		_error_("data provided can only have 1 column if a default value is provided");
+	}
+	
+	/*If default values supplied, figure out which nodes are inside the contour, including the border of the contour: */
+	if(num_default_values){
+		ContourToNodesx( &vec_incontour,x_interp,y_interp,nods_interp,contours,numcontours,1);
+		VecToMPISerial(&incontour,vec_incontour);
+	}
+
+	/*Initialize output*/
+	if (verbose) printf("Initializing output vector\n");
+	data_interp=(double*)xmalloc(nods_interp*data_cols*sizeof(double));
+
+	// read background mesh 
+	if (verbose) printf("Reading mesh\n");
+	Mesh Th(index_data,x_data,y_data,nods_data,nels_data); 
+	Th.CreateSingleVertexToTriangleConnectivity();
+
+	//Loop over output nodes
+	if (verbose) printf("Loop over the nodes\n");
+	for(i=0;i<nods_interp;i++){
+		
+		/*reset skip_bamg: */
+		skip_bamg=false;
+
+		/*figure out if we should skip bamg logic: */
+		if(num_default_values){
+			if(!incontour[i]){
+				/*This node is not inside the contour. Skip Bamg logic and apply default value.: */
+				skip_bamg=true;
+			}
+		}
+
+		if(skip_bamg==false){
+
+			//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);
+
+			// internal point 
+			if (tb.det>0){ 
+				//Area coordinate
+				areacoord[0]= (double) dete[0]/tb.det;
+				areacoord[1]= (double) dete[1]/tb.det;
+				areacoord[2]= (double) dete[2]/tb.det;
+				//3 vertices of the triangle
+				i0=Th.GetId(tb[0]);
+				i1=Th.GetId(tb[1]);
+				i2=Th.GetId(tb[2]);
+				//triangle number
+				it=Th.GetId(tb);
+			}
+			//external point
+			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 (data_rows==nods_data){
+				for (j=0;j<data_cols;j++){
+					data_interp[i*data_cols+j]=areacoord[0]*data[data_cols*i0+j]+areacoord[1]*data[data_cols*i1+j]+areacoord[2]*data[data_cols*i2+j];
+				}
+			}
+			else{
+				for (j=0;j<data_cols;j++){
+					if (it<0 || it>=nels_data){
+						_error_("Triangle number %i not in [0 %i], because not correctly implemented yet... interpolate on grid first",it,nels_data);
+					}
+					data_interp[i*data_cols+j]=data[data_cols*it+j];
+				}
+			}
+		}
+		else{
+			if(num_default_values==1) data_interp[i]=default_values[0];
+			else data_interp[i]=default_values[i];
+		}
+	}
+
+	/*Assign output pointers:*/
+	if (verbose) printf("Assigning output\n");
+	*pdata_interp=data_interp;
+
+	/*No error return*/
+	return 1;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  InterpFromMeshToMesh2dx.h
+ * \brief header file for Bamg module
+ */ 
+
+#ifndef _INTERPFROMMESHTOMESH2DX_H
+#define _INTERPFROMMESHTOMESH2DX_H
+
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+int InterpFromMeshToMesh2dx(double** pdata_interp,double* index_data,double* x_data,double* y_data,int nods_data,int nels_data,
+			double* data,int data_rows,int data_cols,double* x_interp,double* y_interp,int nods_interp,double* default_values,int num_default_values,Contour** contours, int numcontours );
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 11330)
@@ -0,0 +1,138 @@
+/*!\file:  InterpFromMeshToMesh3dx.cpp
+ * \brief  "c" core code for interpolating values from a structured grid.
+ */ 
+
+#include "./InterpFromMeshToMesh3dx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+
+int InterpFromMeshToMesh3dx( Vec* 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*/
+	Vec 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=NewVec(nods_prime);
+	for (i=0;i<nods_prime;i++) VecSetValue(data_prime,i,default_value,INSERT_VALUES);
+
+	/*Loop over the elements*/
+	if (debug) printf("      interpolation progress:   %5.2lf %%",0.0);
+	for (i=0;i<nels_data;i++){
+
+		/*display current iteration*/
+		if (debug && fmod((double)i,(double)100)==0) printf("\b\b\b\b\b\b\b%5.2lf %%",(double)i/nels_data*100);
+
+		/*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 (isnan(data_value)) data_value=default_value;
+
+					/*insert value and go to the next point*/
+					VecSetValue(data_prime,j,data_value,INSERT_VALUES);
+				}
+			}
+		}
+	}
+	if (debug) printf("\b\b\b\b\b\b\b%5.2lf %%\n",100.0);
+
+	/*Assign output pointers:*/
+	*pdata_prime=data_prime;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file InterpFromMeshToMesh3dx.h
+ * \brief: header file for Data interpolation routines.
+ */
+
+#ifndef _INTERPFROMMESHTOMESH3DX_H
+#define _INTERPFROMMESHTOMESH3DX_H
+
+#include "../../toolkits/toolkits.h"
+
+int InterpFromMeshToMesh3dx( Vec* pdata_prime,double* index_data, double* x_data, double* y_data, double* z_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, double* z_prime, int nods_prime,double default_value);
+
+#endif /* _INTERPFROMMESHTOMESH3DX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 11330)
@@ -0,0 +1,108 @@
+/*!\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 "../../io/io.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,int vector_enum,int analysis_type){
+	
+
+	/*intermediary: */
+	int     i,j;
+	bool    transient     = false;
+
+	FILE   *fid           = NULL;
+	int     code          = 0;
+	int     vector_layout = 0;
+	int     counter;
+	int     nods;
+	double* times=NULL;
+	double* values=NULL;
+	bool    spcpresent=false;
+	int     count=0;
+	int     numberofvertices;
+
+	/*variables being fetched: */
+	double *doublevector  = NULL;
+	int     M,N;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+
+	/*First of, find the record for the enum, and get code  of data type: */
+	fid=iomodel->SetFilePointerToData(&code, &vector_layout,vector_enum);
+
+	if(code!=7)_error_("%s%s"," expecting a double vector for constraints with enum ",EnumToStringx(vector_enum));
+	if(vector_layout!=1)_error_("%s%s"," expecting a nodal vector for constraints with enum ",EnumToStringx(vector_enum));
+
+	/*Fetch vector:*/
+	iomodel->FetchData(&doublevector,&M,&N,vector_enum);
+
+	/*Transient or static?:*/
+	if(M==numberofvertices){
+		/*static: just create Constraints objects*/
+		count=0;
+	
+		/*Create Constraints from x,y,z: */
+		for (i=0;i<numberofvertices;i++){
+			
+			/*keep only this partition's nodes:*/
+			if((iomodel->my_vertices[i])){
+
+				if (!isnan(doublevector[i])){
+
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,doublevector[i],analysis_type));
+					count++;
+				}
+			}
+		}
+	}
+	else if (M==(numberofvertices+1)){
+		/*transient: create transient SpcTransient objects. Same logic, except we need to retrieve 
+		 * various times and values to initialize an SpcTransient object: */
+		count=0;
+
+		/*figure out times: */
+		times=(double*)xmalloc(N*sizeof(double));
+		for(j=0;j<N;j++){
+			times[j]=doublevector[(M-1)*N+j];
+		}
+		/*unit conversion: */
+		UnitConversion(times,N,ExtToIuEnum,TimeEnum);
+
+		/*Create constraints from x,y,z: */
+		for (i=0;i<numberofvertices;i++){
+			
+			/*keep only this partition's nodes:*/
+			if((iomodel->my_vertices[i])){
+
+				/*figure out times and values: */
+				values=(double*)xmalloc(N*sizeof(double));
+				spcpresent=false;
+				for(j=0;j<N;j++){
+					values[j]=doublevector[i*N+j];
+					if(!isnan(values[j]))spcpresent=true; //NaN means no spc by default
+				}
+
+				if(spcpresent){
+					constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,N,times,values,analysis_type));
+					count++;
+				}
+				xfree((void**)&values);
+			}
+		}
+	}
+	else{
+		_error_("Size of field %s not supported",EnumToStringx(vector_enum));
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&doublevector);
+	xfree((void**)&times);
+	xfree((void**)&values);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  IoModelToConstraintsx.h
+ */ 
+
+#ifndef _IOMODEL_TO_CONSTRAINTS_H_
+#define _IOMODEL_TO_CONSTRAINTS_H_
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,int vector_enum,int analysis_type);
+
+#endif  /* _IOMODELTOELEMENTINPUTX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/KMLFileReadx/KMLFileReadx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/KMLFileReadx/KMLFileReadx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/KMLFileReadx/KMLFileReadx.cpp	(revision 11330)
@@ -0,0 +1,67 @@
+/*!\file KMLFileReadx.cpp
+ */
+
+#include "./KMLFileReadx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+KML_Object* KMLFileReadx(FILE* fid){
+
+	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);
+	_printf_(true,"\nKMLFileReadx Module -- %s",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();
+		}
+
+//		_printf_(true,"%s\n",kstr);
+		xfree((void**)&kstr);
+	}
+
+	if (kxml) {
+		_printf_(true,"XML declaration:\n");
+		kxml->DeepEcho("  ");
+		delete kxml;
+	}
+	if (kdtd) {
+		_printf_(true,"DTD declaration (not yet implemented):\n");
+		kdtd->DeepEcho("  ");
+		delete kdtd;
+	}
+
+	clock1=clock();
+	time1 =time(NULL);
+	_printf_(true,"KMLFileReadx Module -- %f CPU seconds; %f elapsed seconds.\n\n",
+			 ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+
+	return(kfil);
+}
+
Index: /issm/trunk-jpl-damage/src/c/modules/KMLFileReadx/KMLFileReadx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/KMLFileReadx/KMLFileReadx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/KMLFileReadx/KMLFileReadx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  KMLFileReadx.h
+ * \brief header file for kml mesh writer routines.
+ */ 
+
+#ifndef _KMLFILEREADX_H
+#define _KMLFILEREADX_H
+
+#include <float.h>    /*  DBL_MAX  */
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+KML_Object* KMLFileReadx(FILE* fid);
+
+#endif  /* _KMLFILEREADX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 11330)
@@ -0,0 +1,373 @@
+/*!\file KMLMeshWritex
+ */
+
+#include "./KMLMeshWritex.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void KMLMeshWritex(int* ierror,
+				   char* name,
+				   char* notes,
+				   int* elem,int melem,int nelem,
+				   int* nodecon,int mncon,int nncon,
+				   double* lat, double* lng,
+				   int* part,
+				   double* data, int mdata, int ndata,
+				   double* cmap, int mcmap, int ncmap,
+				   FILE* fid){
+
+	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);
+	_printf_(true,"\nKMLMeshWritex Module -- %s",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) {
+		_printf_(true,"Writing %d Matlab colors as KML style templates.\n",mcmap);
+		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) {
+		_printf_(true,"Creating the node connectivity table.\n");
+		nncon=mxepg+1;
+		nodecon=(int *) xcalloc(mncon*nncon,sizeof(int));
+		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 %d columns.\n",mxepg);
+				}
+				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) {
+			_printf_(true,"Averaging nodal data to element data.\n");
+			edata=(double *) xcalloc(melem*ndata,sizeof(double));
+			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 %d rows.\n",mdata);
+	}
+
+/*  write folder for mesh  */
+
+	(kdoc ->feature   )->AddObject((Object*)KMLMeshElem(elem,melem,nelem,
+														nodecon,mncon,nncon,
+														lat,lng,
+														edata,
+														cmap,mcmap,ncmap));
+
+	if (edfree) xfree((void**)&edata);
+	if (ncfree) xfree((void**)&nodecon);
+	clock0a=clock();
+	time0a =time(NULL);
+	_printf_(true,"  Constructed kml document -- %f CPU seconds; %f elapsed seconds.\n\n",
+			 ((double)(clock0a-clock0))/CLOCKS_PER_SEC,difftime(time0a,time0));
+
+/*  write kml file  */
+
+	_printf_(true,"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_(true,"  Wrote kml file -- %f CPU seconds; %f elapsed seconds.\n\n",
+			 ((double)(clock0b-clock0a))/CLOCKS_PER_SEC,difftime(time0b,time0a));
+
+	_printf_(true,"Deleting kml document.\n");
+	delete kdoc;
+	clock0c=clock();
+	time0c =time(NULL);
+	_printf_(true,"  Deleted kml document -- %f CPU seconds; %f elapsed seconds.\n\n",
+			 ((double)(clock0c-clock0b))/CLOCKS_PER_SEC,difftime(time0c,time0b));
+
+	clock1=clock();
+	time1 =time(NULL);
+	_printf_(true,"KMLMeshWritex Module -- %f CPU seconds; %f elapsed seconds.\n\n",
+			 ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+
+	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  */
+
+	_printf_(true,"Writing %d tria elements as KML polygons.\n",melem);
+
+	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    =(double (*)[3]) xmalloc((nelem+1)*3*sizeof(double));
+
+/*  write the nodal coordinates as a linear ring  */
+
+		for (j=0; j<nelem; j++) {
+			kring->coords[j][0]=lng[elem[ipt]-1];
+			kring->coords[j][1]=lat[elem[ipt]-1];
+			kring->coords[j][2]=alt;
+			ipt++;
+		}
+		kring->coords[nelem][0]=kring->coords[0][0];
+		kring->coords[nelem][1]=kring->coords[0][1];
+		kring->coords[nelem][2]=kring->coords[0][2];
+//		kring->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))
+//			_printf_(true,"  %d tria elements written.\n",(i+1));
+	}
+	_printf_(true,"  %d tria elements written.\n",melem);
+
+	return(kfold);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.h	(revision 11330)
@@ -0,0 +1,30 @@
+/*!\file:  KMLMeshWritex.h
+ * \brief header file for kml mesh writer routines.
+ */ 
+
+#ifndef _KMLMESHWRITEX_H
+#define _KMLMESHWRITEX_H
+
+#include <float.h>    /*  DBL_MAX  */
+#include "../../Container/Container.h"
+#include "../../objects/objects.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/trunk-jpl-damage/src/c/modules/KMLOverlayx/KMLOverlayx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/KMLOverlayx/KMLOverlayx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/KMLOverlayx/KMLOverlayx.cpp	(revision 11330)
@@ -0,0 +1,97 @@
+/*!\file KMLOverlayx
+ */
+
+#include "./KMLOverlayx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.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);
+	_printf_(true,"\nKMLOverlayx Module -- %s",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  */
+
+	_printf_(true,"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_(true,"KMLOverlayx Module -- %f CPU seconds; %f elapsed seconds.\n\n",
+			 ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+
+	return;
+}
+
Index: /issm/trunk-jpl-damage/src/c/modules/KMLOverlayx/KMLOverlayx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/KMLOverlayx/KMLOverlayx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/KMLOverlayx/KMLOverlayx.h	(revision 11330)
@@ -0,0 +1,18 @@
+/*!\file:  KMLOverlayx.h
+ * \brief header file for kml file overlay routines.
+ */ 
+
+#ifndef _KMLOVERLAYX_H
+#define _KMLOVERLAYX_H
+
+#include <float.h>    /*  DBL_MAX  */
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void KMLOverlayx(int* ierror,
+				 double* lataxis, double* longaxis,
+				 int nimages, char** pimages,
+				 FILE* fid);
+
+#endif  /* _KMLOVERLAYX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 11330)
@@ -0,0 +1,71 @@
+/*!\file Kml2Expx
+ * \brief kml to exp conversion routines.
+ */
+
+#include "./Kml2Expx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../modules.h"
+
+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     i,iret=0;
+	double  *lat=NULL,*lon=NULL;
+
+	KML_Object*  kobj=NULL;
+
+	FILE*   fidi=NULL;
+	FILE*   fido=NULL;
+
+	clock_t clock0,clock1;
+	time_t  time0, time1;
+
+	clock0=clock();
+	time0 =time(NULL);
+	_printf_(true,"\nKml2Expx Module -- %s",ctime(&time0));
+
+/*  read kml file  */
+
+	fidi=fopen(filkml,"r");
+	if (!(kobj=KMLFileReadx(fidi)))
+		_error_("Error reading kml file.");
+	fclose(fidi);
+
+/*  open exp file  */
+
+	_printf_(true,"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_(true,"Kml2Expx Module -- %f CPU seconds; %f elapsed seconds.\n\n",
+			 ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+
+	return(iret);
+}
+
Index: /issm/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.h	(revision 11330)
@@ -0,0 +1,18 @@
+/*!\file:  Kml2Expx.h
+ * \brief header file for kml to exp conversion routines.
+ */ 
+
+#ifndef _KML2EXPX_H
+#define _KML2EXPX_H
+
+#include <float.h>    /*  DBL_MAX  */
+#include "../../Container/Container.h"
+#include "../../objects/objects.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/trunk-jpl-damage/src/c/modules/Ll2xyx/Ll2xyx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Ll2xyx/Ll2xyx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Ll2xyx/Ll2xyx.cpp	(revision 11330)
@@ -0,0 +1,128 @@
+/*!\file Ll2xyx.cpp
+ */
+
+#include "./Ll2xyx.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include <math.h>
+
+int Ll2xyx(double* x, double* y, double* lat, double* lon, int ncoord, int sgn){
+/*  This is a cpp conversion of the following:
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+*/
+	double  central_meridian,standard_parallel;
+
+	Ll2xydef(&central_meridian,&standard_parallel,sgn);
+
+	return(Ll2xyx(x,y,lat,lon,ncoord,sgn,central_meridian,standard_parallel));
+}
+
+int Ll2xyx(double* x, double* y, double* lat, double* lon, int ncoord, int sgn, double central_meridian, double standard_parallel){
+/*  This is a cpp conversion of the following:
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+*/
+
+	int     i,iret=0;
+	double  delta,slat;
+	double  cde,re,ex2,ex;
+	double  latitude,longitude;
+	double  T,rho,sl,tc,mc;
+
+	if((sgn!=1) && (sgn!=-1)) _error_("Sign should be either +1 or -1.\n");
+
+	delta = central_meridian;
+	slat  = standard_parallel;
+
+	/*  Conversion constant from degrees to radians  */
+	cde = 57.29577951;
+	/*  Radius of the earth in meters  */
+	re  = 6378.273*pow(10.,3.);
+	/*  Eccentricity of the Hughes ellipsoid squared  */
+	ex2 = 0.006693883;
+	/*  Eccentricity of the Hughes ellipsoid  */
+	ex  =  sqrt(ex2);
+
+	/*  loop over all the coordinate pairs  */
+	for(i=0; i<ncoord; i++){
+		latitude  = fabs(lat[i]) * PI/180.;
+		longitude = (lon[i] + delta) * PI/180.;
+
+		/*  compute X and Y in grid coordinates.  */
+		T = tan(PI/4.-latitude/2.) / pow(((1.-ex*sin(latitude))/(1.+ex*sin(latitude))),(ex/2.));
+
+		if ((90. - slat) < 1.e-5)
+			rho = 2.*re*T/sqrt(pow((1.+ex),(1.+ex))*pow((1.-ex),(1.-ex)));
+		else {
+			sl  = slat*PI/180.;
+			tc  = tan(PI/4.-sl/2.)/pow(((1.-ex*sin(sl))/(1.+ex*sin(sl))),(ex/2.));
+			mc  = cos(sl)/sqrt(1.0-ex2*(pow(sin(sl),2.)));
+			rho = re*mc*T/tc;
+		}
+
+		y[i]= -rho*(double)sgn*cos(sgn*longitude);
+		x[i]=  rho*(double)sgn*sin(sgn*longitude);
+
+		if (latitude>= PI/2.){
+			x[i] = 0.0;
+			y[i] = 0.0;
+			iret=1;
+		}
+	}
+	return(iret);
+}
+
+void Ll2xydef(double* pdelta, double* pslat, int sgn){
+/*  This is a cpp conversion of the following:
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+*/
+	bool    flag=true;
+
+	/*  Get central_meridian and standard_parallel depending on hemisphere  */
+	if (sgn ==  1) {
+		*pdelta= 45;
+		*pslat = 70;
+		_printf_(flag,"Info: creating coordinates in polar stereographic (Std Latitude: 70N Meridian: 45).\n");
+	}
+	else if (sgn == -1) {
+		*pdelta= 0;
+		*pslat = 71;
+		_printf_(flag,"Info: creating coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).\n");
+	}
+	else _error_("Sign should be either +1 or -1.\n");
+
+	return;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Ll2xyx/Ll2xyx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Ll2xyx/Ll2xyx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Ll2xyx/Ll2xyx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  Ll2xyx.h
+ * \brief header file for lat/long to x/y coordinate functions.
+ */ 
+
+#ifndef _LL2XYX_H
+#define _LL2XYX_H
+
+/* local prototypes: */
+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);
+
+#endif  /* _LL2XYX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.cpp	(revision 11330)
@@ -0,0 +1,77 @@
+/*!\file MassFluxx
+ * \brief: compute mass flux along a profile.
+ */
+
+#include "./MassFluxx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void MassFluxx(double* pmass_flux, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,bool process_units){
+
+	int i,j;
+	extern int num_procs;
+	extern int my_rank;
+	
+	Element* element=NULL;
+	int element_id;
+	
+	/*output: */
+	double mass_flux=0;
+	double all_mass_flux=0;
+
+	int  counter;
+
+	/*all segments: */
+	double** array=NULL;
+	int      M;
+	int*     mdims_array=NULL;
+	int*     ndims_array=NULL;
+
+	/*our segments of interest: */
+	double*  segments=NULL;
+	int      num_segments;
+
+	/*First, figure out which segment to compute our mass flux on. Start with retrieving qmu_mass_flux_segments: */
+	parameters->FindParam(&array,&M,&mdims_array,&ndims_array,QmuMassFluxSegmentsEnum);
+
+	/*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=(int)*(segments+5*i+4);
+		for(j=0;j<elements->Size();j++){
+			element=(Element*)elements->GetObjectByOffset(j);
+			if (element->Id()==element_id){
+				/*We found the element which owns this segment, use it to compute the mass flux: */
+				mass_flux+=element->MassFlux(segments+5*i+0,process_units);
+				break;
+			}
+		}
+	}
+
+	#ifdef _PARALLEL_
+	MPI_Allreduce ( (void*)&mass_flux,(void*)&all_mass_flux,1,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
+	mass_flux=all_mass_flux;
+	#endif
+
+	/*Free ressources:*/
+	for(j=0;j<M;j++){
+		double* matrix=array[j];
+		xfree((void**)&matrix);
+	}
+	xfree((void**)&mdims_array);
+	xfree((void**)&ndims_array);
+	xfree((void**)&array);
+	
+	/*Assign output pointers: */
+	*pmass_flux=mass_flux;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.h	(revision 11330)
@@ -0,0 +1,16 @@
+/*!\file:  MassFluxx.h
+ * \brief header file for degree of freedoms distribution routines.
+ */ 
+
+#ifndef _MASSFLUXX_H
+#define _MASSFLUXX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void MassFluxx(double* pmass_flux, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,bool process_units);
+
+
+#endif  /* _MASSFLUXX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.cpp	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file MaxAbsVxx
+ */
+
+#include "./MaxAbsVxx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void MaxAbsVxx( double* pmaxabsvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+	
+	int i;
+	double maxabsvx;
+	double node_maxabsvx;
+	double element_maxabsvx;
+
+	/*Go through elements, and request velocity: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->MaxAbsVx(&element_maxabsvx,process_units); //go pick up the maximum velocity in the inputs
+	
+		if(i==0)maxabsvx=element_maxabsvx; //initialize maxabsvx
+		else{
+			if(element_maxabsvx>maxabsvx)maxabsvx=element_maxabsvx;
+		}
+	}
+	/*A safeguard in case: */
+	if(elements->Size()==0){
+		maxabsvx=-INFINITY;
+	}
+
+	#ifdef _PARALLEL_
+	/*Figure out maximum across the cluster: */
+	MPI_Reduce (&maxabsvx,&node_maxabsvx,1,MPI_DOUBLE,MPI_MAX,0,MPI_COMM_WORLD );
+	MPI_Bcast(&node_maxabsvx,1,MPI_DOUBLE,0,MPI_COMM_WORLD);   
+	maxabsvx=node_maxabsvx;
+	#endif
+
+	/*Assign output pointers:*/
+	*pmaxabsvx=maxabsvx;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  MaxAbsVxx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _MAXABSVXX_H
+#define _MAXABSVXX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void MaxAbsVxx( double* pmaxabsvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif  /* _MAXABSVXX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.cpp	(revision 11330)
@@ -0,0 +1,43 @@
+/*!\file MaxAbsVyx
+ */
+
+#include "./MaxAbsVyx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void MaxAbsVyx( double* pmaxabsvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+	
+	int i;
+	double maxabsvy;
+	double node_maxabsvy;
+	double element_maxabsvy;
+
+
+	/*Go through elements, and request velocity: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->MaxAbsVy(&element_maxabsvy,process_units); //go pick up the maximum velocity in the inputs
+	
+		if(i==0)maxabsvy=element_maxabsvy; //initialize maxabsvy
+		else{
+			if(element_maxabsvy>maxabsvy)maxabsvy=element_maxabsvy;
+		}
+	}
+	/*A safeguard in case: */
+	if(elements->Size()==0){
+		maxabsvy=-INFINITY;
+	}
+
+	#ifdef _PARALLEL_
+	/*Figure out maximum across the cluster: */
+	MPI_Reduce (&maxabsvy,&node_maxabsvy,1,MPI_DOUBLE,MPI_MAX,0,MPI_COMM_WORLD );
+	MPI_Bcast(&node_maxabsvy,1,MPI_DOUBLE,0,MPI_COMM_WORLD);   
+	maxabsvy=node_maxabsvy;
+	#endif
+
+	/*Assign output pointers:*/
+	*pmaxabsvy=maxabsvy;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  MaxAbsVyx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _MAXABSVYX_H
+#define _MAXABSVYX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void MaxAbsVyx( double* pmaxabsvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif  /* _MAXABSVYX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.cpp	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file MaxAbsVzx
+ */
+
+#include "./MaxAbsVzx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void MaxAbsVzx( double* pmaxabsvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+	
+	int i;
+	double maxabsvz;
+	double node_maxabsvz;
+	double element_maxabsvz;
+
+	/*Go through elements, and request velocity: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->MaxAbsVz(&element_maxabsvz,process_units); //go pick up the minimum velocity in the inputs
+	
+		if(i==0)maxabsvz=element_maxabsvz; //initialize maxabsvz
+		else{
+			if(element_maxabsvz>maxabsvz)maxabsvz=element_maxabsvz;
+		}
+	}
+	/*A safeguard in case: */
+	if(elements->Size()==0){
+		maxabsvz=-INFINITY;
+	}
+
+	#ifdef _PARALLEL_
+	/*Figure out minimum across the cluster: */
+	MPI_Reduce (&maxabsvz,&node_maxabsvz,1,MPI_DOUBLE,MPI_MAX,0,MPI_COMM_WORLD );
+	MPI_Bcast(&node_maxabsvz,1,MPI_DOUBLE,0,MPI_COMM_WORLD);   
+	maxabsvz=node_maxabsvz;
+	#endif
+
+	/*Assign output pointers:*/
+	*pmaxabsvz=maxabsvz;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  MaxAbsVzx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _MAXABSVZX_H
+#define _MAXABSVZX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void MaxAbsVzx( double* pmaxabsvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif  /* _MAXABSVZX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.cpp	(revision 11330)
@@ -0,0 +1,43 @@
+/*!\file MaxVelx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./MaxVelx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void MaxVelx( double* pmaxvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+	
+	int i;
+	double maxvel;
+	double node_maxvel;
+	double element_maxvel;
+
+	/*Go through elements, and request velocity: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->MaxVel(&element_maxvel,process_units); //go pick up the maximum velocity in the inputs
+	
+		if(i==0)maxvel=element_maxvel; //initialize maxvel
+		else{
+			if(element_maxvel>maxvel)maxvel=element_maxvel;
+		}
+	}
+	/*A safeguard in case: */
+	if(elements->Size()==0){
+		maxvel=-INFINITY;
+	}
+
+	#ifdef _PARALLEL_
+	/*Figure out maximum across the cluster: */
+	MPI_Reduce (&maxvel,&node_maxvel,1,MPI_DOUBLE,MPI_MAX,0,MPI_COMM_WORLD );
+	MPI_Bcast(&node_maxvel,1,MPI_DOUBLE,0,MPI_COMM_WORLD);   
+	maxvel=node_maxvel;
+	#endif
+
+	/*Assign output pointers:*/
+	*pmaxvel=maxvel;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  MaxVelx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _MAXVELX_H
+#define _MAXVELX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void MaxVelx( double* pmaxvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif  /* _MAXVELX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.cpp	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file MaxVxx
+ */
+
+#include "./MaxVxx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void MaxVxx( double* pmaxvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+	
+	int i;
+	double maxvx;
+	double node_maxvx;
+	double element_maxvx;
+
+	/*Go through elements, and request velocity: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->MaxVx(&element_maxvx,process_units); //go pick up the minimum velocity in the inputs
+	
+		if(i==0)maxvx=element_maxvx; //initialize maxvx
+		else{
+			if(element_maxvx>maxvx)maxvx=element_maxvx;
+		}
+	}
+	/*A safeguard in case: */
+	if(elements->Size()==0){
+		maxvx=-INFINITY;
+	}
+
+	#ifdef _PARALLEL_
+	/*Figure out minimum across the cluster: */
+	MPI_Reduce (&maxvx,&node_maxvx,1,MPI_DOUBLE,MPI_MAX,0,MPI_COMM_WORLD );
+	MPI_Bcast(&node_maxvx,1,MPI_DOUBLE,0,MPI_COMM_WORLD);   
+	maxvx=node_maxvx;
+	#endif
+
+	/*Assign output pointers:*/
+	*pmaxvx=maxvx;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  MaxVxx.h
+ */ 
+
+#ifndef _MAXVXX_H
+#define _MAXVXX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void MaxVxx( double* pmaxvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif  /* _MAXVXX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.cpp	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file MaxVyx
+*/
+
+#include "./MaxVyx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void MaxVyx( double* pmaxvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+
+	int i;
+	double maxvy;
+	double node_maxvy;
+	double element_maxvy;
+
+	/*Go through elements, and request velocity: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->MaxVy(&element_maxvy,process_units); //go pick up the minimum velocity in the inputs
+	
+		if(i==0)maxvy=element_maxvy; //initialize maxvy
+		else{
+			if(element_maxvy>maxvy)maxvy=element_maxvy;
+		}
+	}
+	/*A safeguard in case: */
+	if(elements->Size()==0){
+		maxvy=-INFINITY;
+	}
+
+	#ifdef _PARALLEL_
+	/*Figure out minimum across the cluster: */
+	MPI_Reduce (&maxvy,&node_maxvy,1,MPI_DOUBLE,MPI_MAX,0,MPI_COMM_WORLD );
+	MPI_Bcast(&node_maxvy,1,MPI_DOUBLE,0,MPI_COMM_WORLD);   
+	maxvy=node_maxvy;
+	#endif
+
+	/*Assign output pointers:*/
+	*pmaxvy=maxvy;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  MaxVyx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _MAXVYX_H
+#define _MAXVYX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void MaxVyx( double* pmaxvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif  /* _MAXVYX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.cpp	(revision 11330)
@@ -0,0 +1,43 @@
+/*!\file MaxVzx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./MaxVzx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void MaxVzx( double* pmaxvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+	
+	int i;
+	double maxvz;
+	double node_maxvz;
+	double element_maxvz;
+
+	/*Go through elements, and request velocity: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->MaxVz(&element_maxvz,process_units); //go pick up the minimum velocity in the inputs
+	
+		if(i==0)maxvz=element_maxvz; //initialize maxvz
+		else{
+			if(element_maxvz>maxvz)maxvz=element_maxvz;
+		}
+	}
+	/*A safeguard in case: */
+	if(elements->Size()==0){
+		maxvz=-INFINITY;
+	}
+
+	#ifdef _PARALLEL_
+	/*Figure out minimum across the cluster: */
+	MPI_Reduce (&maxvz,&node_maxvz,1,MPI_DOUBLE,MPI_MAX,0,MPI_COMM_WORLD );
+	MPI_Bcast(&node_maxvz,1,MPI_DOUBLE,0,MPI_COMM_WORLD);   
+	maxvz=node_maxvz;
+	#endif
+
+	/*Assign output pointers:*/
+	*pmaxvz=maxvz;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  MaxVzx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _MAXVZX_H
+#define _MAXVZX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void MaxVzx( double* pmaxvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif  /* _MAXVZX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp	(revision 11330)
@@ -0,0 +1,50 @@
+/*!\file Mergesolutionfromftogx
+ * \brief merge solution back from f set into g set
+ */
+
+#include "../VecMergex/VecMergex.h"
+#include "../../io/io.h"
+#include "./Mergesolutionfromftogx.h"
+
+void	Mergesolutionfromftogx( Vec* pug, Vec uf, Vec ys, Nodes* nodes, Parameters* parameters, bool flag_ys0){
+
+	/*output: */
+	Vec ug=NULL;
+
+	/*intermediary: */
+	int configuration_type;
+	int gsize,fsize,ssize;
+
+	/*Display message*/
+	_printf_(VerboseModule(),"   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){
+			VecSet(ys,0.0);
+		}
+	}
+
+	/*initialize ug: */
+	ug=NewVec(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/trunk-jpl-damage/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  Mergesolutionfromftogx.h
+ * \brief merge solution back from f set into g set
+ */ 
+
+#ifndef _MERGESOLUTIONFROMFTOGX_H
+#define _MERGESOLUTIONFROMFTOGX_H
+
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void	Mergesolutionfromftogx( Vec* pug, Vec uf, Vec ys, Nodes* nodes, Parameters* parameters, bool flag_ys0=false);
+
+#endif  /* _MERGESOLUTIONFROMFTOGX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.cpp	(revision 11330)
@@ -0,0 +1,113 @@
+/*!\file:  MeshPartition.cpp
+ * \brief partition elements and nodes across a cluster of size numprocs. 
+ */
+
+#include "./MeshPartitionx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+int MeshPartitionx(int** pepart, int** pnpart, int numberofelements,int numberofnodes,double* elements,
+		int numberofelements2d,int numberofnodes2d,double* elements2d,int numlayers,int elements_width, int dim,int num_procs){
+
+	int noerr=1;
+	int i,j;
+
+	/*Metis partitioning: */
+	int* epart=NULL;
+	int* npart=NULL;
+	int* index=NULL;
+
+	int* epart2d=NULL;
+	int* npart2d=NULL;
+	int* index2d=NULL;
+	int  count=0;
+
+	int  etype=1; //tria mesh see metis/Programs/Io.c
+	int  etype2d=1; //tria mesh see metis/Programs/Io.c
+	int  numflag=0;
+	int  edgecut=1;
+
+	if(dim==2){
+		epart=(int*)xmalloc(numberofelements*sizeof(int));
+		npart=(int*)xmalloc(numberofnodes*sizeof(int));
+		index=(int*)xmalloc(elements_width*numberofelements*sizeof(int));
+		for (i=0;i<numberofelements;i++){
+			for (j=0;j<elements_width;j++){
+				*(index+elements_width*i+j)=(int)*(elements+elements_width*i+j)-1; //-1 for C indexing in Metis
+			}
+		}
+
+		/*Partition using Metis:*/
+		if (num_procs>1){
+			METIS_PartMeshNodalPatch(&numberofelements,&numberofnodes, index, &etype, &numflag, &num_procs, &edgecut, epart, npart);
+		}
+		else if (num_procs==1){
+			/*METIS does not know how to deal with one cpu only!*/
+			for (i=0;i<numberofelements;i++) epart[i]=0;
+			for (i=0;i<numberofnodes;i++)    npart[i]=0;
+		}
+		else _error_("At least one processor is required");
+	}
+	else{
+		/*We have a 3d mesh, made of a regularly extruded 2d mesh. We first partition the 2d mesh, then we extrude the partition: */
+
+		/*First build concatenated 2d mesh  from 2d_coll and 2d_noncoll: */
+		epart2d=(int*)xmalloc(numberofelements2d*sizeof(int));
+		npart2d=(int*)xmalloc(numberofnodes2d*sizeof(int)); 
+		index2d=(int*)xmalloc(3*numberofelements2d*sizeof(int));
+
+		for (i=0;i<numberofelements2d;i++){
+			for (j=0;j<3;j++){
+				*(index2d+3*i+j)=(int)*(elements2d+3*i+j)-1; //-1 for C indexing in Metis
+			}
+		}
+
+		/*Partition using Metis:*/
+		if (num_procs>1){
+			METIS_PartMeshNodalPatch(&numberofelements2d,&numberofnodes2d, index2d, &etype2d, &numflag, &num_procs, &edgecut, epart2d, npart2d);
+		}
+		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=(int*)xmalloc(numberofelements*sizeof(int));
+		
+		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=(int*)xmalloc(numberofnodes*sizeof(int));
+		
+		count=0;
+		for(i=0;i<(numlayers);i++){
+			for(j=0;j<numberofnodes2d;j++){
+				npart[count]=npart2d[j];
+				count++;
+			}
+		}
+	}
+	
+	/*Assign output pointer:*/
+	*pepart=epart;
+	*pnpart=npart;
+
+	/*Free ressources: */
+	xfree((void**)&index);
+	xfree((void**)&epart2d);
+	xfree((void**)&npart2d);
+	xfree((void**)&index2d);
+
+	return noerr;
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  MeshPartitionx.h
+ * \brief  header file for partitioning module.
+ */ 
+
+#ifndef _MESHPARTITIONX_H
+#define _MESHPARTITIONX_H
+
+/* local prototypes: */
+int MeshPartitionx(int** pepart, int** pnpart, int numberofelements,int numberofnodes,double* elements,
+		int numberofelements2d,int numberofnodes2d,double* elements2d,int numlayers,int elements_width, int dim,int numareas);
+	
+#endif /* _MESHPARTITIONX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp	(revision 11330)
@@ -0,0 +1,93 @@
+/*! \file  ElementSegment.cpp
+ */
+
+#include "./MeshProfileIntersectionx.h"
+		
+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: */
+
+	int i;
+	double alpha;
+	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(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(el+1,xfinal[0],yfinal[0],xfinal[1],yfinal[1]));
+	}
+	else{
+		/*No interesections, but the segment might be entirely inside this triangle!: */
+		if ( (NodeInElement(xnodes,ynodes,xsegment[0],ysegment[0])) && (NodeInElement(xnodes,ynodes,xsegment[1],ysegment[1])) ){
+			segments_dataset->AddObject(new  Segment(el+1,xsegment[0],ysegment[0],xsegment[1],ysegment[1]));
+		}
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/ElementSegmentsIntersection.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/ElementSegmentsIntersection.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/ElementSegmentsIntersection.cpp	(revision 11330)
@@ -0,0 +1,23 @@
+/*! \file  ElementSegmentsIntersection.cpp
+ */
+
+#include "./MeshProfileIntersectionx.h"
+		
+void ElementSegmentsIntersection(DataSet* segments_dataset,int el, double* xnodes,double* ynodes,double* xc,double* yc,int numnodes){
+
+	int i;
+	double xsegment[2];
+	double ysegment[2];
+
+	/*Loop through contour: */
+	for(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);
+
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 11330)
@@ -0,0 +1,73 @@
+/*! \file  MeshProfileIntersectionx.c
+ */
+
+#include "./MeshProfileIntersectionx.h"
+
+void MeshProfileIntersectionx( double** psegments, int* pnumsegs, int* index, double* x, double* y, int nel, int nods,  Contour** contours,int numcontours){
+
+
+	int i,j,k;
+	int m,n;
+
+	/*Contour:*/
+	Contour* 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=(double**)xmalloc(numcontours*sizeof(double*));
+	allnumsegs=(int*)xmalloc(numcontours*sizeof(int));
+
+	/*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=(double*)xmalloc(5*numsegs*sizeof(double));
+	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;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 11330)
@@ -0,0 +1,21 @@
+/*
+	MeshProfileIntersectionx.h
+*/
+
+
+#ifndef _MESHPROFILEINTERSECTIONX_H
+#define _MESHPROFILEINTERSECTIONX_H
+
+#include "../../shared/shared.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void MeshProfileIntersectionx( double** psegments, int* pnumseg, int* index, double* x, double* y, int nel, int nods,  Contour** contours,int numcontours);
+void 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/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp	(revision 11330)
@@ -0,0 +1,52 @@
+/*! \file  MeshSegmentsIntersectionx.c
+ */
+
+#include "./MeshProfileIntersectionx.h"
+
+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;
+	Segment* segment=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=(double*)xmalloc(5*numsegs*sizeof(double));
+	for(i=0;i<numsegs;i++){
+		Segment* segment=(Segment*)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;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/NodeInElement.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/NodeInElement.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/NodeInElement.cpp	(revision 11330)
@@ -0,0 +1,33 @@
+/*! \file  NodeInElement.cpp
+*/
+
+#include "./MeshProfileIntersectionx.h"
+
+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;
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/SegmentIntersect.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/SegmentIntersect.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/SegmentIntersect.cpp	(revision 11330)
@@ -0,0 +1,106 @@
+/*! \file  SegmentIntersect.cpp
+*/
+
+#include "./MeshProfileIntersectionx.h"
+
+int SegmentIntersect(double* palpha, double* pbeta, double* x1, double* y1, double* x2, double* y2){
+
+	/*See ISSM_TIER/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/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/intersect.m
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/intersect.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/intersect.m	(revision 11330)
@@ -0,0 +1,12 @@
+syms xA yA xB yB xC yC xD yD alpha beta x y
+
+A=[xA;yA];
+B=[xB;yB];
+C=[xC;yC];
+D=[xD;yD];
+
+
+Eq=C+alpha*(D-C)-A+beta*(B-A); 
+
+%from Eq, we specify the system to solve: 
+S=solve( xC+alpha*(xD-xC)-xA+beta*(xB-xA), yC+alpha*(yD-yC)-yA+beta*(yB-yA),alpha,beta);
Index: /issm/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.cpp	(revision 11330)
@@ -0,0 +1,43 @@
+/*!\file MinVelx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./MinVelx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void MinVelx( double* pminvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+	
+	int i;
+	double minvel;
+	double node_minvel;
+	double element_minvel;
+
+	/*Go through elements, and request velocity: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->MinVel(&element_minvel,process_units); //go pick up the minimum velocity in the inputs
+	
+		if(i==0)minvel=element_minvel; //initialize minvel
+		else{
+			if(element_minvel<minvel)minvel=element_minvel;
+		}
+	}
+	/*A safeguard in case: */
+	if(elements->Size()==0){
+		minvel=INFINITY;
+	}
+
+	#ifdef _PARALLEL_
+	/*Figure out minimum across the cluster: */
+	MPI_Reduce (&minvel,&node_minvel,1,MPI_DOUBLE,MPI_MIN,0,MPI_COMM_WORLD );
+	MPI_Bcast(&node_minvel,1,MPI_DOUBLE,0,MPI_COMM_WORLD);   
+	minvel=node_minvel;
+	#endif
+
+	/*Assign output pointers:*/
+	*pminvel=minvel;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  MinVelx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _MINVELX_H
+#define _MINVELX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void MinVelx( double* pminvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif  /* _MINVELX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.cpp	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file MinVxx
+ */
+
+#include "./MinVxx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void MinVxx( double* pminvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+	
+	int i;
+	double minvx;
+	double node_minvx;
+	double element_minvx;
+
+	/*Go through elements, and request velocity: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->MinVx(&element_minvx,process_units); //go pick up the minimum velocity in the inputs
+	
+		if(i==0)minvx=element_minvx; //initialize minvx
+		else{
+			if(element_minvx<minvx)minvx=element_minvx;
+		}
+	}
+	/*A safeguard in case: */
+	if(elements->Size()==0){
+		minvx=INFINITY;
+	}
+
+	#ifdef _PARALLEL_
+	/*Figure out minimum across the cluster: */
+	MPI_Reduce (&minvx,&node_minvx,1,MPI_DOUBLE,MPI_MIN,0,MPI_COMM_WORLD );
+	MPI_Bcast(&node_minvx,1,MPI_DOUBLE,0,MPI_COMM_WORLD);   
+	minvx=node_minvx;
+	#endif
+
+	/*Assign output pointers:*/
+	*pminvx=minvx;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  MinVxx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _MINVX_H
+#define _MINVX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void MinVxx( double* pminvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif  /* _MINVX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.cpp	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file MinVyx
+ */
+
+#include "./MinVyx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void MinVyx( double* pminvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+	
+	int i;
+	double minvy;
+	double node_minvy;
+	double element_minvy;
+
+	/*Go through elements, and request velocity: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->MinVy(&element_minvy,process_units); //go pick up the minimum velocity in the inputs
+	
+		if(i==0)minvy=element_minvy; //initialize minvy
+		else{
+			if(element_minvy<minvy)minvy=element_minvy;
+		}
+	}
+	/*A safeguard in case: */
+	if(elements->Size()==0){
+		minvy=INFINITY;
+	}
+
+	#ifdef _PARALLEL_
+	/*Figure out minimum across the cluster: */
+	MPI_Reduce (&minvy,&node_minvy,1,MPI_DOUBLE,MPI_MIN,0,MPI_COMM_WORLD );
+	MPI_Bcast(&node_minvy,1,MPI_DOUBLE,0,MPI_COMM_WORLD);   
+	minvy=node_minvy;
+	#endif
+
+	/*Assign output pointers:*/
+	*pminvy=minvy;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  MinVyx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _MINVYX_H
+#define _MINVYX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void MinVyx( double* pminvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif  /* _MINVYX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.cpp	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file MinVzx
+ */
+
+#include "./MinVzx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void MinVzx( double* pminvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+	
+	int i;
+	double minvz;
+	double node_minvz;
+	double element_minvz;
+
+	/*Go through elements, and request velocity: */
+	for(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		element->MinVz(&element_minvz,process_units); //go pick up the minimum velocity in the inputs
+	
+		if(i==0)minvz=element_minvz; //initialize minvz
+		else{
+			if(element_minvz<minvz)minvz=element_minvz;
+		}
+	}
+	/*A safeguard in case: */
+	if(elements->Size()==0){
+		minvz=INFINITY;
+	}
+
+	#ifdef _PARALLEL_
+	/*Figure out minimum across the cluster: */
+	MPI_Reduce (&minvz,&node_minvz,1,MPI_DOUBLE,MPI_MIN,0,MPI_COMM_WORLD );
+	MPI_Bcast(&node_minvz,1,MPI_DOUBLE,0,MPI_COMM_WORLD);   
+	minvz=node_minvz;
+	#endif
+
+	/*Assign output pointers:*/
+	*pminvz=minvz;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  MinVzx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _MINVZX_H
+#define _MINVZX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void MinVzx( double* pminvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif  /* _MINVZX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp	(revision 11330)
@@ -0,0 +1,33 @@
+#include "../../../Container/Container.h"
+#include "../../../modules/modules.h"
+#include "../../../io/io.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsBalancethickness(Constraints** pconstraints, IoModel* iomodel){
+
+	int    stabilization;	
+	
+	/*Fetch parameters: */
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Output*/
+	Constraints* constraints = NULL;
+
+	/*Recover pointer: */
+	constraints=*pconstraints;
+
+	/*Create constraints if they do not exist yet*/
+	if(!constraints) constraints = new Constraints();
+
+	/*Do not add constraints in DG*/
+	if(stabilization!=3){
+		IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcthicknessEnum,BalancethicknessAnalysisEnum);
+	}
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 11330)
@@ -0,0 +1,59 @@
+/*! \file CreateLoadsBalancethickness.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsBalancethickness(Loads** ploads, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	int element;
+	int stabilization;
+	int numberofedges;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+	iomodel->Constant(&numberofedges,MeshNumberofedgesEnum);
+
+	/*Output*/
+	Loads*    loads    = NULL;
+
+	/*Recover pointer: */
+	loads=*ploads;
+
+	/*Create loads if they do not exist yet*/
+	if(!loads) loads = new Loads();
+	
+	/*Loads only in DG*/
+	if (stabilization==3){
+
+		/*Get edges and elements*/
+		iomodel->FetchData(3,MeshEdgesEnum,MeshElementsEnum,ThicknessEnum);
+
+		/*First load data:*/
+		for (i=0;i<numberofedges;i++){
+
+			/*Get left and right elements*/
+			element=(int)iomodel->Data(MeshEdgesEnum)[4*i+2]-1; //edges 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,iomodel,BalancethicknessAnalysisEnum));
+		}
+
+		/*Free data: */
+		iomodel->DeleteData(3,MeshEdgesEnum,MeshElementsEnum,ThicknessEnum);
+	}
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 11330)
@@ -0,0 +1,94 @@
+/*
+ * CreateNodesBalancethickness.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesBalancethickness(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int  i,j;
+	int  node_id;
+	int  vertex_id;
+	int  io_index;
+	bool continuous_galerkin=true;
+	int    dim;
+	int    numberofelements;
+	int    numberofvertices;
+	int    stabilization;
+
+	/*DataSets: */
+	Nodes*    nodes = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Recover pointer: */
+	nodes=*pnodes;
+
+	/*Create nodes if they do not exist yet*/
+	if(!nodes) nodes = new Nodes();
+
+	/*Continuous Galerkin partition of nodes: */
+	if(stabilization==3) continuous_galerkin=false;
+	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
+
+	/*Check in 3d*/
+	if(stabilization==3 && dim==3) _error_("DG 3d not implemented yet");
+
+	/*First fetch data: */
+	iomodel->FetchData(7,MeshElementsEnum,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+
+	if(continuous_galerkin){
+
+		/*Build Nodes dataset (Continuous Galerkin)*/
+		for (i=0;i<numberofvertices;i++){
+			if(iomodel->my_vertices[i]){
+
+				/*Add node to nodes dataset: */
+				nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,BalancethicknessAnalysisEnum));
+
+			}
+		}
+	}
+	else{
+
+		/*Build Nodes dataset -> 3 for each element (Discontinuous Galerkin)*/
+		for (i=0;i<numberofelements;i++){
+			for (j=0;j<3;j++){
+
+				if(iomodel->my_nodes[3*i+j]){ 
+
+					//Get index of the vertex on which the current node is located
+					vertex_id=(int)*(iomodel->Data(MeshElementsEnum)+3*i+j); //(Matlab indexing)
+					io_index=vertex_id-1;                      //(C indexing)
+					_assert_(vertex_id>0 && vertex_id<=numberofvertices);
+
+					//Compute Node id
+					node_id=iomodel->nodecounter+3*i+j+1;
+
+					/*Add node to nodes dataset: */
+					nodes->AddObject(new Node(node_id,node_id-1,vertex_id,io_index,iomodel,BalancethicknessAnalysisEnum));
+
+				}
+			}
+		}
+	}
+
+	/*Clean fetched data: */
+	iomodel->DeleteData(7,MeshElementsEnum,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp	(revision 11330)
@@ -0,0 +1,55 @@
+/*
+ * UpdateElementsBalancethickness:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../modules/modules.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsBalancethickness(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    dim;
+	int    numberofelements;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->FetchData(1,MeshElementsEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type); //we need i to index into elements.
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsAccumulationRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsAblationRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	iomodel->FetchDataToInput(elements,BalancethicknessThickeningRateEnum);
+
+	if (dim==3){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	}
+	/*Free data: */
+	iomodel->DeleteData(1,MeshElementsEnum);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp	(revision 11330)
@@ -0,0 +1,26 @@
+/*
+ * CreateConstraintsBedSlope.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../io/io.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsBedSlope(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Output*/
+	Constraints* constraints = NULL;
+	
+	/*Recover pointer: */
+	constraints=*pconstraints;
+
+	/*Create constraints if they do not exist yet*/
+	if(!constraints) constraints = new Constraints();
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp	(revision 11330)
@@ -0,0 +1,26 @@
+/*! \file CreateLoadsBedSlope.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../io/io.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsBedSlope(Loads** ploads, IoModel* iomodel){
+
+	/*DataSet*/
+	Loads*    loads    = NULL;
+
+	/*Recover pointer: */
+	loads=*ploads;
+
+	/*Create loads if they do not exist yet*/
+	if(!loads) loads = new Loads();
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp	(revision 11330)
@@ -0,0 +1,54 @@
+/*
+ * CreateNodesBedSlope.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../io/io.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesBedSlope(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	bool continuous_galerkin=true;
+	int    numberofvertices;
+
+	/*DataSets: */
+	Nodes*    nodes = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+
+	/*Recover pointer: */
+	nodes=*pnodes;
+
+	/*Create nodes if they do not exist yet*/
+	if(!nodes) nodes = new Nodes();
+	
+	/*Continuous Galerkin partition of nodes: */
+	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
+	
+	/*First fetch data: */
+	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+
+	for (i=0;i<numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
+			
+			/*Add node to nodes dataset: */
+			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,BedSlopeAnalysisEnum));
+
+		}
+	}
+
+	/*Clean fetched data: */
+	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+	
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp	(revision 11330)
@@ -0,0 +1,47 @@
+/*
+ * UpdateElementsBedSlope:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../modules/modules.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsBedSlope(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    dim;
+	int    numberofelements;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->FetchData(1,MeshElementsEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type); //we need i to index into elements.
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
+
+	if (dim==3){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	}
+	
+	/*Free data: */
+	iomodel->DeleteData(1,MeshElementsEnum);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 11330)
@@ -0,0 +1,73 @@
+/*!\file: CreateParametersControl.cpp
+ * \brief driver for creating parameters dataset, for control analysis.
+ */ 
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void CreateParametersControl(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
+	
+	int         i;
+	Parameters *parameters       = NULL;
+	bool        control_analysis;
+	int         nsteps;
+	int         num_control_type;
+	int         num_cm_responses;
+	int        *control_type     = NULL;
+	double     *cm_responses     = NULL;
+	double     *cm_jump          = NULL;
+	double     *optscal          = NULL;
+	double     *maxiter          = NULL;
+
+	/*Get parameters: */
+	parameters=*pparameters;
+
+	/*retrieve some parameters: */
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+
+	if(control_analysis){
+
+		/*How many controls and how many responses?*/
+		parameters->AddObject(iomodel->CopyConstantObject(InversionNumControlParametersEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(InversionNumCostFunctionsEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(InversionNstepsEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(InversionCostFunctionThresholdEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(InversionGradientOnlyEnum));
+
+		/*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,&nsteps,&num_cm_responses,InversionCostFunctionsEnum);
+		iomodel->FetchData(&cm_jump,&nsteps,NULL,InversionStepThresholdEnum);
+		iomodel->FetchData(&optscal,NULL,NULL,InversionGradientScalingEnum);
+		iomodel->FetchData(&maxiter,NULL,NULL,InversionMaxiterPerStepEnum);
+
+		parameters->AddObject(new IntVecParam(InversionControlParametersEnum,control_type,num_control_type));
+		parameters->AddObject(new DoubleMatParam(InversionGradientScalingEnum,optscal,nsteps,num_control_type));
+		parameters->AddObject(new DoubleMatParam(InversionCostFunctionsEnum,cm_responses,nsteps,num_cm_responses));
+		parameters->AddObject(new DoubleVecParam(InversionStepThresholdEnum,cm_jump,nsteps));
+		parameters->AddObject(new DoubleVecParam(InversionMaxiterPerStepEnum,maxiter,nsteps));
+
+		xfree((void**)&control_type);
+		xfree((void**)&cm_responses);
+		xfree((void**)&cm_jump);
+		xfree((void**)&optscal);
+		xfree((void**)&maxiter);
+	}
+
+	/*Assign output pointer: */
+	*pparameters=parameters;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 11330)
@@ -0,0 +1,69 @@
+/*
+ * UpdateElementsAndMaterialsControl:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../modules/modules.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsAndMaterialsControl(Elements* elements,Materials* materials, IoModel* iomodel){
+
+	/*Intermediary*/
+	int       i;
+	int       counter;
+	Element  *element = NULL;
+	Material *material = NULL;
+	int    numberofelements;
+	int    num_control_type;
+	bool   control_analysis;
+
+	
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	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->FetchData(1,MeshElementsEnum);
+	iomodel->FetchDataToInput(elements,InversionVxObsEnum);
+	iomodel->FetchDataToInput(elements,InversionVyObsEnum); 
+	iomodel->FetchDataToInput(elements,InversionThicknessObsEnum);
+
+	iomodel->FetchData(4,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
+	for(i=0;i<num_control_type;i++){
+		switch((int)iomodel->Data(InversionControlParametersEnum)[i]){
+			case BalancethicknessThickeningRateEnum: iomodel->FetchData(1,BalancethicknessThickeningRateEnum); break;
+			case VxEnum:   iomodel->FetchData(1,VxEnum); break;
+			case VyEnum:   iomodel->FetchData(1,VyEnum); break;
+			case FrictionCoefficientEnum: iomodel->FetchData(1,FrictionCoefficientEnum); break;
+			case MaterialsRheologyBbarEnum:    iomodel->FetchData(1,MaterialsRheologyBEnum); break;
+			default: _error_("Control %s not implemented yet",EnumToStringx((int)iomodel->Data(InversionControlParametersEnum)[i]));
+		}
+	}
+
+	/*Update elements and materials: */
+	counter=0;
+	for (i=0;i<numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			element=(Element*)elements->GetObjectByOffset(counter);
+			element->InputUpdateFromIoModel(i,iomodel); //we need i to index into elements.
+
+			material=(Material*)materials->GetObjectByOffset(counter);
+			material->InputUpdateFromIoModel(i,iomodel); //we need i to index into elements.
+			counter++;
+		}
+	}
+	
+	/*Free data: */
+	iomodel->DeleteData(1+4+5,MeshElementsEnum,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum,BalancethicknessThickeningRateEnum,VxEnum,VyEnum,FrictionCoefficientEnum,MaterialsRheologyBEnum);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateDataSets.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 11330)
@@ -0,0 +1,151 @@
+/*!\file: CreateDataSets
+ * \brief general driver for creating all datasets that make a finite element iomodel
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../objects/objects.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "./ModelProcessorx.h"
+
+
+void CreateDataSets(Elements** pelements,Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads,Parameters** pparameters,IoModel* iomodel,const int solution_type,const int analysis_type,const int nummodels,int analysis_counter){
+
+	bool        continuous = true;
+	Elements   *elements   = NULL;
+	Materials  *materials  = NULL;
+	Parameters *parameters = NULL;
+			
+	/*Create elements, vertices and materials, independent of analysis_type: */
+	CreateElementsVerticesAndMaterials(pelements, pvertices, pmaterials, iomodel,nummodels);
+
+	/*Recover elements and materials, for future update: */
+	elements=*pelements;
+	materials=*pmaterials;
+
+	/*Now, branch onto analysis dependent model generation: */
+	switch(analysis_type){
+
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum:
+			CreateNodesDiagnosticHoriz(pnodes, iomodel);
+			CreateConstraintsDiagnosticHoriz(pconstraints,iomodel);
+			CreateLoadsDiagnosticHoriz(ploads,iomodel);
+			UpdateElementsDiagnosticHoriz(elements,iomodel,analysis_counter,analysis_type);
+			break;
+		
+		case DiagnosticVertAnalysisEnum:
+			CreateNodesDiagnosticVert(pnodes, iomodel);
+			CreateConstraintsDiagnosticVert(pconstraints,iomodel);
+			CreateLoadsDiagnosticVert(ploads,iomodel);
+			UpdateElementsDiagnosticVert(elements,iomodel,analysis_counter,analysis_type);
+			break;
+	
+		case DiagnosticHutterAnalysisEnum:
+			CreateNodesDiagnosticHutter(pnodes, iomodel);
+			CreateConstraintsDiagnosticHutter(pconstraints,iomodel);
+			CreateLoadsDiagnosticHutter(ploads,iomodel);
+			UpdateElementsDiagnosticHutter(elements,iomodel,analysis_counter,analysis_type);
+			break;
+		#endif
+		
+		#ifdef _HAVE_HYDROLOGY_
+		case HydrologyAnalysisEnum:
+			CreateNodesHydrology(pnodes, iomodel);
+			CreateConstraintsHydrology(pconstraints,iomodel);
+			CreateLoadsHydrology(ploads,iomodel);
+			UpdateElementsHydrology(elements,iomodel,analysis_counter,analysis_type);
+			break;
+		#endif
+
+		#ifdef _HAVE_THERMAL_
+		case ThermalAnalysisEnum:
+			CreateNodesThermal(pnodes, iomodel);
+			CreateConstraintsThermal(pconstraints,iomodel);
+			CreateLoadsThermal(ploads,iomodel);
+			UpdateElementsThermal(elements,iomodel,analysis_counter,analysis_type);
+			break;
+	
+		case EnthalpyAnalysisEnum:
+			CreateNodesEnthalpy(pnodes, iomodel);
+			CreateConstraintsEnthalpy(pconstraints,iomodel);
+			CreateLoadsEnthalpy(ploads,iomodel);
+			UpdateElementsEnthalpy(elements,iomodel,analysis_counter,analysis_type);
+			break;
+		
+		case MeltingAnalysisEnum:
+			CreateNodesMelting(pnodes, iomodel);
+			CreateConstraintsMelting(pconstraints,iomodel);
+			CreateLoadsMelting(ploads,iomodel);
+			UpdateElementsMelting(elements,iomodel,analysis_counter,analysis_type);
+			break;
+		#endif
+
+		#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			CreateNodesBalancethickness(pnodes, iomodel);
+			CreateConstraintsBalancethickness(pconstraints,iomodel);
+			CreateLoadsBalancethickness(ploads,iomodel);
+			UpdateElementsBalancethickness(elements,iomodel,analysis_counter,analysis_type);
+			break;
+		#endif
+
+		#ifdef _HAVE_SLOPE_
+		case BedSlopeAnalysisEnum:
+			CreateNodesBedSlope(pnodes, iomodel);
+			CreateConstraintsBedSlope(pconstraints,iomodel);
+			CreateLoadsBedSlope(ploads,iomodel);
+			UpdateElementsBedSlope(elements,iomodel,analysis_counter,analysis_type);
+			break;
+
+		case SurfaceSlopeAnalysisEnum:
+			CreateNodesSurfaceSlope(pnodes, iomodel);
+			CreateConstraintsSurfaceSlope(pconstraints,iomodel);
+			CreateLoadsSurfaceSlope(ploads,iomodel);
+			UpdateElementsSurfaceSlope(elements,iomodel,analysis_counter,analysis_type);
+			break;
+		#endif
+
+		#ifdef _HAVE_PROGNOSTIC_
+		case PrognosticAnalysisEnum:
+			CreateNodesPrognostic(pnodes, iomodel);
+			CreateConstraintsPrognostic(pconstraints,iomodel);
+			CreateLoadsPrognostic(ploads,iomodel);
+			UpdateElementsPrognostic(elements,iomodel,analysis_counter,analysis_type);
+			break;
+		#endif
+
+
+		default:
+			_error_("%s%s%s"," analysis_type: ",EnumToStringx(analysis_type)," not supported yet!");
+	}
+
+	/*Update Elements and Materials For Control methods*/
+	#ifdef _HAVE_CONTROL_
+	UpdateElementsAndMaterialsControl(elements,materials,iomodel);
+	#endif
+
+	/*Generate objects that are not dependent on any analysis_type: */
+	CreateParameters(pparameters,iomodel,solution_type,analysis_type,analysis_counter);
+
+	/*Update Elements in case we are running a transient solution: */
+	#ifdef _HAVE_TRANSIENT_
+	parameters=*pparameters;
+	if(analysis_counter==(nummodels-1)&& solution_type==TransientSolutionEnum){
+		UpdateElementsTransient(elements,parameters,iomodel,analysis_counter,analysis_type);
+	}
+	#endif
+
+	/*Sort datasets: */
+	SortDataSets(pelements,pnodes,pvertices, ploads, pmaterials, pconstraints, pparameters);
+
+	/*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: */
+	UpdateCounters(iomodel,pnodes,ploads,pconstraints);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 11330)
@@ -0,0 +1,98 @@
+/*
+ * CreateElementsNodesAndMaterialsDiagnosticHoriz.c:
+ */
+
+#include "../../Container/Container.h"
+#include "../../toolkits/toolkits.h"
+#include "../../io/io.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../objects/objects.h"
+#include "../../shared/shared.h"
+#include "../MeshPartitionx/MeshPartitionx.h"
+#include "../../include/include.h"
+#include "./ModelProcessorx.h"
+
+void	CreateElementsVerticesAndMaterials(Elements** pelements,Vertices** pvertices,Materials** pmaterials, IoModel* iomodel,const int nummodels){
+
+	/*Intermediary*/
+	int i,j,k,n;
+	int dim;
+	int numberofelements;
+	int numberofvertices;
+	bool control_analysis;
+
+	/*DataSets: */
+	Elements*     elements  = NULL;
+	Vertices*     vertices = NULL;
+	Materials*    materials = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+
+	/*Did we already create the elements? : */
+	if(*pelements)return;
+
+	/*First create the elements, vertices, nodes and material properties, if they don't already exist */
+	elements  = new Elements();
+	vertices  = new Vertices();
+	materials = new Materials();
+	
+	/*First, partition elements and vertices. Nodes will partitioned on a per analysis_type basis. If partitining already done, ignore: */
+	ElementsAndVerticesPartitioning(&iomodel->my_elements,&iomodel->my_vertices,iomodel);
+	
+	/*Fetch data needed: */
+	iomodel->FetchData(4,MeshElementsEnum,MeshElementconnectivityEnum,MaterialsRheologyBEnum,MaterialsRheologyNEnum);
+	#ifdef _HAVE_THREED_
+	if(dim==3)iomodel->FetchData(2,MeshUpperelementsEnum,MeshLowerelementsEnum);
+	#endif
+	if(control_analysis)iomodel->FetchData(3,InversionControlParametersEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
+	
+	/*Create elements and materials: */
+	for (i=0;i<numberofelements;i++){
+		if(iomodel->my_elements[i]){
+
+			/*Create and add tria element to elements dataset: */
+			if(dim==2) elements->AddObject(new Tria(i+1,i,i,iomodel,nummodels));
+	        #ifdef _HAVE_THREED_
+			else       elements->AddObject(new Penta(i+1,i,i,iomodel,nummodels));
+	        #endif
+
+			/*Create and add material property to materials dataset: */
+			materials->AddObject(new Matice(i+1,i,iomodel));
+		}
+	}
+	
+	/*Free data: */
+	iomodel->DeleteData(9,MeshElementsEnum,MeshElementconnectivityEnum,MeshUpperelementsEnum,MeshLowerelementsEnum,
+				MaterialsRheologyBEnum,MaterialsRheologyNEnum,InversionControlParametersEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
+
+	/*Add new constrant material property tgo materials, at the end: */
+	materials->AddObject(new Matpar(numberofelements+1,iomodel));//put it at the end of the materials
+	
+	/*Create vertices: */
+
+	/*Fetch data:*/
+	iomodel->FetchData(6,MeshElementsEnum,MeshXEnum,MeshYEnum,MeshZEnum,BedEnum,ThicknessEnum);
+	CreateNumberNodeToElementConnectivity(iomodel);
+	
+	for (i=0;i<numberofvertices;i++){
+
+		/*vertices and nodes (same number, as we are running continuous galerkin formulation: */
+		if(iomodel->my_vertices[i]){
+			
+			/*Add vertex to vertices dataset: */
+			vertices->AddObject(new Vertex(i+1,i,i,iomodel));
+		}
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(6,MeshElementsEnum,MeshXEnum,MeshYEnum,MeshZEnum,BedEnum,ThicknessEnum);
+
+	/*Assign output pointer: */
+	*pelements=elements;
+	*pvertices=vertices;
+	*pmaterials=materials;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 11330)
@@ -0,0 +1,68 @@
+/*!\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 "../../io/io.h"
+#include "../../include/include.h"
+#include "./ModelProcessorx.h"
+
+void CreateNumberNodeToElementConnectivity(IoModel* iomodel){
+
+	/*Intermediary*/
+	int i,j;
+	int vertexid;
+	int elementswidth;
+	int    dim;
+	int    numberofelements;
+	int    numberofvertices;
+	double* elements=NULL;
+
+	/*output*/
+	int* connectivity=NULL;
+
+	/*Check that this has not been done yet*/
+	if(iomodel->numbernodetoelementconnectivity) return;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	elements=iomodel->Data(MeshElementsEnum);
+
+	/*Some checks if debugging*/
+	_assert_(numberofvertices);
+	_assert_(numberofelements);
+	_assert_(elements);
+
+	/*Allocate ouput*/
+	connectivity=(int*)xcalloc(numberofvertices,sizeof(int));
+
+	/*Get element width (3 or 6)*/
+	if (dim==2){
+		elementswidth=3;
+	}
+	else{
+		elementswidth=6;
+	}
+
+	/*Create connectivity table*/
+	for (i=0;i<numberofelements;i++){
+		for (j=0;j<elementswidth;j++){
+			vertexid=(int)elements[elementswidth*i+j];
+			_assert_(vertexid>0 && vertexid-1<numberofvertices);
+			connectivity[vertexid-1]+=1;
+		}
+	}
+
+	/*Assign to iomodel*/
+	iomodel->numbernodetoelementconnectivity=connectivity;
+
+	/*Do not free connectivity!!!*/
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateParameters.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 11330)
@@ -0,0 +1,122 @@
+/*!\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 "../../Container/Container.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../objects/objects.h"
+#include "../../shared/shared.h"
+#include "../MeshPartitionx/MeshPartitionx.h"
+#include "../../io/io.h"
+#include "./ModelProcessorx.h"
+
+void CreateParameters(Parameters** pparameters,IoModel* iomodel,const int solution_type,int analysis_type,int analysis_counter){
+	
+	int         i;
+	int         numoutputs;
+	Parameters *parameters       = NULL;
+	double     *requestedoutputs = NULL;
+	
+	if(*pparameters)return; //do not create parameters twice!
+
+	/*Initialize dataset: */
+	parameters = new Parameters();
+		
+	/*Copy some constants from iomodel */
+	parameters->AddObject(iomodel->CopyConstantObject(MeshDimensionEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIshutterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsmacayealpattynEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsstokesEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SettingsOutputFrequencyEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticRestolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticReltolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticAbstolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SteadystateReltolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SteadystateMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ConstantsYtsEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingTimeStepEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingFinalTimeEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingTimeAdaptEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingCflCoefficientEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(PrognosticHydrostaticAdjustmentEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(PrognosticStabilizationEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticPenaltyFactorEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(PrognosticMinThicknessEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(PrognosticPenaltyFactorEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyFactorEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SettingsLowmemEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MeshAverageVertexConnectivityEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ConstantsReferencetemperatureEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(BalancethicknessStabilizationEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(HydrologyStabilizationEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(GroundinglineMeltingRateEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalStabilizationEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyThresholdEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyLockEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticRiftPenaltyThresholdEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticStokesreconditioningEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticShelfDampeningEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticViscosityOvershootEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SettingsWaitonlockEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MeshNumberofelementsEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MeshNumberofverticesEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SettingsIoGatherEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SettingsResultsAsPatchesEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(GroundinglineMigrationEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIsdiagnosticEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIsprognosticEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIsthermalEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIsgroundinglineEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MaterialsRheologyLawEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(AutodiffIsautodiffEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(AutodiffForwardEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(AutodiffReverseEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(QmuIsdakotaEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(InversionIscontrolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(InversionTaoEnum));
+
+	/*some parameters that did not come with the iomodel: */
+	parameters->AddObject(new IntParam(SolutionTypeEnum,solution_type));
+	parameters->AddObject(new IntParam(AnalysisTypeEnum,analysis_type));
+	parameters->AddObject(new IntParam(AnalysisCounterEnum,analysis_counter));
+	parameters->AddObject(new DoubleParam(TimeEnum,0.0));  //start at time 0 by default for all solutions
+
+	/*Requested output?*/
+	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,DiagnosticRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(DiagnosticNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new IntVecParam(DiagnosticRequestedOutputsEnum,requestedoutputs,numoutputs));
+	xfree((void**)&requestedoutputs);
+	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,TransientRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(TransientNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new IntVecParam(TransientRequestedOutputsEnum,requestedoutputs,numoutputs));
+	xfree((void**)&requestedoutputs);
+	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,SteadystateRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(SteadystateNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new IntVecParam(SteadystateRequestedOutputsEnum,requestedoutputs,numoutputs));
+	xfree((void**)&requestedoutputs);
+	
+	/*Before returning, create parameters in case we are running Qmu or control types runs: */
+	#ifdef _HAVE_CONTROL_
+	CreateParametersControl(&parameters,iomodel,solution_type,analysis_type);
+	#endif
+
+	#ifdef _HAVE_DAKOTA_
+	CreateParametersDakota(&parameters,iomodel,solution_type,analysis_type);
+	#endif
+
+	/*Go through all parameters, and convert units to SI: */
+	parameters->UnitConversion(ExtToIuEnum);
+
+	/*Assign output pointer: */
+	*pparameters=parameters;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp	(revision 11330)
@@ -0,0 +1,72 @@
+/*!\file:  CreateSingleNodeToElementConnectivity.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 "../../io/io.h"
+#include "../../include/include.h"
+#include "./ModelProcessorx.h"
+
+void CreateSingleNodeToElementConnectivity(IoModel* iomodel){
+
+	/*Intermediary*/
+	int i,j;
+	int vertexid;
+	int elementswidth;
+	int    dim;
+	int    numberofelements;
+	int    numberofvertices;
+	double* elements=NULL;
+
+	/*output*/
+	int* connectivity=NULL;
+
+	/*Return if connectivity already present*/
+	if(iomodel->singlenodetoelementconnectivity) return;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	elements=iomodel->Data(MeshElementsEnum);
+
+	/*Some checks if debugging*/
+	_assert_(numberofvertices);
+	_assert_(numberofelements);
+	_assert_(iomodel->my_elements);
+	_assert_(elements);
+
+	/*Allocate ouput*/
+	connectivity=(int*)xcalloc(numberofvertices,sizeof(int));
+
+	/*Get element width (3 or 6)*/
+	if (dim==2){
+		elementswidth=3;
+	}
+	else{
+		elementswidth=6;
+	}
+
+	/*Create connectivity table*/
+	for (i=0;i<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 (j=0;j<elementswidth;j++){
+				vertexid=(int)elements[elementswidth*i+j];
+				_assert_(vertexid>0 && vertexid-1<numberofvertices);
+				connectivity[vertexid-1]=i+1;
+			}
+		}
+	}
+
+	/*Assign to iomodel*/
+	iomodel->singlenodetoelementconnectivity=connectivity;
+
+	/*Do not free connectivity!!!*/
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 11330)
@@ -0,0 +1,228 @@
+/*!\file: CreateParametersDakota.cpp
+ * \brief general driver for creating parameters dataset
+ */ 
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../include/include.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void CreateParametersDakota(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
+
+	/*variable declarations: {{{1*/
+	int i,j,k;
+	
+	Parameters* parameters = NULL;
+	int      second_count;
+	
+	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];
+	
+	/*parameters for mass flux: */
+	bool     qmu_mass_flux_present=false;
+	int qmu_mass_flux_num_profiles=0;
+	double** array=NULL;
+	int*     mdims_array=NULL;
+	int*     ndims_array=NULL;
+	
+	double*  matrix=NULL;
+	double*  temp_matrix=NULL;
+	int      M;
+	int      temp_m,temp_n;
+	int      m,n;
+	int      count;
+	bool     dakota_analysis=false;
+	char*    name=NULL;
+	int      numberofresponses;
+	int      numberofvertices;
+	int      nrows;
+	int      ncols;
+
+	/*}}}*/
+	
+	/*recover parameters : */
+	parameters=*pparameters;
+
+	/*recover parameters: */
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+
+	if(dakota_analysis){
+
+		iomodel->Constant(&name,MiscellaneousNameEnum);
+		iomodel->Constant(&numberofresponses,QmuNumberofresponsesEnum);
+		iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+
+		/*name of qmu input, error and output files:{{{1*/
+		qmuinname=(char*)xmalloc((strlen(name)+strlen(".qmu.in")+1)*sizeof(char));
+		sprintf(qmuinname,"%s%s",name,".qmu.in");
+		parameters->AddObject(new   StringParam(QmuInNameEnum,qmuinname));
+
+		qmuoutname=(char*)xmalloc((strlen(name)+strlen(".qmu.out")+1)*sizeof(char));
+		sprintf(qmuoutname,"%s%s",name,".qmu.out");
+		parameters->AddObject(new   StringParam(QmuOutNameEnum,qmuoutname));
+
+		qmuerrname=(char*)xmalloc((strlen(name)+strlen(".qmu.err")+1)*sizeof(char));
+		sprintf(qmuerrname,"%s%s",name,".qmu.err");
+		parameters->AddObject(new   StringParam(QmuErrNameEnum,qmuerrname));
+		/*}}}*/
+		/*Fetch variable descriptors: {{{1*/
+		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: {{{1*/
+		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: {{{1*/
+		/*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=(double*)xmalloc(numberofvertices*sizeof(double));
+			for(i=0;i<numberofvertices;i++)dpart[i]=iomodel->my_vertices[i];
+		}
+		parameters->AddObject(new DoubleVecParam(QmuPartitionEnum,dpart,numberofvertices));
+		/*}}}*/
+		/*Deal with data needed because of qmu variables: {{{1*/
+		
+		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));
+
+				/*Add to parameters: */
+				if(nrows==numberofvertices){
+					parameters->AddObject(new DoubleMatParam(StringToEnumx(tag),dakota_parameter,nrows,ncols));
+				}
+				else{
+					parameters->AddObject(new DoubleTransientMatParam(StringToEnumx(tag),dakota_parameter,nrows,ncols));
+				}
+				
+				/*Free ressources:*/
+				xfree((void**)&dakota_parameter);
+			}
+		}
+		/*}}}*/
+		/*Deal with data needed to compute qmu responses: {{{1*/
+		for(i=0;i<numresponsedescriptors;i++){
+			
+			if(strncmp(responsedescriptors[i],"indexed_MassFlux",16)==0){
+				qmu_mass_flux_present=true;
+			}
+		}
+		
+		
+		if(qmu_mass_flux_present){
+			
+			/*Fetch the mass flux segments necessary to compute the mass fluxes.  Build a DoubleMatArrayParam object out of them: */ 
+			iomodel->FetchData(&array,&mdims_array,&ndims_array,&qmu_mass_flux_num_profiles,QmuMassFluxSegmentsEnum);
+			if(qmu_mass_flux_num_profiles==0)_error_(" qmu_mass_flux_num_profiles is 0, when MassFlux computations were requested!");
+
+			/*Go through segments, and extract those that belong to this cpu: */
+			for(i=0;i<qmu_mass_flux_num_profiles;i++){
+				temp_matrix=array[i];
+				temp_m=mdims_array[i];
+				temp_n=ndims_array[i];
+
+				m=0;
+				for(j=0;j<temp_m;j++){
+					if (  iomodel->my_elements[(int)(*(temp_matrix+5*j+4))-1])m++;
+				}
+				if(m){
+					matrix=(double*)xcalloc(5*m,sizeof(double));
+					count=0;
+					for(j=0;j<temp_m;j++){
+						if (iomodel->my_elements[(int)*(temp_matrix+5*j+4)-1]){
+							for(k=0;k<5;k++)*(matrix+5*count+k)=*(temp_matrix+5*j+k);
+							count++;
+						}
+					}
+				}
+				else{
+					matrix=NULL;
+				}
+
+				/*Assign: */
+				array[i]=matrix;
+				mdims_array[i]=m;
+				ndims_array[i]=5;
+
+				/*Free temporary matrix: */
+				xfree((void**)&temp_matrix);
+			}
+
+			/*Ok, we have an array of segments, different on every cpu. Create a DoubleMatArrayParam object with it: */
+			parameters->AddObject(new DoubleMatArrayParam(QmuMassFluxSegmentsEnum,array,qmu_mass_flux_num_profiles,mdims_array,ndims_array));
+
+			/*Free data: */
+			for(i=0;i<qmu_mass_flux_num_profiles;i++){
+				double* matrix=array[i];
+				xfree((void**)&matrix);
+			}
+			xfree((void**)&mdims_array); 
+			xfree((void**)&ndims_array);
+			xfree((void**)&array);
+		}
+		/*}}}*/
+		/*Free data: {{{1*/
+		for(i=0;i<numresponsedescriptors;i++){
+			descriptor=responsedescriptors[i];
+			xfree((void**)&descriptor);
+		}
+		xfree((void**)&responsedescriptors);
+
+		for(i=0;i<numvariabledescriptors;i++){
+			descriptor=variabledescriptors[i];
+			xfree((void**)&descriptor);
+		}
+		xfree((void**)&variabledescriptors);
+		xfree((void**)&part);
+		xfree((void**)&dpart);
+		xfree((void**)&qmuinname);
+		xfree((void**)&qmuerrname);
+		xfree((void**)&qmuoutname);
+		/*}}}*/
+	} //if(dakota_analysis)
+
+	/*Free data*/
+	xfree((void**)&name);
+
+	/*Assign output pointer: */
+	*pparameters=parameters;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp	(revision 11330)
@@ -0,0 +1,348 @@
+/*
+ * CreateConstraintsDiagnosticHoriz.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsDiagnosticHoriz(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Intermediary*/
+	int     i,j;
+	int     count;
+	double  yts;
+	double  g;
+	double  rho_ice;
+	double  stokesreconditioning;
+	bool    isstokes,ismacayealpattyn;
+   bool    spcpresent=false;
+	int Mx,Nx;
+	int My,Ny;
+	int Mz,Nz;
+	double *spcvx          = NULL;
+	double *spcvy          = NULL;
+	double *spcvz          = NULL;
+	double *nodeonmacayeal = NULL;
+	double *nodeonpattyn   = NULL;
+	double *nodeonstokes   = NULL;
+	double *nodeonbed      = NULL;
+	double *nodeonicesheet = NULL;
+	double *vertices_type  = NULL;
+	double *surface        = NULL;
+	double *z              = NULL;
+	double *timesx=NULL;
+	double *timesy=NULL;
+	double *timesz=NULL;
+   double* values=NULL;
+
+	/*Output*/
+	Constraints *constraints      = NULL;
+	SpcStatic   *spcstatic        = NULL;
+	int          node1,node2;
+	int          dim;
+	int          numberofvertices;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&g,ConstantsGEnum);
+	iomodel->Constant(&rho_ice,MaterialsRhoIceEnum);
+	iomodel->Constant(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
+	iomodel->Constant(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
+
+	/*Recover pointer: */
+	constraints=*pconstraints;
+
+	/*Create constraints if they do not exist yet*/
+	if(!constraints) constraints = new Constraints();
+	
+	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
+	if (!ismacayealpattyn & !isstokes){
+		*pconstraints=constraints;
+		return;
+	}
+	
+	/*Constraints: fetch data: */
+	iomodel->FetchData(&spcvx,&Mx,&Nx,DiagnosticSpcvxEnum);
+	iomodel->FetchData(&spcvy,&My,&Ny,DiagnosticSpcvyEnum);
+	iomodel->FetchData(&spcvz,&Mz,&Nz,DiagnosticSpcvzEnum);
+	iomodel->FetchData(&nodeonmacayeal,NULL,NULL,FlowequationBordermacayealEnum);
+	if(dim==3)iomodel->FetchData(&nodeonpattyn,NULL,NULL,FlowequationBorderpattynEnum);
+	if(dim==3)iomodel->FetchData(&nodeonstokes,NULL,NULL,FlowequationBorderstokesEnum);
+	if(dim==3)iomodel->FetchData(&nodeonbed,NULL,NULL,MeshVertexonbedEnum);
+	if(dim==3)iomodel->FetchData(&nodeonicesheet,NULL,NULL,MaskVertexongroundediceEnum);
+	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=(double*)xmalloc(Nx*sizeof(double));
+	for(j=0;j<Nx;j++){
+		timesx[j]=spcvx[(Mx-1)*Nx+j];
+	}
+	/*unit conversion: */
+	UnitConversion(timesx,Nx,ExtToIuEnum,TimeEnum);
+	/*figure out times: */
+	timesy=(double*)xmalloc(Ny*sizeof(double));
+	for(j=0;j<Ny;j++){
+		timesy[j]=spcvy[(My-1)*Ny+j];
+	}
+	/*unit conversion: */
+	UnitConversion(timesy,Ny,ExtToIuEnum,TimeEnum);
+	/*figure out times: */
+	timesz=(double*)xmalloc(Nz*sizeof(double));
+	for(j=0;j<Nz;j++){
+		timesz[j]=spcvz[(Mz-1)*Nz+j];
+	}
+	/*unit conversion: */
+	UnitConversion(timesz,Nz,ExtToIuEnum,TimeEnum);
+
+
+	/*Create spcs from x,y,z, as well as the spc values on those spcs: */
+	for (i=0;i<numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
+
+			/*Start with adding spcs of coupling: zero at the border macayeal/pattyn for the appropriate dofs*/
+			if ((int)vertices_type[i]==MacAyealPattynApproximationEnum){
+				/*If grionmacayeal, spc pattyn dofs: 3 & 4*/
+					if ((int)nodeonpattyn[i]){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!isnan(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!isnan(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else if ((int)nodeonmacayeal[i]){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!isnan(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!isnan(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else _error_("if vertices_type is MacAyealPattyn, you shoud have nodeonpattyn or nodeonmacayeal");
+			}
+			/*Also add spcs of coupling: zero at the border pattyn/stokes for the appropriate dofs*/
+			else if ((int)vertices_type[i]==PattynStokesApproximationEnum){
+				/*If grion,pattyn spc stokes dofs: 3 4 & 5*/
+					if ((int)nodeonpattyn[i]){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!isnan(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!isnan(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else if ((int)nodeonstokes[i]){ //spc pattyn nodes: 1 & 2
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!isnan(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!isnan(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!isnan(spcvz[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,spcvz[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+					}
+					else _error_("if vertices_type is PattynStokes, you shoud have nodeonpattyn or nodeonstokes");
+			}
+			/*Also add spcs of coupling: zero at the border pattyn/stokes for the appropriate dofs*/
+			else if ((int)vertices_type[i]==MacAyealStokesApproximationEnum){
+				/*If grion,pattyn spc stokes dofs: 3 4 & 5*/
+					if ((int)nodeonmacayeal[i]){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!isnan(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!isnan(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else if ((int)nodeonstokes[i]){ //spc macayeal nodes: 1 & 2
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!isnan(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!isnan(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!isnan(spcvz[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,spcvz[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+					}
+					else _error_("if vertices_type is MacAyealStokes, you shoud have nodeonmacayeal or nodeonstokes");
+			}
+			/*Now add the regular spcs*/
+			else{
+				if (Mx==numberofvertices && !isnan(spcvx[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+					count++;
+				}
+				else if (Mx==numberofvertices+1) {
+					/*figure out times and values: */
+					values=(double*)xmalloc(Nx*sizeof(double));
+					spcpresent=false;
+					for(j=0;j<Nx;j++){
+						values[j]=spcvx[i*Nx+j]/yts;
+						if(!isnan(values[j]))spcpresent=true; //NaN means no spc by default
+					}
+
+					if(spcpresent){
+						constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,Nx,timesx,values,DiagnosticHorizAnalysisEnum));
+						count++;
+					}
+					xfree((void**)&values);
+				}
+				else if (vertices_type[i]==HutterApproximationEnum){
+					constraints->AddObject(new SpcDynamic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,DiagnosticHorizAnalysisEnum));
+					count++;
+				}
+
+				if (My==numberofvertices && !isnan(spcvy[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vy.
+					count++;
+				}
+				else if (My==numberofvertices+1){
+					/*figure out times and values: */
+					values=(double*)xmalloc(Ny*sizeof(double));
+					spcpresent=false;
+					for(j=0;j<Ny;j++){
+						values[j]=spcvy[i*Ny+j]/yts;
+						if(!isnan(values[j]))spcpresent=true; //NaN means no spc by default
+					}
+					if(spcpresent){
+						constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,Ny,timesy,values,DiagnosticHorizAnalysisEnum));
+						count++;
+					}
+					xfree((void**)&values);
+				}
+				else if (vertices_type[i]==HutterApproximationEnum){
+					constraints->AddObject(new SpcDynamic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,DiagnosticHorizAnalysisEnum));
+					count++;
+				}
+
+				if ((int)vertices_type[i]==StokesApproximationEnum ||  ((int)vertices_type[i]==NoneApproximationEnum)){
+					if (Mz==numberofvertices && !isnan(spcvz[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvz[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
+						count++;
+					}
+					else if (Mz==numberofvertices+1){
+						/*figure out times and values: */
+						values=(double*)xmalloc(Nz*sizeof(double));
+						spcpresent=false;
+						for(j=0;j<Nz;j++){
+							values[j]=spcvz[i*Nz+j]/yts;
+							if(!isnan(values[j]))spcpresent=true; //NaN means no spc by default
+						}
+						if(spcpresent){
+							constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,Nz,timesz,values,DiagnosticHorizAnalysisEnum));
+							count++;
+						}
+						xfree((void**)&values);
+					}
+
+				}
+				if ((int)vertices_type[i]==NoneApproximationEnum){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,g*rho_ice*(surface[i]-z[i])/stokesreconditioning,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
+					count++;
+				}
+			}
+
+			/*Constraint at the bedrock interface (v.n = vz = 0) (Coordinates will be updated according to the bed slope)*/
+			if (dim==3) if(nodeonbed[i] && nodeonicesheet[i] && nodeonstokes[i]){
+				 switch((int)vertices_type[i]){
+					case MacAyealStokesApproximationEnum:
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0.,DiagnosticHorizAnalysisEnum));
+						count++;
+						break;
+					case PattynStokesApproximationEnum:
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0.,DiagnosticHorizAnalysisEnum));
+						count++;
+						break;
+					case StokesApproximationEnum:
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0.,DiagnosticHorizAnalysisEnum));
+						count++;
+						break;
+					default: _error_("Vertex approximation %s not supported",EnumToStringx((int)vertices_type[i]));
+				}
+			}
+		}
+	}
+	  
+	/*Free data: */
+	xfree((void**)&spcvx);
+	xfree((void**)&spcvy);
+	xfree((void**)&spcvz);
+	xfree((void**)&nodeonmacayeal);
+	xfree((void**)&nodeonpattyn);
+	xfree((void**)&nodeonstokes);
+	xfree((void**)&nodeonicesheet);
+	xfree((void**)&nodeonbed);
+	xfree((void**)&vertices_type);
+	xfree((void**)&surface);
+	xfree((void**)&z);
+
+	/*Free resources:*/
+	xfree((void**)&timesx);
+	xfree((void**)&timesy);
+	xfree((void**)&timesz);
+	xfree((void**)&values);
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp	(revision 11330)
@@ -0,0 +1,164 @@
+/*! \file CreateLoadsDiagnosticHoriz.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsDiagnosticHoriz(Loads** ploads, IoModel* iomodel){
+
+	/*DataSets*/
+	Loads     *loads     = NULL;
+	Icefront  *icefront  = NULL;
+	Riftfront *riftfront = NULL;
+	Pengrid   *pengrid   = NULL;
+
+	/*Intermediary*/
+	int segment_width;
+	int element;
+	int i;
+	int count=0;
+	int penpair_ids[2];
+	int dim;
+	int numberofvertices;
+	bool ismacayealpattyn,isstokes;
+	int  numpenalties,numberofpressureloads,numrifts,numriftsegments;
+	double *pressureload   = NULL;
+	double *elements_type  = NULL;
+	double *nodeoniceshelf = NULL;
+	double *riftinfo       = NULL;
+	double *nodeonbed      = NULL;
+	double *nodeonstokes   = NULL;
+	double *nodeonicesheet = NULL;
+	double *vertices_type  = NULL;
+	double *penalties      = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
+	iomodel->Constant(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
+	iomodel->Constant(&numrifts,RiftsNumriftsEnum);
+
+	/*Recover pointer: */
+	loads=*ploads;
+
+	/*Create loads if they do not exist yet*/
+	if(!loads) loads = new Loads();
+
+	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
+	if (!ismacayealpattyn & !isstokes){
+		*ploads=loads;
+		return;
+	}
+	
+	/*Create pressure loads as boundary conditions. Pay attention to the partitioning if we are running in parallel (the nodes
+	 * referenced by a certain load must belong to the cluster node): */
+	iomodel->FetchData(3,DiagnosticIcefrontEnum,ThicknessEnum,BedEnum);
+	iomodel->FetchData(&pressureload,&numberofpressureloads,NULL,DiagnosticIcefrontEnum);
+	iomodel->FetchData(&elements_type,NULL,NULL,FlowequationElementEquationEnum);
+
+	/*Initialize counter: */
+	count=0;
+
+	/*First load data:*/
+	for (i=0;i<numberofpressureloads;i++){
+		
+		/*Retrieve element to which this icefront belongs: */
+		if (dim==2) segment_width=4; 
+		else segment_width=6;
+		element=(int)(*(pressureload+segment_width*i+segment_width-2)-1); //element is in the penultimate column (node1 node2 ... elem fill)
+
+		/*Now, if this element is not in the partition, pass: */
+		if(!iomodel->my_elements[element]) continue;
+		
+		/*Do not create ice front if Hutter or Stokes elements*/
+		if ((int)*(elements_type+element)==HutterApproximationEnum) continue;
+
+		/*Create and  add load: */
+		if ((int)*(elements_type+element)==(MacAyealApproximationEnum) && dim==2){
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal2dIceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+		}
+		else if ((int)*(elements_type+element)==(MacAyealApproximationEnum) && dim==3){
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal3dIceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+		}
+		else if ((int)*(elements_type+element)==(PattynApproximationEnum)){
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,PattynIceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+		}
+		else if ((int)*(elements_type+element)==(StokesApproximationEnum)){
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,StokesIceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+		}
+		else if ((int)*(elements_type+element)==(MacAyealPattynApproximationEnum)){
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal3dIceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,PattynIceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+		}
+		else if ((int)*(elements_type+element)==(PattynStokesApproximationEnum)){
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,PattynIceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,StokesIceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+		}
+		else if ((int)*(elements_type+element)==(MacAyealStokesApproximationEnum)){
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal3dIceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,StokesIceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(3,DiagnosticIcefrontEnum,ThicknessEnum,BedEnum);
+	xfree((void**)&elements_type);
+	xfree((void**)&pressureload);
+
+	/*Create Penpair for penalties: */
+	iomodel->FetchData(&penalties,&numpenalties,NULL,DiagnosticVertexPairingEnum);
+	
+	for(i=0;i<numpenalties;i++){
+
+		if(iomodel->my_vertices[(int)penalties[2*i+0]-1]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			_assert_(iomodel->my_vertices[(int)penalties[2*i+1]-1]);
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+(int)penalties[2*i+0];
+			penpair_ids[1]=iomodel->nodecounter+(int)penalties[2*i+1];
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(iomodel->loadcounter+count+1,&penpair_ids[0],DiagnosticHorizAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	xfree((void**)&penalties);
+
+	/*Create Riffront loads for rifts: */
+	if(numrifts){
+		iomodel->FetchData(&riftinfo,&numriftsegments,NULL,RiftsRiftstructEnum);
+		iomodel->FetchData(5,RiftsRiftstructEnum,ThicknessEnum,BedEnum,SurfaceEnum,MaskVertexonfloatingiceEnum);
+		for(i=0;i<numriftsegments;i++){
+			if(iomodel->my_elements[(int)*(riftinfo+RIFTINFOSIZE*i+2)-1]){
+				loads->AddObject(new Riftfront(iomodel->loadcounter+count+1,i,iomodel,DiagnosticHorizAnalysisEnum));
+				count++;
+			}
+		}
+		iomodel->DeleteData(5,RiftsRiftstructEnum,ThicknessEnum,BedEnum,SurfaceEnum,MaskVertexonfloatingiceEnum);
+		xfree((void**)&riftfront);
+	}
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp	(revision 11330)
@@ -0,0 +1,65 @@
+/*
+ * CreateNodesDiagnosticHoriz.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesDiagnosticHoriz(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	bool   continuous_galerkin=true;
+	int    numberofvertices;
+	bool   isstokes,ismacayealpattyn;
+
+	/*DataSets: */
+	Nodes*    nodes = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
+	iomodel->Constant(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
+
+	/*Recover pointer: */
+	nodes=*pnodes;
+
+	/*First create nodes*/
+	if(!nodes) nodes = new Nodes();
+	
+	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
+	if(!ismacayealpattyn & !isstokes){
+		*pnodes=nodes;
+		return;
+	}
+
+	/*Continuous Galerkin partition of nodes: */
+	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
+
+	/*Create nodes: */
+	iomodel->FetchData(9,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBordermacayealEnum,FlowequationBorderstokesEnum,
+				MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,MaskVertexonwaterEnum,FlowequationVertexEquationEnum,DiagnosticReferentialEnum);
+	
+	for (i=0;i<numberofvertices;i++){
+
+		if(iomodel->my_vertices[i]){
+			
+			/*Add node to nodes dataset: */
+			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,DiagnosticHorizAnalysisEnum));
+		}
+	}
+
+	/*Clean fetched data: */
+	iomodel->DeleteData(9,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBordermacayealEnum,FlowequationBorderstokesEnum,
+				MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,MaskVertexonwaterEnum,FlowequationVertexEquationEnum,DiagnosticReferentialEnum);
+
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp	(revision 11330)
@@ -0,0 +1,97 @@
+/*
+ * UpdateElementsDiagnosticHoriz:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../modules/modules.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsDiagnosticHoriz(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    dim;
+	int    numberofelements;
+	bool   ismacayealpattyn;
+	bool   isstokes;
+	bool   control_analysis;
+	bool   dakota_analysis;
+
+	/*Fetch constants needed: */
+	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
+	iomodel->Constant(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+
+	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
+	if(!ismacayealpattyn & !isstokes) return;
+
+	/*Fetch data needed: */
+	iomodel->FetchData(2,MeshElementsEnum,FlowequationElementEquationEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type); //we need i to index into elements.
+			counter++;
+		}
+	}
+
+	/*Create inputs: */
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,GeometryHydrostaticRatioEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+	iomodel->FetchDataToInput(elements,FrictionPEnum);
+	iomodel->FetchDataToInput(elements,FrictionQEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+
+	if (dim==3){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+		iomodel->FetchDataToInput(elements,VzEnum);
+		iomodel->FetchDataToInput(elements,SurfaceforcingsAccumulationRateEnum);
+		iomodel->FetchDataToInput(elements,SurfaceforcingsAblationRateEnum);
+		iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+		iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+		iomodel->FetchDataToInput(elements,FlowequationBorderstokesEnum);
+	}
+
+	if(control_analysis){
+		iomodel->FetchDataToInput(elements,InversionVxObsEnum);
+		iomodel->FetchDataToInput(elements,InversionVyObsEnum);
+	}
+
+	/*Post-process: */
+	elements->InputDuplicate(VxEnum,VxPicardEnum);
+	elements->InputDuplicate(VxEnum,InversionVxObsEnum);
+	if(dakota_analysis)elements->InputDuplicate(VxEnum,QmuVxEnum);
+	
+	elements->InputDuplicate(VyEnum,VyPicardEnum);
+	elements->InputDuplicate(VyEnum,InversionVyObsEnum);
+	if(dakota_analysis)elements->InputDuplicate(VyEnum,QmuVyEnum);
+	
+	if(dim==3){
+		elements->InputDuplicate(VzEnum,VzPicardEnum);
+		elements->InputDuplicate(VzEnum,InversionVzObsEnum);
+		if(dakota_analysis)elements->InputDuplicate(VzEnum,QmuVzEnum);
+	}
+	
+	/*Free data: */
+	iomodel->DeleteData(2,MeshElementsEnum,FlowequationElementEquationEnum);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp	(revision 11330)
@@ -0,0 +1,80 @@
+/*
+ * CreateConstraintsDiagnosticHutter.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsDiagnosticHutter(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	int count;
+	double yts;
+	int    numberofvertices;
+	bool   ishutter;
+
+	/*Output*/
+	Constraints* constraints = NULL;
+	SpcStatic*    spcstatic  = NULL;
+
+	/*Recover pointer: */
+	constraints=*pconstraints;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&ishutter,FlowequationIshutterEnum);
+
+	/*Create constraints if they do not exist yet*/
+	if(!constraints) constraints = new Constraints();
+
+	/*Now, is the flag ishutter on? otherwise, do nothing: */
+	if (!ishutter){
+		*pconstraints=constraints;
+		return;
+	}
+
+	/*Fetch data: */
+	iomodel->FetchData(3,DiagnosticSpcvxEnum,DiagnosticSpcvyEnum,FlowequationVertexEquationEnum);
+
+	/*Initialize conunter*/
+	count=0;
+
+	/*vx and vy are spc'd if we are not on nodeonhutter: */
+	for (i=0;i<numberofvertices;i++){
+		/*keep only this partition's nodes:*/
+		if((iomodel->my_vertices[i])){
+			if (!(int)iomodel->Data(FlowequationVertexEquationEnum)[i]==HutterApproximationEnum){
+
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticHutterAnalysisEnum));
+				count++;
+
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,DiagnosticHutterAnalysisEnum));
+				count++;
+			}
+			else{
+				if (!isnan(iomodel->Data(DiagnosticSpcvxEnum)[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,iomodel->Data(DiagnosticSpcvxEnum)[i]/yts,DiagnosticHutterAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+					count++;
+				}
+
+				if (!isnan(iomodel->Data(DiagnosticSpcvyEnum)[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,iomodel->Data(DiagnosticSpcvyEnum)[i]/yts,DiagnosticHutterAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
+					count++;
+				}
+			}
+		}
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(3,DiagnosticSpcvxEnum,DiagnosticSpcvyEnum,FlowequationVertexEquationEnum);
+	
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp	(revision 11330)
@@ -0,0 +1,26 @@
+/*! \file CreateLoadsDiagnosticHutter.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsDiagnosticHutter(Loads** ploads, IoModel* iomodel){
+
+	/*DataSet*/
+	Loads* loads=NULL;
+
+	/*Recover pointer: */
+	loads=*ploads;
+
+	/*Create loads if they do not exist yet*/
+	if(!loads) loads = new Loads();
+	
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp	(revision 11330)
@@ -0,0 +1,62 @@
+/*
+ * CreateNodesDiagnosticHutter.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesDiagnosticHutter(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	bool continuous_galerkin=true;
+	int    numberofvertices;
+	bool   ishutter;
+
+	/*DataSets: */
+	Nodes*    nodes = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&ishutter,FlowequationIshutterEnum);
+
+	/*Recover pointer: */
+	nodes=*pnodes;
+
+	/*Create nodes if they do not exist yet*/
+	if(!nodes) nodes = new Nodes();
+
+	/*Now, is the flag ishutter on? otherwise, do nothing: */
+	if(!ishutter){
+		*pnodes=nodes;
+		return;
+	}
+
+	/*Continuous Galerkin partition of nodes: */
+	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
+
+	/*First fetch data: */
+	iomodel->FetchData(7,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,MeshElementsEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+
+	for (i=0;i<numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
+
+			/*Add node to nodes dataset: */
+			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,DiagnosticHutterAnalysisEnum));
+
+		}
+	}
+
+	/*Clean fetched data: */
+	iomodel->DeleteData(7,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,MeshElementsEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp	(revision 11330)
@@ -0,0 +1,46 @@
+/*
+ * UpdateElementsDiagnosticHutter:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../modules/modules.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsDiagnosticHutter(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    numberofelements;
+	bool   ishutter;
+
+	
+	/*Fetch data needed: */
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&ishutter,FlowequationIshutterEnum);
+
+	/*Now, is the flag hutter on? otherwise, do nothing: */
+	if (!ishutter)return;
+
+	iomodel->FetchData(2,MeshElementsEnum,FlowequationElementEquationEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type); //we need i to index into elements.
+			counter++;
+		}
+	}
+	
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,GeometryHydrostaticRatioEnum);
+	
+	/*Free data: */
+	iomodel->DeleteData(2,MeshElementsEnum,FlowequationElementEquationEnum);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp	(revision 11330)
@@ -0,0 +1,72 @@
+/*
+ * CreateConstraintsDiagnosticHoriz.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsDiagnosticVert(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	int dim;
+	int count;
+	double yts;
+	int    numberofvertices;
+
+	/*Output*/
+	Constraints* constraints = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+
+	/*Recover pointer: */
+	constraints=*pconstraints;
+
+	/*Create constraints if they do not exist yet*/
+	if(!constraints) constraints = new Constraints();
+
+	/*return if 2d mesh*/
+	if(dim==2){
+		*pconstraints=constraints;
+		return;
+	}
+
+	/*Fetch data: */
+	iomodel->FetchData(2,DiagnosticSpcvzEnum,FlowequationBorderstokesEnum);
+
+	/*Initialize counter*/
+	count=0;
+
+	/*Create spcs from x,y,z, as well as the spc values on those spcs: */
+	for (i=0;i<numberofvertices;i++){
+
+		/*keep only this partition's nodes:*/
+		if(iomodel->my_vertices[i]){
+
+			if ((int)iomodel->Data(FlowequationBorderstokesEnum)[i]){
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticVertAnalysisEnum)); //spc to zero as vertical velocity is done in Horiz for Stokes
+				count++;
+			}
+			else if (!isnan(iomodel->Data(DiagnosticSpcvzEnum)[i])){
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,
+								iomodel->Data(DiagnosticSpcvzEnum)[i]/yts,DiagnosticVertAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+				count++;
+
+			}
+		} 
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(2,DiagnosticSpcvzEnum,FlowequationBorderstokesEnum);
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp	(revision 11330)
@@ -0,0 +1,26 @@
+/*! \file CreateLoadsDiagnosticVert.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsDiagnosticVert(Loads** ploads, IoModel* iomodel){
+
+	/*DataSet*/
+	Loads* loads=NULL;
+
+	/*Recover pointer: */
+	loads=*ploads;
+
+	/*Create loads if they do not exist yet*/
+	if(!loads) loads = new Loads();
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp	(revision 11330)
@@ -0,0 +1,62 @@
+/*
+ * CreateNodesDiagnosticVert.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesDiagnosticVert(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	bool continuous_galerkin=true;
+	int    dim;
+	int    numberofvertices;
+
+	/*DataSets: */
+	Nodes*    nodes = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+
+	/*Recover pointer: */
+	nodes=*pnodes;
+
+	/*Create nodes if they do not exist yet*/
+	if(!nodes) nodes = new Nodes();
+
+	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
+	if (dim==2){
+		*pnodes=nodes;
+		return;
+	}
+
+	/*Continuous Galerkin partition of nodes: */
+	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
+	
+	/*First fetch data: */
+	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+
+	for (i=0;i<numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
+
+			/*Add node to nodes dataset: */
+			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,DiagnosticVertAnalysisEnum));
+
+		}
+	}
+
+	/*Clean fetched data: */
+	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+	
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp	(revision 11330)
@@ -0,0 +1,59 @@
+/*
+ * UpdateElementsDiagnosticVert:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../modules/modules.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsDiagnosticVert(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    dim;
+	int    numberofelements;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if (dim==2)return;
+
+	/*Fetch data needed: */
+	iomodel->FetchData(1,MeshElementsEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type); //we need i to index into elements.
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,GeometryHydrostaticRatioEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsAccumulationRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsAblationRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+
+	/*Free data: */
+	iomodel->DeleteData(1,MeshElementsEnum);
+	
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 11330)
@@ -0,0 +1,99 @@
+/*!\file:  DistributeNumDofs.cpp
+ * \brief: figure out the maximum number of dofs per node.
+ */ 
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+	
+void DistributeNumDofs(DofIndexing* index,int analysis_type,double* vertices_type){
+
+	/*For now, we distribute by analysis_type, later, we will distribute using the analysis_type,
+	 * but also the vertices_type: */
+
+	int numdofs=2; //default numdofs
+	int i;
+	int* doftype=NULL;
+
+	/*ok, according to analysis type: */
+	if (analysis_type==DiagnosticHorizAnalysisEnum){
+		if (vertices_type[0]==MacAyealApproximationEnum){
+			numdofs=2;
+		}
+		else if (vertices_type[0]==PattynApproximationEnum){
+			numdofs=2;
+		}
+		else if (vertices_type[0]==HutterApproximationEnum){
+			numdofs=2;
+		}
+		else if (vertices_type[0]==StokesApproximationEnum){
+			numdofs=4;
+		}
+		else if (vertices_type[0]==NoneApproximationEnum){
+			numdofs=4;
+		}
+		else if (vertices_type[0]==MacAyealPattynApproximationEnum){
+			numdofs=4;
+			doftype=(int*)xmalloc(numdofs*sizeof(int));
+			doftype[0]=MacAyealApproximationEnum;
+			doftype[1]=MacAyealApproximationEnum;
+			doftype[2]=PattynApproximationEnum;
+			doftype[3]=PattynApproximationEnum;
+		}
+		else if (vertices_type[0]==PattynStokesApproximationEnum){
+			numdofs=6;
+			doftype=(int*)xmalloc(numdofs*sizeof(int));
+			doftype[0]=PattynApproximationEnum;
+			doftype[1]=PattynApproximationEnum;
+			doftype[2]=StokesApproximationEnum;
+			doftype[3]=StokesApproximationEnum;
+			doftype[4]=StokesApproximationEnum;
+			doftype[5]=StokesApproximationEnum;
+		}
+		else if (vertices_type[0]==MacAyealStokesApproximationEnum){
+			numdofs=6;
+			doftype=(int*)xmalloc(numdofs*sizeof(int));
+			doftype[0]=MacAyealApproximationEnum;
+			doftype[1]=MacAyealApproximationEnum;
+			doftype[2]=StokesApproximationEnum;
+			doftype[3]=StokesApproximationEnum;
+			doftype[4]=StokesApproximationEnum;
+			doftype[5]=StokesApproximationEnum;
+		}
+		else _error_("Approximationtype %i (%s) not implemented yet for DiagnosticHoriz",(int)*vertices_type,EnumToStringx((int)*vertices_type));
+	}
+	else if (analysis_type==DiagnosticVertAnalysisEnum){
+		numdofs=1;
+	}
+	else if (analysis_type==DiagnosticHutterAnalysisEnum){
+		numdofs=2;
+	}
+	else if (analysis_type==BedSlopeAnalysisEnum || analysis_type==SurfaceSlopeAnalysisEnum){
+		numdofs=1;
+	}
+	else if (analysis_type==ThermalAnalysisEnum){
+		numdofs=1;
+	}
+	else if (analysis_type==EnthalpyAnalysisEnum){
+		numdofs=1;
+	}
+	else if (analysis_type==HydrologyAnalysisEnum){
+		numdofs=1;
+	}
+	else if (analysis_type==MeltingAnalysisEnum){
+		numdofs=1;
+	}
+	else if (analysis_type==PrognosticAnalysisEnum){
+		numdofs=1;
+	}
+	else if (analysis_type==BalancethicknessAnalysisEnum){
+		numdofs=1;
+	}
+	else _error_("analysis type: %i (%s) not implemented yet",analysis_type,EnumToStringx(analysis_type));
+
+	/*Now initialize the index*/
+	index->Init(numdofs,doftype);
+
+	/*Clean up*/
+	 xfree((void**)&doftype);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 11330)
@@ -0,0 +1,154 @@
+/*!\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 "../../objects/objects.h"
+#include "../../shared/shared.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../io/io.h"
+#include "../../include/include.h"
+#include "../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx/ModelProcessorx.h"
+
+void  ElementsAndVerticesPartitioning(bool** pmy_elements, int** pmy_vertices, IoModel* iomodel){
+
+	int i;
+
+	extern int my_rank;
+	extern int num_procs;
+	int    numberofelements;
+	int    numberofvertices;
+	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    dim;
+	double* elements=NULL;
+	double* elements2d=NULL;
+	double* riftinfo=NULL;
+	double* vertex_pairing=NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&numberofelements2d,MeshNumberofelements2dEnum);
+	iomodel->Constant(&numberofvertices2d,MeshNumberofvertices2dEnum);
+	iomodel->Constant(&numlayers,MeshNumberoflayersEnum);
+	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: */
+	if(dim==2) elements_width=3; //tria elements
+	else elements_width=6; //penta elements
+
+	#ifdef _PARALLEL_
+	/*Determine parallel partitioning of elements: we use Metis for now. First load the data, then partition*/
+	if(dim==2){
+		/*load elements: */
+		iomodel->FetchData(&elements,NULL,NULL,MeshElementsEnum);
+	}
+	else{
+		/*load elements2d: */
+		iomodel->FetchData(&elements2d,NULL,NULL,MeshElements2dEnum);
+	}
+
+	MeshPartitionx(&epart, &npart,numberofelements,numberofvertices,elements, numberofelements2d,numberofvertices2d,elements2d,numlayers,elements_width, dim,num_procs);
+
+	/*Free elements and elements2d: */
+	xfree((void**)&elements);
+	xfree((void**)&elements2d);
+
+	#else
+	/*In serial mode, epart is full of 0: all elements belong to cpu 0: */
+	epart=(int*)xcalloc(numberofelements,sizeof(int));
+	#endif
+
+	/*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=(int)*(riftinfo+RIFTINFOSIZE*i+2)-1; //matlab indexing to c indexing
+			el2=(int)*(riftinfo+RIFTINFOSIZE*i+3)-1; //matlab indexing to c indexing
+			epart[el2]=epart[el1]; //ensures that this pair of elements will be in the same partition, as well as the corresponding vertices;
+		}
+		xfree((void**)&riftinfo); 
+	}
+
+	/*Used later on: */
+	my_vertices=(int*)xcalloc(numberofvertices,sizeof(int));
+	my_elements=(bool*)xcalloc(numberofelements,sizeof(bool));
+
+	/*Start figuring out, out of the partition, which elements belong to this cpu: */
+	iomodel->FetchData(&elements,NULL,NULL,MeshElementsEnum);
+	for (i=0;i<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*/
+			my_vertices[(int)*(elements+elements_width*i+0)-1]=1;
+			my_vertices[(int)*(elements+elements_width*i+1)-1]=1;
+			my_vertices[(int)*(elements+elements_width*i+2)-1]=1;
+			
+			if(elements_width==6){
+				my_vertices[(int)*(elements+elements_width*i+3)-1]=1;
+				my_vertices[(int)*(elements+elements_width*i+4)-1]=1;
+				my_vertices[(int)*(elements+elements_width*i+5)-1]=1;
+			}
+		}
+	}//for (i=0;i<numberofelements;i++)
+	/*Free data : */
+	xfree((void**)&elements);
+
+	/*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,DiagnosticVertexPairingEnum);
+	for(i=0;i<numvertex_pairing;i++){
+		if(my_vertices[(int)vertex_pairing[2*i+0]-1] && !my_vertices[(int)vertex_pairing[2*i+1]-1]){
+			my_vertices[(int)vertex_pairing[2*i+1]-1]=2; //to know that these elements are not on the partition
+		}
+	}
+	xfree((void**)&vertex_pairing);
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,PrognosticVertexPairingEnum);
+	for(i=0;i<numvertex_pairing;i++){
+		if(my_vertices[(int)vertex_pairing[2*i+0]-1] && !my_vertices[(int)vertex_pairing[2*i+1]-1]){
+			my_vertices[(int)vertex_pairing[2*i+1]-1]=2; //to know that these elements are not on the partition
+		}
+	}
+	xfree((void**)&vertex_pairing);
+
+	/*Free ressources:*/
+	xfree((void**)&npart);
+	xfree((void**)&epart);
+
+	/*Assign output pointers:*/
+	*pmy_elements=my_elements;
+	*pmy_vertices=my_vertices;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 11330)
@@ -0,0 +1,71 @@
+/*
+ * CreateConstraintsEnthalpy.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../io/io.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsEnthalpy(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	int count;
+	int    dim;
+	int    numberofvertices;
+	double heatcapacity;
+	double referencetemperature;
+	
+	/*Output*/
+	Constraints* constraints = NULL;
+	SpcStatic*    spcstatic  = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&heatcapacity,MaterialsHeatcapacityEnum);
+	iomodel->Constant(&referencetemperature,ConstantsReferencetemperatureEnum);
+
+	/*Recover pointer: */
+	constraints=*pconstraints;
+
+	/*Create constraints if they do not exist yet*/
+	if(!constraints) constraints = new Constraints();
+
+	/*return if 2d mesh*/
+	if (dim==2){
+		*pconstraints=constraints;
+		return;
+	}
+
+	/*Fetch data: */
+	double *spctemperature=NULL;
+	iomodel->FetchData(&spctemperature,NULL,NULL,ThermalSpctemperatureEnum);
+
+	/*Initialize counter*/
+	count=0;
+
+	/*Create constraints from x,y,z: */
+	for (i=0;i<numberofvertices;i++){
+		/*keep only this partition's nodes:*/
+		if((iomodel->my_vertices[i])){
+
+			if (!isnan(spctemperature[i])){
+
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,heatcapacity*(spctemperature[i]-referencetemperature),EnthalpyAnalysisEnum));
+				count++;
+
+			}
+		}
+	}
+
+	/*Free data: */
+	xfree((void**)&spctemperature);
+	
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp	(revision 11330)
@@ -0,0 +1,27 @@
+/*! \file CreateLoadsEnthalpy.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsEnthalpy(Loads** ploads, IoModel* iomodel){
+
+	/*DataSet*/
+	Loads* loads=NULL;
+
+	/*Recover pointer: */
+	loads=*ploads;
+
+	/*Create loads if they do not exist yet*/
+	if(!loads) loads = new Loads();
+
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp	(revision 11330)
@@ -0,0 +1,54 @@
+/*
+ * CreateNodesEnthalpy.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesEnthalpy(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	bool continuous_galerkin=true;
+	int    numberofvertices;
+
+	/*DataSets: */
+	Nodes*    nodes = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	
+	/*Recover pointer: */
+	nodes=*pnodes;
+
+	/*Create nodes if they do not exist yet*/
+	if(!nodes) nodes = new Nodes();
+
+	/*Continuous Galerkin partition of nodes: */
+	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
+
+	/*Create nodes and vertices: */
+	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+
+	for (i=0;i<numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
+			
+			/*Add node to nodes dataset: */
+			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,EnthalpyAnalysisEnum));
+
+		}
+	}
+
+	/*Clean fetched data: */
+	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+	
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp	(revision 11330)
@@ -0,0 +1,64 @@
+/*
+ * UpdateElementsEnthalpy:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../modules/modules.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsEnthalpy(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    dim;
+	int    numberofelements;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if(dim==2)return;
+
+	/*Fetch data needed: */
+	iomodel->FetchData(4,MeshElementsEnum,TemperatureEnum,WaterfractionEnum,PressureEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type); //we need i to index into elements.
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+	iomodel->FetchDataToInput(elements,FrictionPEnum);
+	iomodel->FetchDataToInput(elements,FrictionQEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
+	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,BasalforcingsGeothermalfluxEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,VzEnum);
+	
+	/*Free data: */
+	iomodel->DeleteData(4,MeshElementsEnum,TemperatureEnum,WaterfractionEnum,PressureEnum);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp	(revision 11330)
@@ -0,0 +1,28 @@
+/*
+ * CreateConstraintsHydrology.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../modules/modules.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../io/io.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsHydrology(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Output*/
+	Constraints *constraints = NULL;
+
+	/*Recover pointer: */
+	constraints=*pconstraints;
+
+	/*Create constraints if they do not exist yet*/
+	if(!constraints) constraints = new Constraints();
+	IoModelToConstraintsx(constraints,iomodel,HydrologySpcwatercolumnEnum,HydrologyAnalysisEnum);
+	
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp	(revision 11330)
@@ -0,0 +1,29 @@
+/*! \file CreateLoadsHydrology.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsHydrology(Loads** ploads, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+
+	/*DataSet*/
+	Loads*    loads    = NULL;
+
+	/*Recover pointer: */
+	loads=*ploads;
+
+	/*Create loads if they do not exist yet*/
+	if(!loads) loads = new Loads();
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp	(revision 11330)
@@ -0,0 +1,51 @@
+/*
+ * CreateNodesHydrology.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesHydrology(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	bool continuous_galerkin=true;
+	int    numberofvertices;
+
+	/*DataSets: */
+	Nodes*    nodes = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	
+	/*Recover pointer: */
+	nodes=*pnodes;
+
+	/*Create nodes if they do not exist yet*/
+	if(!nodes) nodes = new Nodes();
+
+	/*Continuous Galerkin partition of nodes: */
+	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
+
+	/*Create nodes and vertices: */
+	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+	for (i=0;i<numberofvertices;i++){
+
+		if(iomodel->my_vertices[i]){
+			/*Add node to nodes dataset: */
+			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,HydrologyAnalysisEnum));
+
+		}
+	}
+	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+	
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp	(revision 11330)
@@ -0,0 +1,60 @@
+/*
+ * UpdateElementsHydrology:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../modules/modules.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsHydrology(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    numberofelements;
+	
+	/*Fetch data needed: */
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->FetchData(1,MeshElementsEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type); //we need i to index into elements.
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+	iomodel->FetchDataToInput(elements,FrictionPEnum);
+	iomodel->FetchDataToInput(elements,FrictionQEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
+	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+	iomodel->FetchDataToInput(elements,PressureEnum);
+	iomodel->FetchDataToInput(elements,TemperatureEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,WatercolumnEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGeothermalfluxEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,VzEnum);
+
+	elements->InputDuplicate(WatercolumnEnum,WaterColumnOldEnum);
+
+	/*Free data: */
+	iomodel->DeleteData(1,MeshElementsEnum);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp	(revision 11330)
@@ -0,0 +1,30 @@
+/*
+ * CreateConstraintsMelting.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../io/io.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsMelting(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	int count;
+	
+	/*Intermediary*/
+	Constraints* constraints = NULL;
+
+	/*Recover pointer: */
+	constraints=*pconstraints;
+
+	/*Create constraints if they do not exist yet*/
+	if(!constraints) constraints = new Constraints();
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 11330)
@@ -0,0 +1,51 @@
+/*! \file CreateLoadsMelting.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsMelting(Loads** ploads, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	int    dim;
+	int    numberofvertices;
+
+	/*DataSet*/
+	Loads*    loads    = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+
+	/*if 2d: Error*/
+	if (dim==2) _error_("2d meshes not supported yet");
+
+	/*Recover pointer: */
+	loads=*ploads;
+
+	/*Create loads if they do not exist yet*/
+	if(!loads) loads = new Loads();
+
+	//create penalties for nodes: no node can have a temperature over the melting point
+	iomodel->FetchData(2,MeshVertexonbedEnum,MeshElementsEnum);
+	CreateSingleNodeToElementConnectivity(iomodel);
+
+	for (i=0;i<numberofvertices;i++){
+		if((iomodel->my_vertices[i]==1)){
+			if (iomodel->Data(MeshVertexonbedEnum)[i]){ 
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,MeltingAnalysisEnum));
+			}
+		}
+	}
+	iomodel->DeleteData(2,MeshVertexonbedEnum,MeshElementsEnum);
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp	(revision 11330)
@@ -0,0 +1,52 @@
+/*
+ * CreateNodesMelting.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../include/include.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesMelting(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	bool continuous_galerkin=true;
+	int    numberofvertices;
+
+	/*DataSets: */
+	Nodes*    nodes = NULL;
+	
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+
+	/*Recover pointer: */
+	nodes=*pnodes;
+
+	/*Create nodes if they do not exist yet*/
+	if(!nodes) nodes = new Nodes();
+
+	/*Continuous Galerkin partition of nodes: */
+	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
+
+	/*First fetch data: */
+	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+	for (i=0;i<numberofvertices;i++){
+
+		if(iomodel->my_vertices[i]){
+			
+			/*Add node to nodes dataset: */
+			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,MeltingAnalysisEnum));
+
+		}
+	}
+	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp	(revision 11330)
@@ -0,0 +1,63 @@
+/*
+ * UpdateElementsMelting:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../modules/modules.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsMelting(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    dim;
+	int    numberofelements;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if (dim==2)return;
+
+	/*Fetch data needed: */
+	iomodel->FetchData(1,MeshElementsEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type); //we need i to index into elements.
+			counter++;
+		}
+	}
+
+	/*Create inputs: */
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+	iomodel->FetchDataToInput(elements,FrictionPEnum);
+	iomodel->FetchDataToInput(elements,FrictionQEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
+	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsAccumulationRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsAblationRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,PressureEnum);
+	
+	/*Free data: */
+	iomodel->DeleteData(1,MeshElementsEnum);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/ModelProcessorx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 11330)
@@ -0,0 +1,77 @@
+/*!\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 "../../objects/objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../include/include.h"
+#include "../../modules/modules.h"
+
+void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* IOMODEL,const int solution_type,const int nummodels,const int* analysis_type_list){
+
+	int   i,analysis_type,dim,verbose;
+	bool  isthermal,isprognostic,isdiagnostic,isgroundingline;
+	
+	/*output: */
+	Elements    *elements    = NULL;
+	Nodes       *nodes       = NULL;
+	Vertices    *vertices    = NULL;
+	Materials   *materials   = NULL;
+	Constraints *constraints = NULL;
+	Loads       *loads       = NULL;
+	Parameters  *parameters  = NULL;
+
+	
+	/*Initialize IoModel from input file*/
+	IoModel* iomodel = new IoModel(IOMODEL);
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&verbose,VerboseEnum);
+	iomodel->Constant(&isthermal,TransientIsthermalEnum);
+	iomodel->Constant(&isprognostic,TransientIsprognosticEnum);
+	iomodel->Constant(&isdiagnostic,TransientIsdiagnosticEnum);
+	iomodel->Constant(&isgroundingline,TransientIsgroundinglineEnum);
+	
+	SetVerbosityLevel(verbose);
+
+	for(i=0;i<nummodels;i++){
+
+		analysis_type=analysis_type_list[i];
+
+		/*Hack for trasient runs (to be improved)*/
+		if(solution_type==TransientSolutionEnum && analysis_type==ThermalAnalysisEnum && dim==2) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==MeltingAnalysisEnum && dim==2) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==ThermalAnalysisEnum && isthermal==false) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==MeltingAnalysisEnum && isthermal==false) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==PrognosticAnalysisEnum && isprognostic==false && isgroundingline==false) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==DiagnosticHorizAnalysisEnum && isdiagnostic==false) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==DiagnosticVertAnalysisEnum && isdiagnostic==false) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==DiagnosticHutterAnalysisEnum && isdiagnostic==false) continue;
+	
+		_printf_(VerboseMProcessor(),"   creating datasets for analysis %s\n",EnumToStringx(analysis_type));
+		CreateDataSets(&elements,&nodes,&vertices,&materials,&constraints,&loads,&parameters,iomodel,solution_type,analysis_type,nummodels,i);
+	}
+
+	/*Free ressources:*/
+	delete iomodel;
+
+	/*Assign output pointers:*/
+	*pelements=elements;
+	*pnodes=nodes;
+	*pvertices=vertices;
+	*pmaterials=materials;
+	*pconstraints=constraints;
+	*ploads=loads;
+	*pparameters=parameters;
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/ModelProcessorx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 11330)
@@ -0,0 +1,112 @@
+/* \file ModelProcessorx.h
+ * \brief  Header file for model processor
+ */
+
+#ifndef _MODEL_PROCESSORX_H_
+#define _MODEL_PROCESSORX_H_
+
+#define RIFTINFOSIZE 12
+
+class DataSet;
+class IoModel;
+class Parameters;
+#include "../../io/io.h"
+
+void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* iomodel_handle,const int solution_type,const int nummodels,const int* analysis_type_list);
+
+/*Creation of fem datasets: general drivers*/
+void  CreateDataSets(Elements** pelements,Nodes** pnodes,Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads,Parameters** pparameters,IoModel* iomodel,const int solution_type,int analysis_type,const int nummodels,int analysis_counter);
+void  CreateElementsVerticesAndMaterials(Elements** pelements,Vertices** pvertices,Materials** pmaterials, IoModel* iomodel,const int nummodels);
+void  CreateParameters(Parameters** pparameters,IoModel* iomodel,const int solution_type,int analysis_type,int analysis_counter);
+void  CreateParametersControl(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
+void  CreateParametersDakota(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
+void  UpdateElementsAndMaterialsControl(Elements* elements,Materials* materials, IoModel* iomodel);
+
+/*Creation of fem datasets: specialised drivers: */
+
+/*diagnostic horizontal*/
+void	CreateNodesDiagnosticHoriz(Nodes** pnodes,IoModel* iomodel);
+void	CreateConstraintsDiagnosticHoriz(Constraints** pconstraints,IoModel* iomodel);
+void  CreateLoadsDiagnosticHoriz(Loads** ploads, IoModel* iomodel);
+void	UpdateElementsDiagnosticHoriz(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+
+/*diagnostic vertical*/
+void	CreateNodesDiagnosticVert(Nodes** pnodes,IoModel* iomodel);
+void	CreateConstraintsDiagnosticVert(Constraints** pconstraints,IoModel* iomodel);
+void  CreateLoadsDiagnosticVert(Loads** ploads, IoModel* iomodel);
+void	UpdateElementsDiagnosticVert(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+
+/*diagnostic hutter*/
+void	CreateNodesDiagnosticHutter(Nodes** pnodes,IoModel* iomodel);
+void	CreateConstraintsDiagnosticHutter(Constraints** pconstraints,IoModel* iomodel);
+void  CreateLoadsDiagnosticHutter(Loads** ploads, IoModel* iomodel);
+void	UpdateElementsDiagnosticHutter(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+
+/*bed slope*/
+void	CreateNodesBedSlope(Nodes** pnodes,IoModel* iomodel);
+void	CreateConstraintsBedSlope(Constraints** pconstraints,IoModel* iomodel);
+void  CreateLoadsBedSlope(Loads** ploads, IoModel* iomodel);
+void	UpdateElementsBedSlope(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+
+/*surface slope*/
+void	CreateNodesSurfaceSlope(Nodes** pnodes,IoModel* iomodel);
+void	CreateConstraintsSurfaceSlope(Constraints** pconstraints,IoModel* iomodel);
+void  CreateLoadsSurfaceSlope(Loads** ploads, IoModel* iomodel);
+void	UpdateElementsSurfaceSlope(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+
+/*thermal:*/
+void	CreateNodesThermal(Nodes** pnodes,IoModel* iomodel);
+void	CreateConstraintsThermal(Constraints** pconstraints,IoModel* iomodel);
+void  CreateLoadsThermal(Loads** ploads, IoModel* iomodel);
+void	UpdateElementsThermal(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+
+/*enthalpy:*/
+void	CreateNodesEnthalpy(Nodes** pnodes,IoModel* iomodel);
+void	CreateConstraintsEnthalpy(Constraints** pconstraints,IoModel* iomodel);
+void  CreateLoadsEnthalpy(Loads** ploads, IoModel* iomodel);
+void	UpdateElementsEnthalpy(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+
+/*hydrology:*/
+void	CreateNodesHydrology(Nodes** pnodes,IoModel* iomodel);
+void	CreateConstraintsHydrology(Constraints** pconstraints,IoModel* iomodel);
+void  CreateLoadsHydrology(Loads** ploads, IoModel* iomodel);
+void	UpdateElementsHydrology(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+
+/*melting:*/
+void	CreateNodesMelting(Nodes** pnodes,IoModel* iomodel);
+void	CreateConstraintsMelting(Constraints** pconstraints,IoModel* iomodel);
+void  CreateLoadsMelting(Loads** ploads, IoModel* iomodel);
+void	UpdateElementsMelting(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+
+/*prognostic:*/
+void	CreateNodesPrognostic(Nodes** pnodes,IoModel* iomodel);
+void	CreateConstraintsPrognostic(Constraints** pconstraints,IoModel* iomodel);
+void  CreateLoadsPrognostic(Loads** ploads, IoModel* iomodel);
+void	UpdateElementsPrognostic(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+
+/*balancedthickness:*/
+void	CreateNodesBalancethickness(Nodes** pnodes,IoModel* iomodel);
+void	CreateConstraintsBalancethickness(Constraints** pconstraints,IoModel* iomodel);
+void  CreateLoadsBalancethickness(Loads** ploads, IoModel* iomodel);
+void	UpdateElementsBalancethickness(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+
+/*transient: */
+void	UpdateElementsTransient(Elements* elements,Parameters* parameters,IoModel* iomodel,int analysis_counter,int analysis_type);
+
+/*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);
+
+/*Connectivity*/
+void  CreateSingleNodeToElementConnectivity(IoModel* iomodel);
+void  CreateNumberNodeToElementConnectivity(IoModel* iomodel);
+
+/*Diverse: */
+void  SortDataSets(Elements** pelements,Nodes** pnodes,Vertices** pvertices, Loads** ploads, Materials** pmaterials, Constraints** pconstraints, Parameters** pparameters);
+void  UpdateCounters(IoModel* iomodel,Nodes** pnodes,Loads** ploads, Constraints** pconstraints);
+
+
+/*Distribution of dofs: */
+void DistributeNumDofs(DofIndexing* index,int analysis_type,double* vertices_type);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/NodesPartitioning.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 11330)
@@ -0,0 +1,165 @@
+/*!\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 "../../objects/objects.h"
+#include "../../shared/shared.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../io/io.h"
+#include "../../include/include.h"
+#include "../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx/ModelProcessorx.h"
+
+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){
+	
+	/*First thing, this is a new partition for a new analysis_type, therefore, to avoid a leak, erase the nodes partition that might come through pmy_nodes: */
+	xfree((void**)pmy_nodes);
+
+	/*Now, depending on whether we are running galerkin discontinous or continuous elements, carry out a different partition of the nodes: */
+	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){
+
+	/*as many nodes as there are vertices */
+	int    numberofvertices;
+
+	/*output: */
+	bool* my_nodes=NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+
+	my_nodes=(bool*)xmalloc(numberofvertices*sizeof(bool));
+	memcpy(my_nodes,my_vertices,numberofvertices*sizeof(bool));
+
+	/*Assign output pointers:*/
+	*pmy_nodes=my_nodes;
+}
+
+
+void  DiscontinuousGalerkinNodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices, IoModel* iomodel){
+
+	int    numberofelements;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+
+	/*each element has it own nodes (as many as vertices) + additional nodes from neighbouring elements for each edge. 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 edges, which mess up sorting of 
+	 * ids. */
+	
+	int i,j;
+	int    dim;
+
+	/*output: */
+	bool*   my_nodes=NULL;
+
+	int     i1,i2;
+	int     cols;
+	double  e1,e2;
+	int     pos;
+	int     numberofedges;
+	double* edges=NULL;
+	double* elements=NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+
+	/*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 edges require the dofs of the 2 nodes of each elements sharing the edge.
+	 *    if the 2 elements sharing the edge are on 2 different cpus, we must duplicate
+	 *    the two nodes that are not on the cpus so that the edge can access the dofs of
+	 *    all its 4 nodes
+	 */
+
+	/*Allocate*/
+	my_nodes=(bool*)xcalloc(3*numberofelements,sizeof(int));
+
+	/*First: add all the nodes of all the elements belonging to this cpu*/
+	if (dim==2){
+		for (i=0;i<numberofelements;i++){
+			if (my_elements[i]){
+				my_nodes[3*i+0]=1;
+				my_nodes[3*i+1]=1;
+				my_nodes[3*i+2]=1;
+			}
+		}
+	}
+	else{
+		_error_("not implemented yet");
+	}
+
+	/*Second: add all missing nodes*/
+
+	/*Get edges and elements*/
+	iomodel->FetchData(&edges,&numberofedges,&cols,MeshEdgesEnum);
+	iomodel->FetchData(&elements,NULL,NULL,MeshElementsEnum);
+	if (cols!=4) _error_("field edges should have 4 columns");
+
+	/*!All elements have been partitioned above, only create elements for this CPU: */
+	for (i=0;i<numberofedges;i++){
+
+		/*Get left and right elements*/
+		e1=edges[4*i+2]-1; //edges are [node1 node2 elem1 elem2]
+		e2=edges[4*i+3]-1; //edges are [node1 node2 elem1 elem2]
+
+		/* 1) If the element e1 is in the current partition
+		 * 2) and if the edge of the element is shared by another element (internal edge)
+		 * 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[(int)e1] && !isnan(e2) && !my_elements[(int)e2]){ 
+
+			/*1: Get vertices ids*/
+			i1=(int)edges[4*i+0];
+			i2=(int)edges[4*i+1];
+
+			/*2: Get the column where these ids are located in the index*/
+			pos=UNDEF;
+			for(j=0;j<3;j++){
+				if ((int)elements[3*(int)e2+j]==i1) pos=j;
+			}
+
+			/*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[(int)e2*3+0]=1;
+				my_nodes[(int)e2*3+2]=1;
+			}
+			else if(pos==1){
+				my_nodes[(int)e2*3+1]=1;
+				my_nodes[(int)e2*3+0]=1;
+			}
+			else if (pos==2){
+				my_nodes[(int)e2*3+2]=1;
+				my_nodes[(int)e2*3+1]=1;
+			}
+			else{
+				_error_("Problem in edges creation");
+			}
+		}
+	}
+
+	/*Free data: */
+	xfree((void**)&elements);
+	xfree((void**)&edges);
+
+	/*Assign output pointers:*/
+	*pmy_nodes=my_nodes;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp	(revision 11330)
@@ -0,0 +1,33 @@
+#include "../../../Container/Container.h"
+#include "../../../modules/modules.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../io/io.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsPrognostic(Constraints** pconstraints, IoModel* iomodel){
+
+	int stabilization;
+	
+	/*Fetch parameters: */
+	iomodel->Constant(&stabilization,PrognosticStabilizationEnum);
+
+	/*Output*/
+	Constraints *constraints = NULL;
+
+	/*Recover pointer: */
+	constraints=*pconstraints;
+
+	/*Create constraints if they do not exist yet*/
+	if(!constraints) constraints = new Constraints();
+
+	/*Do not add constraints in DG, they are weakly imposed*/
+	if(stabilization!=3){
+		IoModelToConstraintsx(constraints,iomodel,PrognosticSpcthicknessEnum,PrognosticAnalysisEnum);
+	}
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp	(revision 11330)
@@ -0,0 +1,98 @@
+/*! \file CreateLoadsPrognostic.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsPrognostic(Loads** ploads, IoModel* iomodel){
+
+	/*Intermediaries*/
+	int i;
+	int element;
+	int penpair_ids[2];
+	int count=0;
+	int stabilization;
+	int numberofedges;
+	int numvertex_pairing;
+	int numberofelements;
+
+	/*DataSet*/
+	Loads*    loads    = NULL;
+	
+	/*Fetch parameters: */
+	iomodel->Constant(&stabilization,PrognosticStabilizationEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&numberofedges,MeshNumberofedgesEnum);
+
+	/*Recover pointer: */
+	loads=*ploads;
+
+	/*Create loads if they do not exist yet*/
+	if(!loads) loads = new Loads();
+
+	/*Loads only in DG*/
+	if (stabilization==3){
+
+		/*Get edges and elements*/
+		iomodel->FetchData(3,MeshEdgesEnum,MeshElementsEnum,ThicknessEnum);
+
+		/*First load data:*/
+		for (i=0;i<numberofedges;i++){
+
+			/*Get left and right elements*/
+			element=(int)(iomodel->Data(MeshEdgesEnum)[4*i+2])-1; //edges 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,iomodel,PrognosticAnalysisEnum));
+		}
+
+		/*Free data: */
+		iomodel->DeleteData(3,MeshEdgesEnum,MeshElementsEnum,ThicknessEnum);
+	}
+
+	/*Create Penpair for vertex_pairing: */
+	double *vertex_pairing=NULL;
+	double *nodeonbed=NULL;
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,PrognosticVertexPairingEnum);
+	iomodel->FetchData(&nodeonbed,NULL,NULL,MeshVertexonbedEnum);
+
+	for(i=0;i<numvertex_pairing;i++){
+
+		if(iomodel->my_vertices[(int)vertex_pairing[2*i+0]-1]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			_assert_(iomodel->my_vertices[(int)vertex_pairing[2*i+1]-1]);
+
+			/*Skip if one of the two is not on the bed*/
+			if(!nodeonbed[(int)vertex_pairing[2*i+0]-1] || !nodeonbed[(int)vertex_pairing[2*i+1]-1]) continue;
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+(int)vertex_pairing[2*i+0];
+			penpair_ids[1]=iomodel->nodecounter+(int)vertex_pairing[2*i+1];
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(
+							iomodel->loadcounter+count+1,
+							&penpair_ids[0],
+							PrognosticAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	xfree((void**)&vertex_pairing);
+	xfree((void**)&nodeonbed);
+
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp	(revision 11330)
@@ -0,0 +1,94 @@
+/*
+ * CreateNodesPrognostic.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesPrognostic(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int  i,j;
+	int  node_id;
+	int  vertex_id;
+	int  io_index;
+	bool continuous_galerkin=true;
+	int  dim;
+	int    numberofelements;
+	int    numberofvertices;
+	int    stabilization;
+
+	/*DataSets: */
+	Nodes*    nodes = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&stabilization,PrognosticStabilizationEnum);
+
+	/*Recover pointer: */
+	nodes=*pnodes;
+
+	/*Create nodes if they do not exist yet*/
+	if(!nodes) nodes = new Nodes();
+
+	/*Create partition of nodes: */
+	if(stabilization==3) continuous_galerkin=false;
+	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
+
+	/*Check in 3d*/
+	if(stabilization==3 && dim==3) _error_("DG 3d not implemented yet");
+
+	/*First fetch data: */
+	iomodel->FetchData(7,MeshElementsEnum,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+	if(continuous_galerkin){
+
+		/*Build Nodes dataset (Continuous Galerkin)*/
+		for (i=0;i<numberofvertices;i++){
+
+			if(iomodel->my_vertices[i]){
+
+				/*Add node to nodes dataset: */
+				nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,PrognosticAnalysisEnum));
+
+			}
+		}
+	}
+	else{
+
+		/*Build Nodes dataset -> 3 for each element (Discontinuous Galerkin)*/
+		for (i=0;i<numberofelements;i++){
+			for (j=0;j<3;j++){
+
+				if(iomodel->my_nodes[3*i+j]){ 
+
+					//Get index of the vertex on which the current node is located
+					vertex_id=(int)*(iomodel->Data(MeshElementsEnum)+3*i+j); //(Matlab indexing)
+					io_index=vertex_id-1;                      //(C indexing)
+					_assert_(vertex_id>0 && vertex_id<=numberofvertices);
+
+					//Compute Node id
+					node_id=iomodel->nodecounter+3*i+j+1;
+
+					/*Add node to nodes dataset: */
+					nodes->AddObject(new Node(node_id,node_id-1,vertex_id,io_index,iomodel,PrognosticAnalysisEnum));
+
+				}
+			}
+		}
+	}
+
+	/*Clean fetched data: */
+	iomodel->DeleteData(7,MeshElementsEnum,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp	(revision 11330)
@@ -0,0 +1,73 @@
+/*
+ * UpdateElementsPrognostic:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../modules/modules.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsPrognostic(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    dim;
+	int    numberofelements;
+	int    stabilization;
+	bool   dakota_analysis;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&stabilization,PrognosticStabilizationEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->FetchData(1,MeshElementsEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type); //we need i to index into elements.
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,BathymetryEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsAccumulationRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsAblationRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateCorrectionEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+
+	if(stabilization==3){
+		iomodel->FetchDataToInput(elements,PrognosticSpcthicknessEnum); //for DG, we need the spc in the element
+	}
+
+	if(dakota_analysis){
+		elements->InputDuplicate(BedEnum,QmuBedEnum);
+		elements->InputDuplicate(ThicknessEnum,QmuThicknessEnum);
+		elements->InputDuplicate(SurfaceEnum,QmuSurfaceEnum);
+	}
+
+	if (dim==3){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+		iomodel->FetchDataToInput(elements,PressureEnum);
+		iomodel->FetchDataToInput(elements,TemperatureEnum);
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(1,MeshElementsEnum);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SortDataSets.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SortDataSets.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SortDataSets.cpp	(revision 11330)
@@ -0,0 +1,48 @@
+/*!\file: SortDataSets.cpp
+ * \brief sort datasets created in CreateDataSets
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../objects/objects.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "./ModelProcessorx.h"
+
+
+void SortDataSets(Elements** pelements,Nodes** pnodes,Vertices** pvertices, Loads** ploads, Materials** pmaterials, Constraints** pconstraints, Parameters** pparameters){
+
+	Elements* elements=NULL;
+	Nodes* nodes=NULL;
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Constraints* constraints=NULL;
+	Parameters* parameters=NULL;
+
+	/*Recover pointers: */
+	elements=*pelements;
+	nodes=*pnodes;
+	vertices=*pvertices;
+	loads=*ploads;
+	materials=*pmaterials;
+	constraints=*pconstraints;
+	parameters=*pparameters;
+
+	/*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: */
+
+	if(elements)elements->Presort();
+	if(nodes)nodes->Presort();
+	if(vertices)vertices->Presort();
+	if(loads)loads->Presort();
+	if(materials)materials->Presort();
+	if(constraints)constraints->Presort();
+	if(parameters)parameters->Presort();
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp	(revision 11330)
@@ -0,0 +1,26 @@
+/*
+ * CreateConstraintsSurfaceSlope.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../io/io.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsSurfaceSlope(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Output*/
+	Constraints* constraints = NULL;
+	
+	/*Recover pointer: */
+	constraints=*pconstraints;
+
+	/*Create constraints if they do not exist yet*/
+	if(!constraints) constraints = new Constraints();
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp	(revision 11330)
@@ -0,0 +1,26 @@
+/*! \file CreateLoadsSurfaceSlope.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../io/io.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsSurfaceSlope(Loads** ploads, IoModel* iomodel){
+
+	/*DataSet*/
+	Loads*    loads    = NULL;
+
+	/*Recover pointer: */
+	loads=*ploads;
+
+	/*Create loads if they do not exist yet*/
+	if(!loads) loads = new Loads();
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp	(revision 11330)
@@ -0,0 +1,55 @@
+/*
+ * CreateNodesSurfaceSlope.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../io/io.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesSurfaceSlope(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	bool continuous_galerkin=true;
+	int    numberofvertices;
+
+	/*DataSets: */
+	Nodes*    nodes = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+
+	/*Recover pointer: */
+	nodes=*pnodes;
+
+	/*Create nodes if they do not exist yet*/
+	if(!nodes) nodes = new Nodes();
+	
+	/*Continuous Galerkin partition of nodes: */
+	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
+	
+	/*First fetch data: */
+	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+
+	for (i=0;i<numberofvertices;i++){
+
+		if(iomodel->my_vertices[i]){
+			
+			/*Add node to nodes dataset: */
+			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,SurfaceSlopeAnalysisEnum));
+
+		}
+	}
+
+	/*Clean fetched data: */
+	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+	
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp	(revision 11330)
@@ -0,0 +1,47 @@
+/*
+ * UpdateElementsSurfaceSlope:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../modules/modules.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsSurfaceSlope(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    dim;
+	int    numberofelements;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->FetchData(1,MeshElementsEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type); //we need i to index into elements.
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
+	
+	if (dim==3){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	}
+	
+	/*Free data: */
+	iomodel->DeleteData(1,MeshElementsEnum);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp	(revision 11330)
@@ -0,0 +1,40 @@
+/*
+ * CreateConstraintsThermal.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../modules/modules.h"
+#include "../../../io/io.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsThermal(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	int count;
+	int    dim;
+	
+	/*Output*/
+	Constraints* constraints = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+
+	/*Recover pointer: */
+	constraints=*pconstraints;
+
+	/*Create constraints if they do not exist yet*/
+	if(!constraints) constraints = new Constraints();
+
+	/*Only 3d mesh supported*/
+	if (dim==3){
+		IoModelToConstraintsx(constraints,iomodel,ThermalSpctemperatureEnum,ThermalAnalysisEnum);
+	}
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 11330)
@@ -0,0 +1,54 @@
+/*! \file CreateLoadsThermal.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsThermal(Loads** ploads, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	int    dim;
+	int    numberofvertices;
+
+	/*DataSet*/
+	Loads*    loads    = NULL;
+	Pengrid*    pengrid  = NULL;
+
+	/*Recover pointer: */
+	loads=*ploads;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+
+	/*Create loads if they do not exist yet*/
+	if(!loads) loads = new Loads();
+
+	/*return if 2d mesh*/
+	if (dim==2) _error_("2d meshes not supported yet");
+
+	//create penalties for nodes: no node can have a temperature over the melting point
+	iomodel->FetchData(2,ThermalSpctemperatureEnum,MeshElementsEnum);
+	CreateSingleNodeToElementConnectivity(iomodel);
+
+	for (i=0;i<numberofvertices;i++){
+	
+		/*keep only this partition's nodes:*/
+		if((iomodel->my_vertices[i]==1)){
+			if (isnan(iomodel->Data(ThermalSpctemperatureEnum)[i])){ //No penalty applied on spc nodes!
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,ThermalAnalysisEnum));
+			}
+		}
+	}
+	iomodel->DeleteData(2,ThermalSpctemperatureEnum,MeshElementsEnum);
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp	(revision 11330)
@@ -0,0 +1,54 @@
+/*
+ * CreateNodesThermal.c:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesThermal(Nodes** pnodes, IoModel* iomodel){
+
+	/*Intermediary*/
+	int i;
+	bool continuous_galerkin=true;
+	int    numberofvertices;
+
+	/*DataSets: */
+	Nodes*    nodes = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+
+	/*Recover pointer: */
+	nodes=*pnodes;
+
+	/*Create nodes if they do not exist yet*/
+	if(!nodes) nodes = new Nodes();
+
+	/*Continuous Galerkin partition of nodes: */
+	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
+
+	/*Create nodes and vertices: */
+	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+
+	for (i=0;i<numberofvertices;i++){
+
+		if(iomodel->my_vertices[i]){
+			/*Add node to nodes dataset: */
+			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,ThermalAnalysisEnum));
+
+		}
+	}
+
+	/*Clean fetched data: */
+	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
+	
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp	(revision 11330)
@@ -0,0 +1,69 @@
+/*
+ * UpdateElementsThermal:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../modules/modules.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsThermal(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    dim;
+	int    numberofelements;
+	bool   dakota_analysis;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if (dim==2)return;
+
+	/*Fetch data needed: */
+	iomodel->FetchData(1,MeshElementsEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type); //we need i to index into elements.
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+	iomodel->FetchDataToInput(elements,FrictionPEnum);
+	iomodel->FetchDataToInput(elements,FrictionQEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
+	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
+	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);
+	
+	if(dakota_analysis){
+		elements->InputDuplicate(TemperatureEnum,QmuTemperatureEnum);
+		elements->InputDuplicate(BasalforcingsMeltingRateEnum,QmuMeltingEnum);
+	}
+	/*Free data: */
+	iomodel->DeleteData(1,MeshElementsEnum);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 11330)
@@ -0,0 +1,20 @@
+/*
+ * UpdateElementsTransient:
+ */
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../modules/modules.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsTransient(Elements* elements, Parameters* parameters,IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	/*nothing for now: */
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/UpdateCounters.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/UpdateCounters.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ModelProcessorx/UpdateCounters.cpp	(revision 11330)
@@ -0,0 +1,38 @@
+/*!\file: UpdateCounter.cpp
+ * \brief update counters after adding objects to a dataset.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../objects/objects.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "./ModelProcessorx.h"
+
+void    UpdateCounters(IoModel* iomodel,Nodes** pnodes,Loads** ploads, Constraints** pconstraints){
+
+	Nodes* nodes=NULL;
+	Loads* loads=NULL;
+	Constraints* constraints=NULL;
+
+	/*recover pointers: */
+	nodes=*pnodes;
+	loads=*ploads;
+	constraints=*pconstraints;
+
+
+	if(nodes) iomodel->nodecounter=nodes->NumberOfNodes();
+	else iomodel->nodecounter=0;
+
+	if(loads)iomodel->loadcounter=loads->NumberOfLoads();
+	else iomodel->loadcounter=0;
+	
+	if(constraints)iomodel->constraintcounter=constraints->NumberOfConstraints();
+	else iomodel->constraintcounter=0;
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 11330)
@@ -0,0 +1,46 @@
+/*!\file NodalValuex
+ * \brief: compute value at certain node
+ */
+
+#include "./NodalValuex.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void NodalValuex( double* pnodalvalue, int natureofdataenum,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units){
+
+	extern int my_rank;
+	int i;
+	int index;
+	Element* element=NULL;
+	double value;
+	int found;
+	int sumfound;
+	int 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(i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		found=element->NodalValue(&value,index,natureofdataenum,process_units);
+		if (found){
+			cpu_found=my_rank;
+			break;
+		}
+	}
+
+	/*Broadcast whether we found the element: */
+	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
+	if(!sumfound)_error_("%s%i%s%s","could not find element with vertex with id",index," to compute nodal value ",EnumToStringx(natureofdataenum));
+
+	/*Broadcast and plug into response: */
+	MPI_Allreduce ( &cpu_found,&cpu_found,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
+	MPI_Bcast(&value,1,MPI_DOUBLE,cpu_found,MPI_COMM_WORLD); 
+
+	*pnodalvalue=value;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  NodalValuex.h
+ * \brief header file for NodalValuex
+ */ 
+
+#ifndef _NODALVALUEX_H
+#define _NODALVALUEX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void NodalValuex( double* pnodalvalue, int natureofdataenum,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif  /* _NODALVALUEX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 11330)
@@ -0,0 +1,79 @@
+/*!\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 "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void	NodeConnectivityx( double** pconnectivity, int* pwidth, double* elements, int nel, int nods){
+
+	int i,j,n;
+	const int maxels=25;
+	const int width=maxels+1;
+
+	/*intermediary: */
+	int     node;
+	int     index;
+	int     num_elements;
+	int     already_plugged=0;
+	double  element;
+
+	/*output: */
+	double* connectivity=NULL;
+
+
+
+	/*Allocate connectivity: */
+	connectivity=(double*)xcalloc(nods*width,sizeof(double));
+
+	/*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<nel;n++){
+
+		element=(double)(n+1); //matlab indexing
+
+		for(i=0;i<3;i++){
+		
+			node=(int)*(elements+n*3+i); //already matlab indexed, elements comes directly from the workspace.
+			index=node-1;
+
+			num_elements=(int)*(connectivity+width*index+maxels); //retrieve number of elements already  plugged into the connectivity of this node.
+			
+			already_plugged=0;
+			for(j=0;j<num_elements;j++){
+				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)=(double)(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_("%s%g%s"," max connectivity width reached (",*(connectivity+width*i+maxels),")! increase width of connectivity table");
+	}
+
+	/*Assign output pointers: */
+	*pconnectivity=connectivity;
+	*pwidth=width;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/NodeConnectivityx/NodeConnectivityx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/NodeConnectivityx/NodeConnectivityx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/NodeConnectivityx/NodeConnectivityx.h	(revision 11330)
@@ -0,0 +1,12 @@
+/*!\file:  NodeConnectivityx.h
+ * \brief header file for node connectivity computation
+ */ 
+
+#ifndef _NODECONNECTIVITYX_H
+#define _NODECONNECTIVITYX_H
+
+/* local prototypes: */
+void	NodeConnectivityx( double** pconnectivity, int* pwidth,double* elements, int nel, int nods);
+
+#endif  /* _NODECONNECTIVITYX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/NodesDofx/NodesDofx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/NodesDofx/NodesDofx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/NodesDofx/NodesDofx.cpp	(revision 11330)
@@ -0,0 +1,33 @@
+/*!\file NodesDofx
+ * \brief: establish degrees of freedom for all nodes
+ */
+
+#include "./NodesDofx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void NodesDofx(Nodes* nodes, Parameters* parameters,int configuration_type){
+
+	int noerr=1;
+	int found=0;
+	int i;
+	
+	/*Do we have any nodes for this analysis type? :*/
+	if(nodes->NumberOfNodes(configuration_type)){ 
+
+		/*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/trunk-jpl-damage/src/c/modules/NodesDofx/NodesDofx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/NodesDofx/NodesDofx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/NodesDofx/NodesDofx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  NodesDofx.h
+ * \brief header file for degree of freedoms distribution routines.
+ */ 
+
+#ifndef _NODESDOFX_H
+#define _NODESDOFX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void NodesDofx(Nodes* nodes, Parameters* parameters,int analysis_type);
+
+#endif  /* _NODESDOFX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/Orthx/Orthx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Orthx/Orthx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Orthx/Orthx.cpp	(revision 11330)
@@ -0,0 +1,31 @@
+/*!\file Orthx
+ * \brief orthogonalize searching directions for inverse control methods
+ */
+
+#include "./Orthx.h"
+
+void	Orthx( Vec* pnewgradj, Vec gradj, Vec oldgradj){
+	
+	/*output: */
+	Vec newgradj=NULL;
+
+	/*intermediary:*/
+	double norm_new,norm_old,dot_product;;
+
+	/*Initialize output*/
+	VecDuplicate(gradj,&newgradj);
+	VecCopy(gradj,newgradj);
+
+	/*rough orthagonalization
+	gradient=gradient-(gradient'*oldgradient)*oldgradient /norm(oldgradient)^2; */
+	if(oldgradj){
+		VecNorm(oldgradj,NORM_2,&norm_old);
+		_assert_(norm_old!=0); 
+		VecDot(newgradj,oldgradj,&dot_product);
+		_assert_(dot_product!=NAN); 
+		VecAXPY(newgradj, -dot_product/pow(norm_old,2), oldgradj);
+	}
+
+	/*Assign correct pointer*/
+	*pnewgradj=newgradj;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Orthx/Orthx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Orthx/Orthx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Orthx/Orthx.h	(revision 11330)
@@ -0,0 +1,16 @@
+/*!\file:  Orthx.h
+ * \brief orthogonalize searching directions for inverse control methods
+ */ 
+
+#ifndef _ORTHX_H
+#define _ORTHX_H
+
+#include "../../objects/objects.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+
+/* local prototypes: */
+void	Orthx( Vec* pnewgradj, Vec gradj, Vec oldgradj);
+
+#endif  /* _ORTHX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/OutputResultsx/OutputResultsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 11330)
@@ -0,0 +1,120 @@
+/*!\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 "../../Container/Container.h"
+#include "../../io/io.h"
+#include "../../objects/objects.h"
+		
+#ifdef _SERIAL_
+void OutputResultsx(mxArray** pdataref, Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Results** presults){
+#else 
+void OutputResultsx(                    Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Results** presults){
+#endif
+
+	extern 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;
+	Results    *results                 = NULL;
+	bool        dakota_analysis         = false;
+	
+	#ifdef _SERIAL_
+	const char **fnames      = NULL;
+	mwSize       onebyone[2] = {0,0};
+	mwSize       ndim        = 2;
+	int          nfields=0;
+	#endif
+
+	/*recover results dataset: */
+	results=*presults;
+
+	/*retrieve parameters: */
+	parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+
+	if(dakota_analysis){
+		//no need to output anything, Dakota analysis has different outputs
+		#ifdef _SERIAL_
+		*pdataref=mxCreateStructArray( ndim,onebyone,nfields,fnames);
+		#endif
+		return; 
+	}
+
+	/*We have results inside our elements, loads, etc ... Get them out of there, into the results dataset: */
+	elements->ProcessResultsUnits();
+	elements->ToResults(results,parameters);
+	elements->DeleteResults();
+
+	/*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: */
+	#ifdef _PARALLEL_
+	if(my_rank==0){
+		parameters->FindParam(&solutiontype,SolutionTypeEnum);
+		EnumToStringx(&solutiontypestring,solutiontype);
+		results->AddObject(new StringExternalResult(results->Size()+1,SolutionTypeEnum,solutiontypestring,1,0));
+		xfree((void**)&solutiontypestring);
+	}
+
+	/*Now, open file for writing, if not already done: */
+	if(!parameters->Exist(OutputFilePointerEnum)){
+		
+		/*We don't have a file pointer. Retrieve the output file name and open it for writing:*/
+		parameters->FindParam(&outputfilename,OutputfilenameEnum);
+
+		/*What strategy? : */
+		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=pfopen(outputfilename ,"wb");
+		}
+		else{
+			/*We are opening different  files for output on all cpus. Append the  rank to the filename, and open: */
+			parameters->FindParam(&fid,OutputFilePointerEnum);
+			sprintf(cpu_outputfilename,"%s.%i",outputfilename,my_rank);
+			fid=pfopen(cpu_outputfilename ,"wb");
+		}
+		xfree((void**)&outputfilename);
+		
+		/*Add file pointer in parameters for further calls to OutputResultsx: */
+		parameters->SetParam(fid,OutputFilePointerEnum);
+	}
+	#endif
+
+	/*Write results to disk (in parallel), or to memory (in serial mode): */
+	#ifdef _SERIAL_
+		results->Write(pdataref);
+	#else
+		results->Write(parameters);
+	#endif
+
+	/*Delete and reinitialize results, in parallel: */
+	#ifdef _PARALLEL_
+		delete results; results=new Results();
+
+		/*Close output file? :*/
+		/*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);
+		}
+		*/
+	#endif
+
+	/*Assign output pointers:*/
+	*presults=results;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/OutputResultsx/OutputResultsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/OutputResultsx/OutputResultsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/OutputResultsx/OutputResultsx.h	(revision 11330)
@@ -0,0 +1,24 @@
+/*!\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 "../../Container/Container.h"
+
+#ifdef _SERIAL_
+#include <mex.h>
+void OutputResultsx(mxArray** pdataref, Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads,  Materials* materials, Parameters* parameters, Results** presults);
+#else
+void OutputResultsx(Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads,  Materials* materials, Parameters* parameters, Results** presults);
+#endif
+
+#endif  /* _OUTPUTRESULTS_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/OutputRiftsx/OutputRiftsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/OutputRiftsx/OutputRiftsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/OutputRiftsx/OutputRiftsx.cpp	(revision 11330)
@@ -0,0 +1,30 @@
+/*!\file OutputRiftsx
+ * \brief: output results from diagnostic solution, for rifts. Notably: fraction of 
+ * melange, and penetration.
+ */
+
+#include "./OutputRiftsx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void OutputRiftsx( Vec* priftproperties, Loads* loads, int numrifts){
+
+	/*output: */
+	Vec riftproperties=NULL;
+
+	/*Allocate grad_g: */
+	riftproperties=NewVec(numrifts);
+
+	/*Compute rift properties : */
+	loads->OutputRifts(riftproperties);
+
+	/*Assemble vector: */
+	VecAssemblyBegin(riftproperties);
+	VecAssemblyEnd(riftproperties);
+
+	/*Assign output pointers: */
+	*priftproperties=riftproperties;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/OutputRiftsx/OutputRiftsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/OutputRiftsx/OutputRiftsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/OutputRiftsx/OutputRiftsx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  OutputRiftsx.h
+ * \brief header file for rift results output.
+ */ 
+
+#ifndef _OUTPUTRIFTSX_H
+#define _OUTPUTRIFTSX_H
+
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void OutputRiftsx( Vec* priftproperties, Loads* loads, int numrifts);
+
+#endif  /* _OUTPUTRIFTSX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp	(revision 11330)
@@ -0,0 +1,122 @@
+/*!\file ParsePetscOptionsx
+ * * \brief: parse options present in a petsc file, and create petsc options 
+ * objects accordingly. This will be used to drive the behaviour of Petsc 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 "./ParsePetscOptionsx.h"
+#include "../../io/io.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void ParsePetscOptionsx(Parameters* parameters,FILE* fid){
+
+	char line [1000];
+	extern int my_rank;
+	int i;
+
+	/*intermediary: */
+	double* analyses=NULL;
+	char** strings=NULL;
+	int numanalyses;
+	char* string=NULL;
+	char* newstring=NULL;
+	char* catstring=NULL;
+	int   stringlength;
+
+	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=(double*)xmalloc(numanalyses*sizeof(double));
+		strings=(char**)xmalloc(numanalyses*sizeof(char*));
+		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=(char*)xmalloc((strlen(line)+1)*sizeof(char)); 
+					memcpy(string,line,(strlen(line)+1)*sizeof(char));
+
+					strings[numanalyses-1]=string;
+				}
+				else{
+					string=strings[numanalyses-1];
+					newstring=(char*)xmalloc((strlen(line)+1)*sizeof(char));
+					memcpy(newstring,line,(strlen(line)+1)*sizeof(char));
+
+					/*concatenate:*/
+					catstring=(char*)xmalloc((strlen(string)+1+strlen(newstring)+1+1)*sizeof(char)); //fit in a space " "
+					memcpy(catstring,string,(strlen(string)+1)*sizeof(char));
+
+					strcat(catstring," ");
+					strcat(catstring,newstring);
+					strings[numanalyses-1]=catstring;
+					xfree((void**)&newstring);
+					xfree((void**)&string);
+				}
+			}
+		}
+	}
+
+	#ifdef _PARALLEL_
+	/*Ok, broadcast to other cpus: */
+	MPI_Bcast(&numanalyses,1,MPI_INT,0,MPI_COMM_WORLD);
+	if(my_rank!=0){
+		analyses=(double*)xmalloc(numanalyses*sizeof(double));
+		strings=(char**)xmalloc(numanalyses*sizeof(char*));
+	}
+	MPI_Bcast(analyses,numanalyses,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	for(i=0;i<numanalyses;i++){
+		char* string=strings[i];
+		if(my_rank==0)stringlength=(strlen(string)+1)*sizeof(char);
+		MPI_Bcast(&stringlength,1,MPI_INT,0,MPI_COMM_WORLD);
+		if(my_rank!=0)string=(char*)xmalloc(stringlength);
+		MPI_Bcast(string,stringlength,MPI_CHAR,0,MPI_COMM_WORLD);
+		if(my_rank!=0)strings[i]=string;
+	}
+	#endif
+
+	/*Ok, out of strings and analyses and numanalyses, create parameters, and plug them into parameters container: */
+	parameters->AddObject(new StringArrayParam(PetscOptionsStringsEnum,strings,numanalyses));
+	parameters->AddObject(new DoubleVecParam(PetscOptionsAnalysesEnum,analyses,numanalyses));
+
+	/*Clean up and return*/
+	for(i=0;i<numanalyses;i++) xfree((void**)&strings[i]);
+	xfree((void**)&strings);
+	xfree((void**)&analyses);
+	return;
+}
+
Index: /issm/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  ParsePetscOptionsx.h
+ * \brief header file for parsing petsc options file
+ */ 
+
+#ifndef _PARSEPETSCOPTIONSX_H
+#define _PARSEPETSCOPTIONSX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void ParsePetscOptionsx(Parameters* parameters, FILE* petscoptionsfid);
+
+#endif  /* _PARSEPETSCOPTIONSX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp	(revision 11330)
@@ -0,0 +1,38 @@
+/*! \file  PointCloudFindNeighborsx.c
+ */
+
+#include "./PointCloudFindNeighborsx.h"
+
+int PointCloudFindNeighborsx( Vec* pflags,double* x, double* y, int nods, double mindistance,double multithread){
+
+	/*output: */
+	Vec flags=NULL;
+	flags=NewVec(nods);
+
+	/*threading: */
+	PointCloudFindNeighborsThreadStruct gate;
+	int num=1;
+
+	#ifdef _MULTITHREADING_
+	num=_NUMTHREADS_;
+	#endif
+
+	if(!multithread)num=1;
+
+	/*initialize thread parameters: */
+	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: */
+	VecAssemblyBegin(flags);
+	VecAssemblyEnd(flags);
+
+	/*Assign output pointers: */
+	*pflags=flags;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h	(revision 11330)
@@ -0,0 +1,31 @@
+/*
+	PointCloudFindNeighborsx.h
+*/
+
+
+#ifndef _POINTCLOUDFLAGNEIGHBORSX_H
+#define _POINTCLOUDFLAGNEIGHBORSX_H
+
+#include "../../shared/shared.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+int PointCloudFindNeighborsx( Vec* pflags,double* x, double* y, int nods, double mindistance,double multithread);
+
+/*threading: */
+typedef struct{
+
+	double* x;
+	double* y;
+	int nods;
+	double mindistance;
+	Vec flags;
+
+
+} PointCloudFindNeighborsThreadStruct;
+
+void* PointCloudFindNeighborsxt(void* vPointCloudFindNeighborsThreadStruct);
+
+
+#endif /* _POINTCLOUDFLAGNEIGHBORSX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 11330)
@@ -0,0 +1,76 @@
+/*!\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;
+	Vec     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=(bool*)xcalloc(nods,sizeof(bool));
+
+	/*partition loop across threads: */
+	PartitionRange(&i0,&i1,nods,num_threads,my_thread);
+
+	/*Loop over the nodes*/
+	if (my_thread==0) printf("      loop progress:   %5.2lf %%",0.0);
+
+	for (i=i0;i<i1;i++){
+
+		/*display current iteration*/
+		if (my_thread==0 && fmod((double)i,(double)100)==0) printf("\b\b\b\b\b\b\b%5.2lf %%",(double)i/nods*100*num_threads);
+
+		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]) VecSetValue(flags,i,1,INSERT_VALUES);
+				if(!already[j]) VecSetValue(flags,j,2,INSERT_VALUES);
+				already[i]=true;
+				already[j]=true;
+				break;
+			}
+		}
+	}
+	if (my_thread==0) printf("\b\b\b\b\b\b\b%5.2lf %%\n",100.0);
+
+	/*Free ressources:*/
+	xfree((void**)&already);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp	(revision 11330)
@@ -0,0 +1,38 @@
+/*!\file PropagateFlagsFromConnectivityx
+ */
+
+#include "./PropagateFlagsFromConnectivityx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.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/trunk-jpl-damage/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  PropagateFlagsFromConnectivityx.h
+ */ 
+
+#ifndef _PROPAGATEFLAGSFROMCONNECTIVITYX_H
+#define _PROPAGATEFLAGSFROMCONNECTIVITYX_H
+
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void PropagateFlagsFromConnectivityx( double* pool, double* connectivity,int index, double* flags);
+
+#endif  /* _PROPAGATEFLAGSFROMCONNECTIVITYX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/Reduceloadx/Reduceloadx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 11330)
@@ -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 "../../io/io.h"
+
+void	Reduceloadx( Vec pf, Mat Kfs, Vec y_s,bool flag_ys0){
+
+	/*intermediary*/
+	Vec         y_s0   = NULL;
+	Vec         Kfsy_s = NULL;
+	int         Kfsm,Kfsn;
+	int         global_m,global_n;
+	PetscScalar a;
+	bool        fromlocalsize = true;
+	int         verbose;
+
+	_printf_(VerboseModule(),"   Dirichlet lifting applied to load vector\n");
+
+	MatGetSize(Kfs,&global_m,&global_n);
+	if(pf && global_m*global_n){
+
+		/*Some checks in debugging mode*/
+		_assert_(y_s);
+
+		/*pf = pf - Kfs * y_s;*/
+		MatGetLocalSize(Kfs,&Kfsm,&Kfsn);
+		Kfsy_s=NewVec(Kfsm,fromlocalsize);
+		if (flag_ys0){
+
+			/*Create y_s0, full of 0: */
+			VecDuplicate(y_s,&y_s0);
+			VecSet(y_s0,0.0);
+			VecAssemblyBegin(y_s0);
+			VecAssemblyEnd(y_s0);
+
+			MatMultPatch(Kfs,y_s0,Kfsy_s);
+		}
+		else{
+			MatMultPatch(Kfs,y_s,Kfsy_s);
+		}
+
+		a=-1;
+		VecAXPY(pf,a,Kfsy_s);  
+	}
+
+
+	/*Free ressources and return*/
+	VecFree(&y_s0);
+	VecFree(&Kfsy_s);
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Reduceloadx/Reduceloadx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Reduceloadx/Reduceloadx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Reduceloadx/Reduceloadx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  Reduceloadx.h
+ * \brief reduce loads (wring out boundary conditions)
+ */ 
+
+#ifndef _REDUCELOADX_H
+#define _REDUCELOADX_H
+
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void	Reduceloadx( Vec pf, Mat Kfs, Vec ys,bool flag_ys0=false);
+
+#endif  /* _REDUCELOADX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 11330)
@@ -0,0 +1,58 @@
+/*!\file Reducevectorgtofx
+ * \brief reduce petsc vector from g set to s set (free dofs), using the nodeset partitioning 
+ * vectors.
+ */
+
+#include "./Reducevectorgtofx.h"
+ 
+void Reducevectorgtofx(Vec* puf, Vec ug, Nodes* nodes,Parameters* parameters){
+
+	/*output: */
+	Vec uf=NULL;
+
+	/*variables: */
+	int i;
+	int configuration_type;
+	int fsize;
+	double* ug_serial=NULL;
+
+	/*first figure out fsize: */
+	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	fsize=nodes->NumberOfDofs(configuration_type,FsetEnum);
+
+	if(fsize==0){
+		uf=NULL;
+	}
+	else{
+		/*allocate: */
+		uf=NewVec(fsize);
+
+		if(nodes->NumberOfNodes(configuration_type)){ 
+
+			/*serialize ug, so nodes can index into it: */
+			VecToMPISerial(&ug_serial,ug);
+
+			/*Go through all nodes, and ask them to retrieve values from ug, and plug them into uf: */
+			for(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: */
+		VecAssemblyBegin(uf);
+		VecAssemblyEnd(uf);
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&ug_serial);
+
+	/*Assign output pointers:*/
+	*puf=uf;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\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 "../../objects/objects.h"
+
+/* local prototypes: */
+void Reducevectorgtofx(Vec* puf, Vec ug, Nodes* nodes,Parameters* parameters);
+
+#endif  /* _REDUCEVECTORGTOFX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.cpp	(revision 11330)
@@ -0,0 +1,58 @@
+/*!\file Reducevectorgtosx
+ * \brief reduce petsc vector from g set to s set (single point constraints), using the nodeset partitioning 
+ * vectors.
+ */
+
+#include "./Reducevectorgtosx.h"
+
+void Reducevectorgtosx(Vec* pys, Vec yg, Nodes* nodes,Parameters* parameters){
+
+	/*output: */
+	Vec ys=NULL;
+
+	/*variables: */
+	int i;
+	int configuration_type;
+	int ssize;
+	double* yg_serial=NULL;
+
+	/*first figure out ssize: */
+	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	ssize=nodes->NumberOfDofs(configuration_type,SsetEnum);
+
+	if(ssize==0){
+		ys=NULL;
+	}
+	else{
+		/*allocate: */
+		ys=NewVec(ssize);
+
+		if(nodes->NumberOfNodes(configuration_type)){ 
+
+			/*serialize yg, so nodes can index into it: */
+			VecToMPISerial(&yg_serial,yg);
+
+			/*Go throygh all nodes, and ask them to retrieve values from yg, and plyg them into ys: */
+			for(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(ys,yg_serial,SsetEnum);
+				}
+			}
+		}
+		/*Assemble vector: */
+		VecAssemblyBegin(ys);
+		VecAssemblyEnd(ys);
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&yg_serial);
+
+	/*Assign output pointers:*/
+	*pys=ys;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  Reducevectorgtosx.h
+ * \brief reduce petsc vector from g set to s set (single point constraints), using the nodeset partitioning 
+ * vectors.
+ */ 
+
+#ifndef _REDUCEVECTORGTOSX_H
+#define _REDUCEVECTORGTOSX_H
+
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void Reducevectorgtosx(Vec* pys, Vec yg, Nodes* nodes,Parameters* parameters);
+
+#endif  /* _REDUCEVECTORGTOSX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/RequestedOutputsx/RequestedOutputsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/RequestedOutputsx/RequestedOutputsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/RequestedOutputsx/RequestedOutputsx.cpp	(revision 11330)
@@ -0,0 +1,39 @@
+/*!\file RequestedOutputsx
+ * \brief: compute outputs that were requested specifically for this solution, such as BasalStress, StrainHeating, etc ...
+ */
+
+#include "../../modules/modules.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void RequestedOutputsx(Results* results,Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters, int* requested_outputs, int numoutputs, int step, double time){
+
+	int  i,j;
+	int  output_enum;
+	double output_value;
+	Element* element=NULL;
+
+	/*retrieve parameters: */
+	if(numoutputs){
+		for(i=0;i<numoutputs;i++){
+			output_enum=requested_outputs[i];
+
+			switch(output_enum){
+
+				case IceVolumeEnum:
+					Responsex(&output_value,elements,nodes,vertices,loads,materials,parameters,"IceVolume",false,0);
+					results->AddObject(new DoubleExternalResult(results->Size()+1,IceVolumeEnum,output_value,step,time));
+					break;
+				default:
+					/*create this output in the element inputs, and then transfer to results:*/
+					for(j=0;j<elements->Size();j++){
+						element=(Element*)elements->GetObjectByOffset(j);
+						element->RequestedOutput(output_enum,step,time);
+					}
+					break;
+			}
+		}
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/modules/RequestedOutputsx/RequestedOutputsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/RequestedOutputsx/RequestedOutputsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/RequestedOutputsx/RequestedOutputsx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  RequestedOutputsx.h
+ * \brief header file for  requesting outputs
+ */ 
+
+#ifndef _REQUESTED_OUTPUTSX_H_
+#define _REQUESTED_OUTPUTSX_H_
+
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void RequestedOutputsx(Results* results,Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters, int* requested_outputs, int numoutputs, int step=1, double time=0);
+
+#endif  /* _INPUTTORESULTX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 11330)
@@ -0,0 +1,39 @@
+/*!\file ResetConstraintsx
+ * \brief: reset thermal penalties
+ */
+
+#include "./ResetConstraintsx.h"
+#include "../modules.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void ResetConstraintsx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters){
+
+	int i;
+
+	extern int num_procs;
+	extern int my_rank;
+
+	/*output: */
+	int analysis_type;
+
+	/*Display message*/
+	_printf_(VerboseModule(),"   Resetting penalties\n");
+
+	/*recover parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Do we have penalties linked to rifts? In this case, run our special rifts penalty 
+	 * management routine, otherwise, skip : */
+	if (RiftIsPresent(loads,analysis_type)){
+		_error_("rift constraints reset not supported yet!");
+	}
+	else if(ThermalIsPresent(loads,analysis_type)){
+		ThermalConstraintsReset(loads,analysis_type);
+	}
+	else{ /*Do nothing, no constraints management!:*/}
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 11330)
@@ -0,0 +1,16 @@
+/*!\file:  ResetConstraintsx.h
+ * \brief header file for penalty constraints module
+ */ 
+
+#ifndef _RESETCONSTRAINTSX_H
+#define _RESETCONSTRAINTSX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void  ThermalConstraintsReset(Loads* loads, int configuration_type);
+void ResetConstraintsx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters); 
+
+#endif  /* _RESETCONSTRAINTSX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ThermalConstraintsReset.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ThermalConstraintsReset.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ThermalConstraintsReset.cpp	(revision 11330)
@@ -0,0 +1,29 @@
+/*!\file:  ThermalConstraintsState.cpp
+ * \brief  melting rate constraints
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ResetConstraintsx.h"
+
+void  ThermalConstraintsReset(Loads* loads, int configuration_type){
+
+	int i;
+
+	/*Enforce constraints: */
+	for(i=0;i<loads->Size();i++){
+		Object* object=(Object*)loads->GetObjectByOffset(i);
+		Load* load=(Load*)object;
+		if(load->InAnalysis(configuration_type)){
+			if(object->ObjectEnum()==PengridEnum){
+
+				Pengrid* pengrid=(Pengrid*)object;
+				pengrid->ResetConstraint();
+			}
+		}
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp	(revision 11330)
@@ -0,0 +1,19 @@
+/*!\file ResetCoordinateSystemx
+ * \brief: reset coordinate system for full-Stokes: tangential to the bedrock
+ */
+
+#include "./ResetCoordinateSystemx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+
+void ResetCoordinateSystemx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,Parameters* parameters){
+
+	Element *element = NULL;
+
+	for (int i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		element->ResetCoordinateSystem();
+	}
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  ResetCoordinateSystemx.h
+ * \brief header file for reset coordinate system module
+ */ 
+
+#ifndef _RESETCOORDINATESYSTEMX_H
+#define _RESETCOORDINATESYSTEMX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void ResetCoordinateSystemx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters); 
+
+#endif  /* _RESETCOORDINATESYSTEMX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/Responsex/Responsex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Responsex/Responsex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Responsex/Responsex.cpp	(revision 11330)
@@ -0,0 +1,54 @@
+/*!\file Responsex
+ * \brief: compute response according to a response descriptor
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../Container/Container.h"    
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../toolkits/toolkits.h"
+#include "../modules.h"
+
+void Responsex(double* responses,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,const char* response_descriptor,bool process_units,int weight_index){
+
+	switch (StringToEnumx(response_descriptor)){
+
+		#ifdef _HAVE_RESPONSES_
+		case IceVolumeEnum:              IceVolumex(               responses, elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case MinVelEnum:                 MinVelx(                  responses, elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case MaxVelEnum:                 MaxVelx(                  responses, elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case MinVxEnum:                  MinVxx(                   responses, elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case MaxVxEnum:                  MaxVxx(                   responses, elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case MaxAbsVxEnum:               MaxAbsVxx(                responses, elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case MinVyEnum:                  MinVyx(                   responses, elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case MaxVyEnum:                  MaxVyx(                   responses, elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case MaxAbsVyEnum:               MaxAbsVyx(                responses, elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case MinVzEnum:                  MinVzx(                   responses, elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case MaxVzEnum:                  MaxVzx(                   responses, elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case MaxAbsVzEnum:               MaxAbsVzx(                responses, elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case MassFluxEnum:               MassFluxx(                responses, elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		case SurfaceAbsVelMisfitEnum:    SurfaceAbsVelMisfitx(     responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case SurfaceRelVelMisfitEnum:    SurfaceRelVelMisfitx(     responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case SurfaceLogVelMisfitEnum:    SurfaceLogVelMisfitx(     responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case SurfaceLogVxVyMisfitEnum:   SurfaceLogVxVyMisfitx(    responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case SurfaceAverageVelMisfitEnum:SurfaceAverageVelMisfitx( responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case ThicknessAbsMisfitEnum:     ThicknessAbsMisfitx(      responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case ThicknessAbsGradientEnum:   ThicknessAbsGradientx(    responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case RheologyBbarAbsGradientEnum:RheologyBbarAbsGradientx( responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case MaterialsRheologyBbarEnum:ElementResponsex(responses, elements,nodes, vertices, loads, materials, parameters,MaterialsRheologyBbarEnum,process_units); break;
+		case VelEnum:ElementResponsex(responses, elements,nodes, vertices, loads, materials, parameters,VelEnum,process_units); break;
+		case FrictionCoefficientEnum:NodalValuex(responses, FrictionCoefficientEnum,elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		default: _error_(" response descriptor \"%s\" not supported yet!",response_descriptor); break;
+		#else
+		default: _error_(" ISSM was not compiled with responses capabilities, exiting!");
+		#endif
+	}
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Responsex/Responsex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Responsex/Responsex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Responsex/Responsex.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  Responsesx.h
+ * \brief header file for computing dakota responses
+ */ 
+
+#ifndef _RESPONSESX_H
+#define _RESPONSESX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+void Responsex(double* presponse,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,const char* response_descriptor,bool process_units,int weight_index);
+
+#endif  /* _RESPONSESXX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file RheologyBbarAbsGradientx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./RheologyBbarAbsGradientx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void RheologyBbarAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+
+	/*Intermediary*/
+	int i;
+	Element* element=NULL;
+
+	/*output: */
+	double J=0;
+	double J_sum;
+
+	/*Compute Misfit: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		J+=element->RheologyBbarAbsGradient(process_units,weight_index);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  RheologyBbarAbsGradientx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _RHEOLOGYBBARGRADIENTX_H
+#define _RHEOLOGYBBARGRADIENTX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void RheologyBbarAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/Scotchx/Scotchx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Scotchx/Scotchx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Scotchx/Scotchx.cpp	(revision 11330)
@@ -0,0 +1,342 @@
+/* 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);
+
+#endif //#ifdef _HAVE_SCOTCH_ 
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Scotchx/Scotchx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Scotchx/Scotchx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Scotchx/Scotchx.h	(revision 11330)
@@ -0,0 +1,70 @@
+/*!\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 "../../Container/Container.h"
+#include "../../objects/objects.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/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 11330)
@@ -0,0 +1,611 @@
+/*!\file Shp2Kmlx
+ * \brief shp to kml conversion routines.
+ */
+
+#include "./Shp2Kmlx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../modules.h"
+
+int Shp2Kmlx(char* filshp,char* filkml,
+			 int sgn){
+
+	#ifdef _HAVE_SHAPELIB_ //only works if Shapelib library has been compiled in.
+	
+	double  cm,sp;
+
+	if (sgn)
+		Xy2lldef(&cm,&sp,sgn);
+
+	return(Shp2Kmlx(filshp,filkml,
+					sgn,cm,sp));
+
+	#endif //ifdef _HAVE_SHAPELIB_
+}
+
+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);
+	_printf_(true,"\nShp2Kmlx Module -- %s",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=(int *) xmalloc(nshape*sizeof(int));
+	pnpart=(int *) xmalloc(nshape*sizeof(int));
+	ppstrt=(int **) xmalloc(nshape*sizeof(int *));
+	pptype=(int **) xmalloc(nshape*sizeof(int *));
+	pnvert=(int *) xmalloc(nshape*sizeof(int));
+	pshapx=(double **) xmalloc(nshape*sizeof(double *));
+	pshapy=(double **) xmalloc(nshape*sizeof(double *));
+	pshapz=(double **) xmalloc(nshape*sizeof(double *));
+	pshapm=(double **) xmalloc(nshape*sizeof(double *));
+
+/*  loop over the list of shapes  */
+
+	for( i = 0; i < nEntities; i++ )
+	{
+//	int     j;
+		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]=(int *) xmalloc(pnpart[i]*sizeof(int));
+		pptype[i]=(int *) xmalloc(pnpart[i]*sizeof(int));
+	}
+	else {
+		ppstrt[i]=NULL;
+		pptype[i]=NULL;
+	}
+	pnvert[i]=psShape->nVertices;
+	if (pnvert[i]) {
+		pshapx[i]=(double *) xmalloc(pnvert[i]*sizeof(double));
+		pshapy[i]=(double *) xmalloc(pnvert[i]*sizeof(double));
+		pshapz[i]=(double *) xmalloc(pnvert[i]*sizeof(double));
+		pshapm[i]=(double *) xmalloc(pnvert[i]*sizeof(double));
+	}
+	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_(true,"Warning -- Shape %d of type \"%s\" should not have %d > 0 parts.\n",
+						 i,SHPTypeName( pstype[i] ),pnpart[i]);
+			if (pnvert[i] > 1)
+				_printf_(true,"Warning -- Shape %d of type \"%s\" should not have %d > 1 vertices.\n",
+						 i,SHPTypeName( pstype[i] ),pnvert[i]);
+
+			kpoint=new KML_Point();
+
+			lat=(double *) xmalloc(pnvert[i]*sizeof(double));
+			lon=(double *) xmalloc(pnvert[i]*sizeof(double));
+			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];
+
+			xfree((void**)&lon);
+			xfree((void**)&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=(double *) xmalloc(pnvert[i]*sizeof(double));
+			lon=(double *) xmalloc(pnvert[i]*sizeof(double));
+			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    =(double (*)[3]) xmalloc(kline->ncoord*3*sizeof(double));
+				for (k=0; k<kline->ncoord; k++) {
+					kline->coords[k][0]=lon      [ppstrt[i][j]+k];
+					kline->coords[k][1]=lat      [ppstrt[i][j]+k];
+					kline->coords[k][2]=pshapz[i][ppstrt[i][j]+k];
+				}
+
+				(kmulti->geometry  )->AddObject((Object*)kline);
+				kline =NULL;
+			}
+
+			xfree((void**)&lon);
+			xfree((void**)&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=(double *) xmalloc(pnvert[i]*sizeof(double));
+			lon=(double *) xmalloc(pnvert[i]*sizeof(double));
+			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    =(double (*)[3]) xmalloc(kring->ncoord*3*sizeof(double));
+					if (cpsum < 0)
+						for (k=0; k<kring->ncoord; k++) {
+							kring->coords[kring->ncoord-1-k][0]=lon      [ppstrt[i][j]+k];
+							kring->coords[kring->ncoord-1-k][1]=lat      [ppstrt[i][j]+k];
+							kring->coords[kring->ncoord-1-k][2]=pshapz[i][ppstrt[i][j]+k];
+						}
+					else
+						for (k=0; k<kring->ncoord; k++) {
+							kring->coords[k                ][0]=lon      [ppstrt[i][j]+k];
+							kring->coords[k                ][1]=lat      [ppstrt[i][j]+k];
+							kring->coords[k                ][2]=pshapz[i][ppstrt[i][j]+k];
+						}
+
+					(kpoly ->outer     )->AddObject((Object*)kring);
+					kring =NULL;
+				}
+
+/*  inner ring (ccw)  */
+
+				else {
+					if (!kpoly) {
+						_printf_(true,"Warning -- Shape %d of type \"%s\", part %d, expected to be outer loop (cw).\n",
+								 i,SHPTypeName( pstype[i] ),j);
+						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    =(double (*)[3]) xmalloc(kring->ncoord*3*sizeof(double));
+					for (k=0; k<kring->ncoord; k++) {
+						kring->coords[k][0]=lon      [ppstrt[i][j]+k];
+						kring->coords[k][1]=lat      [ppstrt[i][j]+k];
+						kring->coords[k][2]=pshapz[i][ppstrt[i][j]+k];
+					}
+
+					(kpoly ->inner     )->AddObject((Object*)kring);
+					kring =NULL;
+				}
+			}
+
+			if (kpoly) {
+				(kmulti->geometry  )->AddObject((Object*)kpoly);
+				kpoly =NULL;
+			}
+
+			xfree((void**)&lon);
+			xfree((void**)&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_(true,"Warning -- Shape %d of type \"%s\" should not have %d > 0 parts.\n",
+						 i,SHPTypeName( pstype[i] ),pnpart[i]);
+
+/*  create a multigeometry to hold all the points  */
+
+			kmulti=new KML_MultiGeometry();
+
+/*  convert to lat/lon, if necessary  */
+
+			lat=(double *) xmalloc(pnvert[i]*sizeof(double));
+			lon=(double *) xmalloc(pnvert[i]*sizeof(double));
+			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;
+			}
+
+			xfree((void**)&lon);
+			xfree((void**)&lat);
+
+			(kplace->geometry  )->AddObject((Object*)kmulti);
+			kmulti=NULL;
+			(kfold ->feature   )->AddObject((Object*)kplace);
+			kplace=NULL;
+		}
+
+/*  multipatch types  */
+
+		else if (pstype[i] == SHPT_MULTIPATCH) {
+			_printf_(true,"Warning -- Shape %d of type \"%s\" will be ignored.\n",
+					 i,SHPTypeName( pstype[i] ));
+			continue;
+		}
+
+/*  unknown type  */
+
+		else {
+			_printf_(true,"Warning -- Shape %d of type \"%s\" will be ignored.\n",
+					 i,SHPTypeName( pstype[i] ));
+		}
+	}
+
+/*  assemble the rest of the kml hierarchy  */
+
+	(kdoc ->feature   )->AddObject((Object*)kfold);
+	kfold=NULL;
+	(kfile->kmlobj    )->AddObject((Object*)kdoc);
+	kdoc =NULL;
+
+/*  write kml file  */
+
+	_printf_(true,"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--) {
+		xfree((void**)&(pshapm[i]));
+		xfree((void**)&(pshapz[i]));
+		xfree((void**)&(pshapy[i]));
+		xfree((void**)&(pshapx[i]));
+	}
+	xfree((void**)&pshapm);
+	xfree((void**)&pshapz);
+	xfree((void**)&pshapy);
+	xfree((void**)&pshapx);
+	xfree((void**)&pnvert);
+	for (i=nshape-1; i>=0; i--) {
+		xfree((void**)&(pptype[i]));
+		xfree((void**)&(ppstrt[i]));
+	}
+	xfree((void**)&pptype);
+	xfree((void**)&ppstrt);
+	xfree((void**)&pnpart);
+	xfree((void**)&pstype);
+
+	clock1=clock();
+	time1 =time(NULL);
+	_printf_(true,"Shp2Kmlx Module -- %f CPU seconds; %f elapsed seconds.\n\n",
+			 ((double)(clock1-clock0))/CLOCKS_PER_SEC,difftime(time1,time0));
+
+	return(iret);
+
+	#endif //ifdef _HAVE_SHAPELIB_
+}
+
Index: /issm/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.h	(revision 11330)
@@ -0,0 +1,29 @@
+/*!\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 "../../Container/Container.h"
+#include "../../objects/objects.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/trunk-jpl-damage/src/c/modules/SmearFunctionx/SmearFunctionx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SmearFunctionx/SmearFunctionx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SmearFunctionx/SmearFunctionx.cpp	(revision 11330)
@@ -0,0 +1,56 @@
+/*!\file SmearFunctionx
+ * \brief: create 
+ */
+
+#include "./SmearFunctionx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void SmearFunctionx(Vec* psmearedvector,double (*WeightFunction)(double distance,double radius), int SmearedFieldEnum, double radius,Elements* elements,Nodes* nodes, Parameters* parameters){
+	
+	Element *element = NULL;
+	Vec x=NULL;
+	Vec y=NULL;
+	Vec z=NULL;
+	Vec smearedvector=NULL;
+	int i;
+
+	double* x_serial=NULL;
+	double* y_serial=NULL;
+	double* z_serial=NULL;
+
+	/*retrive parameters: */
+	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	/*allocate: */
+	gsize=nodes->NumberOfDofs(configuration_type,GsetEnum);
+	smearedvector=NewVec(gsize);
+	
+	x=NewVec(gsize);
+	y=NewVec(gsize);
+	z=NewVec(gsize);
+
+	for(i=0;i<nodes->Size();i++){
+
+	}
+
+
+
+	/*Fill smearedvector vector: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		element->SmearFunction(smearedvector,WeightFunction,SmearedFieldEnum,radius);
+	}
+
+
+	VecAssemblyBegin(smearedvector);
+	VecAssemblyEnd(smearedvector);
+	
+	/*Assign output pointers: */
+	*psmearedvector=smearedvector;
+
+}
+
Index: /issm/trunk-jpl-damage/src/c/modules/SmearFunctionx/SmearFunctionx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SmearFunctionx/SmearFunctionx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SmearFunctionx/SmearFunctionx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  SystemMatricesx.h
+ * \brief header file for degree of freedoms distribution routines.
+ */ 
+
+#ifndef _SYSTEMMATRICESX_H
+#define _SYSTEMMATRICESX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void SystemMatricesx(Mat* pKff, Mat* pKfs, Vec* ppf, Vec* pdf, double* pkmax,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,
+			bool kflag=true,bool pflag=true,bool penalty_kflag=true,bool penalty_pflag=true);
+
+#endif  /* _SYSTEMMATRICESX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/Solverx/DofTypesToIndexSet.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Solverx/DofTypesToIndexSet.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Solverx/DofTypesToIndexSet.cpp	(revision 11330)
@@ -0,0 +1,82 @@
+/*!\file Solverx
+ * \brief solver
+ */
+
+#include "./Solverx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+        
+void DofTypesToIndexSet(IS* pisv, IS* pisp, Vec df,int typeenum){
+
+	/*output: */
+	IS          isv=NULL;
+	IS          isp=NULL;
+
+	int         start,end;
+	double*     df_local=NULL;
+	int         df_local_size;
+	int         i;
+
+	int*     pressure_indices=NULL;
+	int*     velocity_indices=NULL;
+	int      pressure_num=0;
+	int      velocity_num=0;
+	int      pressure_count=0;
+	int      velocity_count=0;
+
+	if(typeenum==StokesSolverEnum){
+
+		/*Ok, recover doftypes vector values and indices: */
+		VecGetOwnershipRange(df,&start,&end);
+		VecGetLocalSize(df,&df_local_size);
+		VecGetArray(df,&df_local);
+
+		pressure_num=0;
+		velocity_num=0;
+		for(i=0;i<df_local_size;i++){
+			if (df_local[i]==PressureEnum)pressure_num++;
+			else velocity_num++;
+		}
+
+		/*Allocate indices: */
+		if(pressure_num)pressure_indices=(int*)xmalloc(pressure_num*sizeof(int));
+		if(velocity_num)velocity_indices=(int*)xmalloc(velocity_num*sizeof(int));
+
+		pressure_count=0;
+		velocity_count=0;
+		for(i=0;i<df_local_size;i++){
+			if (df_local[i]==PressureEnum){
+				pressure_indices[pressure_count]=start+i;
+				pressure_count++;
+			}
+			if (df_local[i]==VelocityEnum){
+				velocity_indices[velocity_count]=start+i;
+				velocity_count++;
+			}
+		}
+		VecRestoreArray(df,&df_local);
+		
+		/*Create indices sets: */
+		#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+		ISCreateGeneral(PETSC_COMM_WORLD,pressure_num,pressure_indices,&isp);
+		ISCreateGeneral(PETSC_COMM_WORLD,velocity_num,velocity_indices,&isv);
+		#else
+		ISCreateGeneral(PETSC_COMM_WORLD,pressure_num,pressure_indices,PETSC_COPY_VALUES,&isp);
+		ISCreateGeneral(PETSC_COMM_WORLD,velocity_num,velocity_indices,PETSC_COPY_VALUES,&isv);
+		#endif
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&pressure_indices);
+	xfree((void**)&velocity_indices);
+
+	/*Assign output pointers:*/
+	*pisv=isv;
+	*pisp=isp;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Solverx/Solverx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Solverx/Solverx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Solverx/Solverx.cpp	(revision 11330)
@@ -0,0 +1,161 @@
+/*!\file Solverx
+ * \brief solver
+ */
+
+#include "./Solverx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+void	Solverx(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;
+	int        analysis_type;
+
+	/*Solver */
+	KSP        ksp              = NULL;
+	PC         pc               = NULL;
+	int        iteration_number;
+	int        solver_type;
+	bool       fromlocalsize    = true;
+	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+	PetscTruth flag,flg;
+	#else
+	PetscBool flag,flg;
+	#endif
+
+	/*Stokes: */
+	IS         isv=NULL;
+	IS         isp=NULL;
+
+	#if _PETSC_MAJOR_ >= 3 
+	char ksp_type[50];
+	#endif
+
+
+	/*Display message*/
+	_printf_(VerboseModule(),"   Solving\n");
+	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+	if(VerboseSolver())PetscOptionsPrint(stdout);
+	#else
+	if(VerboseSolver())PetscOptionsView(PETSC_VIEWER_STDOUT_WORLD);
+	#endif
+
+	/*First, check that f-set is not NULL, i.e. model is fully constrained: {{{*/
+	_assert_(Kff);
+	MatGetSize(Kff,&global_m,&global_n); _assert_(global_m==global_m);
+	if(!global_n){
+		*puf=NULL; return;
+	}
+	/*}}}*/
+	/*Initial guess logic here: {{{1*/
+	/*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,fromlocalsize);
+	}
+	/*}}}*/
+	/*Process petsc options to see if we are using special types of external solvers: {{{1*/
+	PetscOptionsDetermineSolverType(&solver_type);
+
+	/*In serial mode, the matrices have been loaded as MPIAIJ or AIJ matrices. 
+	 We need to convert them if we are going to run the solvers successfully: */
+	#ifdef _SERIAL_
+	#if _PETSC_MAJOR_ == 2 
+	if (solver_type==MUMPSPACKAGE_LU){
+		/*Convert Kff to MATTAIJMUMPS: */
+		MatConvert(Kff,MATAIJMUMPS,MAT_REUSE_MATRIX,&Kff);
+	}
+	if (solver_type==MUMPSPACKAGE_CHOL){
+		/*Convert Kff to MATTSBAIJMUMPS: */
+		MatConvert(Kff,MATSBAIJMUMPS,MAT_REUSE_MATRIX,&Kff);
+	}
+	if (solver_type==SPOOLESPACKAGE_LU){
+		/*Convert Kff to MATTSBAIJMUMPS: */
+		MatConvert(Kff,MATAIJSPOOLES,MAT_REUSE_MATRIX,&Kff);
+	}
+	if (solver_type==SPOOLESPACKAGE_CHOL){
+		/*Convert Kff to MATTSBAIJMUMPS: */
+		MatConvert(Kff,MATSBAIJSPOOLES,MAT_REUSE_MATRIX,&Kff);
+	}
+	if (solver_type==SUPERLUDISTPACKAGE){
+		/*Convert Kff to MATTSBAIJMUMPS: */
+		MatConvert(Kff,MATSUPERLU_DIST,MAT_REUSE_MATRIX,&Kff);
+	}
+	if (solver_type==StokesSolverEnum){
+		_error_("Petsc 2 does not support multi-physics solvers");
+	}
+	#endif
+	#endif
+	/*}}}*/
+	/*Prepare solver:{{{1*/
+	KSPCreate(MPI_COMM_WORLD,&ksp);
+	KSPSetOperators(ksp,Kff,Kff,DIFFERENT_NONZERO_PATTERN);
+	KSPSetFromOptions(ksp);
+
+	#if defined(_SERIAL_) && _PETSC_VERSION_==3
+	/*Specific solver?: */
+	KSPGetPC(ksp,&pc);
+	if (solver_type==MUMPSPACKAGE_LU){
+		PCFactorSetMatSolverPackage(pc,MAT_SOLVER_MUMPS);
+	}
+	#endif
+
+	#if defined(_PARALLEL_) && _PETSC_VERSION_==3
+	/*Stokes: */
+	if (solver_type==StokesSolverEnum){
+		/*Make indices out of doftypes: */
+		if(!df)_error_("need doftypes for Stokes solver!\n");
+		DofTypesToIndexSet(&isv,&isp,df,StokesSolverEnum);
+
+		/*Set field splits: */
+		KSPGetPC(ksp,&pc);
+		PCFieldSplitSetIS(pc,isv);
+		PCFieldSplitSetIS(pc,isp);
+
+	}
+	#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: {{{1*/
+	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);
+		}
+	}
+	/*}}}*/
+	
+	if(VerboseSolver())KSPView(ksp,PETSC_VIEWER_STDOUT_WORLD);
+
+	/*Solve: */
+	KSPSolve(ksp,pf,uf);
+	
+	/*Check convergence*/
+	KSPGetIterationNumber(ksp,&iteration_number);
+	if (iteration_number<0) _error_("%s%i"," Solver diverged at iteration number: ",-iteration_number);
+
+	/*Free resources:*/
+	KSPFree(&ksp);
+		
+	/*Assign output pointers:*/
+	*puf=uf;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Solverx/Solverx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Solverx/Solverx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Solverx/Solverx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  Solverx.h
+ * \brief solver
+ */ 
+
+#ifndef _SOLVERX_H
+#define _SOLVERX_H
+
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void	Solverx( Vec* puf, Mat Kff, Vec pf, Vec uf0,Vec df,Parameters* parameters);
+void    DofTypesToIndexSet(IS* pisv, IS* pisp, Vec df,int typeenum);
+#endif  /* _SOLVERX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/SpcNodesx/SpcNodesx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SpcNodesx/SpcNodesx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SpcNodesx/SpcNodesx.cpp	(revision 11330)
@@ -0,0 +1,26 @@
+/*!\file SpcNodesx
+ * \brief: establish single point constraints on all nodes, as well as constraints vector.
+ */
+
+#include "./SpcNodesx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void SpcNodesx(Nodes* nodes,Constraints* constraints,Parameters* parameters, int analysis_type){
+
+	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/trunk-jpl-damage/src/c/modules/SpcNodesx/SpcNodesx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SpcNodesx/SpcNodesx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SpcNodesx/SpcNodesx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  SpcNodesx.h
+ * \brief header file for node single point constraints
+ */ 
+
+#ifndef _SPCNODESX_H
+#define _SPCNODESX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+#include "../../toolkits/toolkits.h"
+
+/* local prototypes: */
+void SpcNodesx(Nodes* nodes, Constraints* constraints,Parameters* parameters,int analysis_type);
+
+#endif  /* _SPCNODESX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/StringToEnumx/StringToEnumx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/StringToEnumx/StringToEnumx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/StringToEnumx/StringToEnumx.cpp	(revision 11330)
@@ -0,0 +1,444 @@
+/*
+* \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 "../../shared/shared.h"
+#include "../../include/include.h"
+#include "./StringToEnumx.h"
+
+int  StringToEnumx(const char* name){
+
+	if (strcmp(name,"AutodiffForward")==0) return AutodiffForwardEnum;
+	else if (strcmp(name,"AutodiffIsautodiff")==0) return AutodiffIsautodiffEnum;
+	else if (strcmp(name,"AutodiffReverse")==0) return AutodiffReverseEnum;
+	else if (strcmp(name,"BalancethicknessSpcthickness")==0) return BalancethicknessSpcthicknessEnum;
+	else if (strcmp(name,"BalancethicknessStabilization")==0) return BalancethicknessStabilizationEnum;
+	else if (strcmp(name,"BalancethicknessThickeningRate")==0) return BalancethicknessThickeningRateEnum;
+	else if (strcmp(name,"BasalforcingsGeothermalflux")==0) return BasalforcingsGeothermalfluxEnum;
+	else if (strcmp(name,"BasalforcingsMeltingRateCorrection")==0) return BasalforcingsMeltingRateCorrectionEnum;
+	else if (strcmp(name,"BasalforcingsMeltingRate")==0) return BasalforcingsMeltingRateEnum;
+	else if (strcmp(name,"Bathymetry")==0) return BathymetryEnum;
+	else if (strcmp(name,"Bed")==0) return BedEnum;
+	else if (strcmp(name,"ConstantsG")==0) return ConstantsGEnum;
+	else if (strcmp(name,"ConstantsReferencetemperature")==0) return ConstantsReferencetemperatureEnum;
+	else if (strcmp(name,"ConstantsYts")==0) return ConstantsYtsEnum;
+	else if (strcmp(name,"DiagnosticAbstol")==0) return DiagnosticAbstolEnum;
+	else if (strcmp(name,"DiagnosticIcefront")==0) return DiagnosticIcefrontEnum;
+	else if (strcmp(name,"DiagnosticMaxiter")==0) return DiagnosticMaxiterEnum;
+	else if (strcmp(name,"DiagnosticNumRequestedOutputs")==0) return DiagnosticNumRequestedOutputsEnum;
+	else if (strcmp(name,"DiagnosticPenaltyFactor")==0) return DiagnosticPenaltyFactorEnum;
+	else if (strcmp(name,"DiagnosticReferential")==0) return DiagnosticReferentialEnum;
+	else if (strcmp(name,"DiagnosticReltol")==0) return DiagnosticReltolEnum;
+	else if (strcmp(name,"DiagnosticRequestedOutputs")==0) return DiagnosticRequestedOutputsEnum;
+	else if (strcmp(name,"DiagnosticRestol")==0) return DiagnosticRestolEnum;
+	else if (strcmp(name,"DiagnosticRiftPenaltyLock")==0) return DiagnosticRiftPenaltyLockEnum;
+	else if (strcmp(name,"DiagnosticRiftPenaltyThreshold")==0) return DiagnosticRiftPenaltyThresholdEnum;
+	else if (strcmp(name,"DiagnosticShelfDampening")==0) return DiagnosticShelfDampeningEnum;
+	else if (strcmp(name,"DiagnosticSpcvx")==0) return DiagnosticSpcvxEnum;
+	else if (strcmp(name,"DiagnosticSpcvy")==0) return DiagnosticSpcvyEnum;
+	else if (strcmp(name,"DiagnosticSpcvz")==0) return DiagnosticSpcvzEnum;
+	else if (strcmp(name,"DiagnosticStokesreconditioning")==0) return DiagnosticStokesreconditioningEnum;
+	else if (strcmp(name,"DiagnosticVertexPairing")==0) return DiagnosticVertexPairingEnum;
+	else if (strcmp(name,"DiagnosticViscosityOvershoot")==0) return DiagnosticViscosityOvershootEnum;
+	else if (strcmp(name,"FlowequationBordermacayeal")==0) return FlowequationBordermacayealEnum;
+	else if (strcmp(name,"FlowequationBorderpattyn")==0) return FlowequationBorderpattynEnum;
+	else if (strcmp(name,"FlowequationBorderstokes")==0) return FlowequationBorderstokesEnum;
+	else if (strcmp(name,"FlowequationElementEquation")==0) return FlowequationElementEquationEnum;
+	else if (strcmp(name,"FlowequationIshutter")==0) return FlowequationIshutterEnum;
+	else if (strcmp(name,"FlowequationIsmacayealpattyn")==0) return FlowequationIsmacayealpattynEnum;
+	else if (strcmp(name,"FlowequationIsstokes")==0) return FlowequationIsstokesEnum;
+	else if (strcmp(name,"FlowequationVertexEquation")==0) return FlowequationVertexEquationEnum;
+	else if (strcmp(name,"FrictionCoefficient")==0) return FrictionCoefficientEnum;
+	else if (strcmp(name,"FrictionP")==0) return FrictionPEnum;
+	else if (strcmp(name,"FrictionQ")==0) return FrictionQEnum;
+	else if (strcmp(name,"GeometryHydrostaticRatio")==0) return GeometryHydrostaticRatioEnum;
+	else if (strcmp(name,"HydrologyCR")==0) return HydrologyCREnum;
+	else if (strcmp(name,"HydrologyKn")==0) return HydrologyKnEnum;
+	else if (strcmp(name,"HydrologyN")==0) return HydrologyNEnum;
+	else if (strcmp(name,"HydrologyP")==0) return HydrologyPEnum;
+	else if (strcmp(name,"HydrologyQ")==0) return HydrologyQEnum;
+	else if (strcmp(name,"HydrologySpcwatercolumn")==0) return HydrologySpcwatercolumnEnum;
+	else if (strcmp(name,"HydrologyStabilization")==0) return HydrologyStabilizationEnum;
+	else if (strcmp(name,"InversionControlParameters")==0) return InversionControlParametersEnum;
+	else if (strcmp(name,"InversionCostFunction")==0) return InversionCostFunctionEnum;
+	else if (strcmp(name,"InversionCostFunctionThreshold")==0) return InversionCostFunctionThresholdEnum;
+	else if (strcmp(name,"InversionCostFunctionsCoefficients")==0) return InversionCostFunctionsCoefficientsEnum;
+	else if (strcmp(name,"InversionCostFunctions")==0) return InversionCostFunctionsEnum;
+	else if (strcmp(name,"InversionGradientOnly")==0) return InversionGradientOnlyEnum;
+	else if (strcmp(name,"InversionGradientScaling")==0) return InversionGradientScalingEnum;
+	else if (strcmp(name,"InversionIscontrol")==0) return InversionIscontrolEnum;
+	else if (strcmp(name,"InversionTao")==0) return InversionTaoEnum;
+	else if (strcmp(name,"InversionMaxParameters")==0) return InversionMaxParametersEnum;
+	else if (strcmp(name,"InversionMaxiterPerStep")==0) return InversionMaxiterPerStepEnum;
+	else if (strcmp(name,"InversionMinParameters")==0) return InversionMinParametersEnum;
+	else if (strcmp(name,"InversionNsteps")==0) return InversionNstepsEnum;
+	else if (strcmp(name,"InversionNumControlParameters")==0) return InversionNumControlParametersEnum;
+	else if (strcmp(name,"InversionNumCostFunctions")==0) return InversionNumCostFunctionsEnum;
+	else if (strcmp(name,"InversionStepThreshold")==0) return InversionStepThresholdEnum;
+	else if (strcmp(name,"InversionThicknessObs")==0) return InversionThicknessObsEnum;
+	else if (strcmp(name,"InversionVelObs")==0) return InversionVelObsEnum;
+	else if (strcmp(name,"InversionVxObs")==0) return InversionVxObsEnum;
+	else if (strcmp(name,"InversionVyObs")==0) return InversionVyObsEnum;
+	else if (strcmp(name,"InversionVzObs")==0) return InversionVzObsEnum;
+	else if (strcmp(name,"MaskElementonfloatingice")==0) return MaskElementonfloatingiceEnum;
+	else if (strcmp(name,"MaskElementongroundedice")==0) return MaskElementongroundediceEnum;
+	else if (strcmp(name,"MaskElementonwater")==0) return MaskElementonwaterEnum;
+	else if (strcmp(name,"MaskVertexonfloatingice")==0) return MaskVertexonfloatingiceEnum;
+	else if (strcmp(name,"MaskVertexongroundedice")==0) return MaskVertexongroundediceEnum;
+	else if (strcmp(name,"MaskVertexonwater")==0) return MaskVertexonwaterEnum;
+	else if (strcmp(name,"MaterialsBeta")==0) return MaterialsBetaEnum;
+	else if (strcmp(name,"MaterialsHeatcapacity")==0) return MaterialsHeatcapacityEnum;
+	else if (strcmp(name,"MaterialsLatentheat")==0) return MaterialsLatentheatEnum;
+	else if (strcmp(name,"MaterialsMeltingpoint")==0) return MaterialsMeltingpointEnum;
+	else if (strcmp(name,"MaterialsMixedLayerCapacity")==0) return MaterialsMixedLayerCapacityEnum;
+	else if (strcmp(name,"MaterialsRheologyB")==0) return MaterialsRheologyBEnum;
+	else if (strcmp(name,"MaterialsRheologyBbar")==0) return MaterialsRheologyBbarEnum;
+	else if (strcmp(name,"MaterialsRheologyLaw")==0) return MaterialsRheologyLawEnum;
+	else if (strcmp(name,"MaterialsRheologyN")==0) return MaterialsRheologyNEnum;
+	else if (strcmp(name,"MaterialsRhoIce")==0) return MaterialsRhoIceEnum;
+	else if (strcmp(name,"MaterialsRhoWater")==0) return MaterialsRhoWaterEnum;
+	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,"MeshAverageVertexConnectivity")==0) return MeshAverageVertexConnectivityEnum;
+	else if (strcmp(name,"MeshDimension")==0) return MeshDimensionEnum;
+	else if (strcmp(name,"MeshEdges")==0) return MeshEdgesEnum;
+	else if (strcmp(name,"MeshElementconnectivity")==0) return MeshElementconnectivityEnum;
+	else if (strcmp(name,"MeshElementonbed")==0) return MeshElementonbedEnum;
+	else if (strcmp(name,"MeshElementonsurface")==0) return MeshElementonsurfaceEnum;
+	else if (strcmp(name,"MeshElements2d")==0) return MeshElements2dEnum;
+	else if (strcmp(name,"MeshElements")==0) return MeshElementsEnum;
+	else if (strcmp(name,"MeshLowerelements")==0) return MeshLowerelementsEnum;
+	else if (strcmp(name,"MeshNumberofedges")==0) return MeshNumberofedgesEnum;
+	else if (strcmp(name,"MeshNumberofelements2d")==0) return MeshNumberofelements2dEnum;
+	else if (strcmp(name,"MeshNumberofelements")==0) return MeshNumberofelementsEnum;
+	else if (strcmp(name,"MeshNumberoflayers")==0) return MeshNumberoflayersEnum;
+	else if (strcmp(name,"MeshNumberofvertices2d")==0) return MeshNumberofvertices2dEnum;
+	else if (strcmp(name,"MeshNumberofvertices")==0) return MeshNumberofverticesEnum;
+	else if (strcmp(name,"MeshUpperelements")==0) return MeshUpperelementsEnum;
+	else if (strcmp(name,"MeshVertexonbed")==0) return MeshVertexonbedEnum;
+	else if (strcmp(name,"MeshVertexonsurface")==0) return MeshVertexonsurfaceEnum;
+	else if (strcmp(name,"MeshX")==0) return MeshXEnum;
+	else if (strcmp(name,"MeshY")==0) return MeshYEnum;
+	else if (strcmp(name,"MeshZ")==0) return MeshZEnum;
+	else if (strcmp(name,"MiscellaneousName")==0) return MiscellaneousNameEnum;
+	else if (strcmp(name,"PrognosticHydrostaticAdjustment")==0) return PrognosticHydrostaticAdjustmentEnum;
+	else if (strcmp(name,"PrognosticMinThickness")==0) return PrognosticMinThicknessEnum;
+	else if (strcmp(name,"PrognosticPenaltyFactor")==0) return PrognosticPenaltyFactorEnum;
+	else if (strcmp(name,"PrognosticSpcthickness")==0) return PrognosticSpcthicknessEnum;
+	else if (strcmp(name,"PrognosticStabilization")==0) return PrognosticStabilizationEnum;
+	else if (strcmp(name,"PrognosticVertexPairing")==0) return PrognosticVertexPairingEnum;
+	else if (strcmp(name,"QmuIsdakota")==0) return QmuIsdakotaEnum;
+	else if (strcmp(name,"QmuMassFluxSegments")==0) return QmuMassFluxSegmentsEnum;
+	else if (strcmp(name,"QmuNumberofpartitions")==0) return QmuNumberofpartitionsEnum;
+	else if (strcmp(name,"QmuNumberofresponses")==0) return QmuNumberofresponsesEnum;
+	else if (strcmp(name,"QmuPartition")==0) return QmuPartitionEnum;
+	else if (strcmp(name,"QmuResponsedescriptors")==0) return QmuResponsedescriptorsEnum;
+	else if (strcmp(name,"QmuVariabledescriptors")==0) return QmuVariabledescriptorsEnum;
+	else if (strcmp(name,"RiftsNumrifts")==0) return RiftsNumriftsEnum;
+	else if (strcmp(name,"RiftsRiftstruct")==0) return RiftsRiftstructEnum;
+	else if (strcmp(name,"SettingsIoGather")==0) return SettingsIoGatherEnum;
+	else if (strcmp(name,"SettingsLowmem")==0) return SettingsLowmemEnum;
+	else if (strcmp(name,"SettingsOutputFrequency")==0) return SettingsOutputFrequencyEnum;
+	else if (strcmp(name,"SettingsResultsAsPatches")==0) return SettingsResultsAsPatchesEnum;
+	else if (strcmp(name,"SettingsWaitonlock")==0) return SettingsWaitonlockEnum;
+	else if (strcmp(name,"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,"SurfaceforcingsAblationRate")==0) return SurfaceforcingsAblationRateEnum;
+	else if (strcmp(name,"SurfaceforcingsAccumulationRate")==0) return SurfaceforcingsAccumulationRateEnum;
+	else if (strcmp(name,"SurfaceforcingsMassBalance")==0) return SurfaceforcingsMassBalanceEnum;
+	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,"Thickness")==0) return ThicknessEnum;
+	else if (strcmp(name,"TimesteppingCflCoefficient")==0) return TimesteppingCflCoefficientEnum;
+	else if (strcmp(name,"TimesteppingFinalTime")==0) return TimesteppingFinalTimeEnum;
+	else if (strcmp(name,"TimesteppingTimeAdapt")==0) return TimesteppingTimeAdaptEnum;
+	else if (strcmp(name,"TimesteppingTimeStep")==0) return TimesteppingTimeStepEnum;
+	else if (strcmp(name,"TransientIsdiagnostic")==0) return TransientIsdiagnosticEnum;
+	else if (strcmp(name,"TransientIsgroundingline")==0) return TransientIsgroundinglineEnum;
+	else if (strcmp(name,"TransientIsprognostic")==0) return TransientIsprognosticEnum;
+	else if (strcmp(name,"TransientIsthermal")==0) return TransientIsthermalEnum;
+	else if (strcmp(name,"TransientNumRequestedOutputs")==0) return TransientNumRequestedOutputsEnum;
+	else if (strcmp(name,"TransientRequestedOutputs")==0) return TransientRequestedOutputsEnum;
+	else if (strcmp(name,"SolutionType")==0) return SolutionTypeEnum;
+	else if (strcmp(name,"AnalysisType")==0) return AnalysisTypeEnum;
+	else if (strcmp(name,"ConfigurationType")==0) return ConfigurationTypeEnum;
+	else if (strcmp(name,"AdjointBalancethicknessAnalysis")==0) return AdjointBalancethicknessAnalysisEnum;
+	else if (strcmp(name,"AdjointHorizAnalysis")==0) return AdjointHorizAnalysisEnum;
+	else if (strcmp(name,"AdjointSolution")==0) return AdjointSolutionEnum;
+	else if (strcmp(name,"AnalysisCounter")==0) return AnalysisCounterEnum;
+	else if (strcmp(name,"BalancethicknessAnalysis")==0) return BalancethicknessAnalysisEnum;
+	else if (strcmp(name,"BalancethicknessSolution")==0) return BalancethicknessSolutionEnum;
+	else if (strcmp(name,"BedSlopeAnalysis")==0) return BedSlopeAnalysisEnum;
+	else if (strcmp(name,"BedSlopeSolution")==0) return BedSlopeSolutionEnum;
+	else if (strcmp(name,"BedSlopeXAnalysis")==0) return BedSlopeXAnalysisEnum;
+	else if (strcmp(name,"BedSlopeYAnalysis")==0) return BedSlopeYAnalysisEnum;
+	else if (strcmp(name,"DiagnosticHorizAnalysis")==0) return DiagnosticHorizAnalysisEnum;
+	else if (strcmp(name,"DiagnosticHutterAnalysis")==0) return DiagnosticHutterAnalysisEnum;
+	else if (strcmp(name,"DiagnosticSolution")==0) return DiagnosticSolutionEnum;
+	else if (strcmp(name,"DiagnosticVertAnalysis")==0) return DiagnosticVertAnalysisEnum;
+	else if (strcmp(name,"EnthalpyAnalysis")==0) return EnthalpyAnalysisEnum;
+	else if (strcmp(name,"EnthalpySolution")==0) return EnthalpySolutionEnum;
+	else if (strcmp(name,"FlaimAnalysis")==0) return FlaimAnalysisEnum;
+	else if (strcmp(name,"FlaimSolution")==0) return FlaimSolutionEnum;
+	else if (strcmp(name,"HydrologyAnalysis")==0) return HydrologyAnalysisEnum;
+	else if (strcmp(name,"HydrologySolution")==0) return HydrologySolutionEnum;
+	else if (strcmp(name,"MeltingAnalysis")==0) return MeltingAnalysisEnum;
+	else if (strcmp(name,"NoneAnalysis")==0) return NoneAnalysisEnum;
+	else if (strcmp(name,"PrognosticAnalysis")==0) return PrognosticAnalysisEnum;
+	else if (strcmp(name,"PrognosticSolution")==0) return PrognosticSolutionEnum;
+	else if (strcmp(name,"SteadystateSolution")==0) return SteadystateSolutionEnum;
+	else if (strcmp(name,"SurfaceSlopeAnalysis")==0) return SurfaceSlopeAnalysisEnum;
+	else if (strcmp(name,"SurfaceSlopeSolution")==0) return SurfaceSlopeSolutionEnum;
+	else if (strcmp(name,"SurfaceSlopeXAnalysis")==0) return SurfaceSlopeXAnalysisEnum;
+	else if (strcmp(name,"SurfaceSlopeYAnalysis")==0) return SurfaceSlopeYAnalysisEnum;
+	else if (strcmp(name,"ThermalAnalysis")==0) return ThermalAnalysisEnum;
+	else if (strcmp(name,"ThermalSolution")==0) return ThermalSolutionEnum;
+	else if (strcmp(name,"TransientSolution")==0) return TransientSolutionEnum;
+	else if (strcmp(name,"Approximation")==0) return ApproximationEnum;
+	else if (strcmp(name,"HutterApproximation")==0) return HutterApproximationEnum;
+	else if (strcmp(name,"MacAyealApproximation")==0) return MacAyealApproximationEnum;
+	else if (strcmp(name,"MacAyealPattynApproximation")==0) return MacAyealPattynApproximationEnum;
+	else if (strcmp(name,"MacAyealStokesApproximation")==0) return MacAyealStokesApproximationEnum;
+	else if (strcmp(name,"NoneApproximation")==0) return NoneApproximationEnum;
+	else if (strcmp(name,"PattynApproximation")==0) return PattynApproximationEnum;
+	else if (strcmp(name,"PattynStokesApproximation")==0) return PattynStokesApproximationEnum;
+	else if (strcmp(name,"StokesApproximation")==0) return StokesApproximationEnum;
+	else if (strcmp(name,"Constraints")==0) return ConstraintsEnum;
+	else if (strcmp(name,"Loads")==0) return LoadsEnum;
+	else if (strcmp(name,"Materials")==0) return MaterialsEnum;
+	else if (strcmp(name,"Nodes")==0) return NodesEnum;
+	else if (strcmp(name,"Parameters")==0) return ParametersEnum;
+	else if (strcmp(name,"Vertices")==0) return VerticesEnum;
+	else if (strcmp(name,"Results")==0) return ResultsEnum;
+	else if (strcmp(name,"BoolInput")==0) return BoolInputEnum;
+	else if (strcmp(name,"BoolParam")==0) return BoolParamEnum;
+	else if (strcmp(name,"ControlInput")==0) return ControlInputEnum;
+	else if (strcmp(name,"DatasetInput")==0) return DatasetInputEnum;
+	else if (strcmp(name,"DofIndexing")==0) return DofIndexingEnum;
+	else if (strcmp(name,"DoubleInput")==0) return DoubleInputEnum;
+	else if (strcmp(name,"DoubleMatArrayParam")==0) return DoubleMatArrayParamEnum;
+	else if (strcmp(name,"DoubleMatParam")==0) return DoubleMatParamEnum;
+	else if (strcmp(name,"DoubleParam")==0) return DoubleParamEnum;
+	else if (strcmp(name,"DoubleVecParam")==0) return DoubleVecParamEnum;
+	else if (strcmp(name,"Element")==0) return ElementEnum;
+	else if (strcmp(name,"ElementResult")==0) return ElementResultEnum;
+	else if (strcmp(name,"ExternalResult")==0) return ExternalResultEnum;
+	else if (strcmp(name,"FileParam")==0) return FileParamEnum;
+	else if (strcmp(name,"Hook")==0) return HookEnum;
+	else if (strcmp(name,"Icefront")==0) return IcefrontEnum;
+	else if (strcmp(name,"Input")==0) return InputEnum;
+	else if (strcmp(name,"IntInput")==0) return IntInputEnum;
+	else if (strcmp(name,"IntParam")==0) return IntParamEnum;
+	else if (strcmp(name,"IntVecParam")==0) return IntVecParamEnum;
+	else if (strcmp(name,"MacAyeal2dIceFront")==0) return MacAyeal2dIceFrontEnum;
+	else if (strcmp(name,"MacAyeal3dIceFront")==0) return MacAyeal3dIceFrontEnum;
+	else if (strcmp(name,"Matice")==0) return MaticeEnum;
+	else if (strcmp(name,"Matpar")==0) return MatparEnum;
+	else if (strcmp(name,"Node")==0) return NodeEnum;
+	else if (strcmp(name,"Numericalflux")==0) return NumericalfluxEnum;
+	else if (strcmp(name,"Param")==0) return ParamEnum;
+	else if (strcmp(name,"PattynIceFront")==0) return PattynIceFrontEnum;
+	else if (strcmp(name,"Pengrid")==0) return PengridEnum;
+	else if (strcmp(name,"Penpair")==0) return PenpairEnum;
+	else if (strcmp(name,"Penta")==0) return PentaEnum;
+	else if (strcmp(name,"PentaP1Input")==0) return PentaP1InputEnum;
+	else if (strcmp(name,"PetscMatParam")==0) return PetscMatParamEnum;
+	else if (strcmp(name,"PetscVecParam")==0) return PetscVecParamEnum;
+	else if (strcmp(name,"Riftfront")==0) return RiftfrontEnum;
+	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,"StokesIceFront")==0) return StokesIceFrontEnum;
+	else if (strcmp(name,"StringArrayParam")==0) return StringArrayParamEnum;
+	else if (strcmp(name,"StringParam")==0) return StringParamEnum;
+	else if (strcmp(name,"Tria")==0) return TriaEnum;
+	else if (strcmp(name,"TriaP1Input")==0) return TriaP1InputEnum;
+	else if (strcmp(name,"Vertex")==0) return VertexEnum;
+	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,"BedSlopeX")==0) return BedSlopeXEnum;
+	else if (strcmp(name,"BedSlopeY")==0) return BedSlopeYEnum;
+	else if (strcmp(name,"Boundary")==0) return BoundaryEnum;
+	else if (strcmp(name,"Constant")==0) return ConstantEnum;
+	else if (strcmp(name,"Converged")==0) return ConvergedEnum;
+	else if (strcmp(name,"ExtToIu")==0) return ExtToIuEnum;
+	else if (strcmp(name,"Fill")==0) return FillEnum;
+	else if (strcmp(name,"FractionIncrement")==0) return FractionIncrementEnum;
+	else if (strcmp(name,"Friction")==0) return FrictionEnum;
+	else if (strcmp(name,"GroundinglineMeltingRate")==0) return GroundinglineMeltingRateEnum;
+	else if (strcmp(name,"Internal")==0) return InternalEnum;
+	else if (strcmp(name,"IuToExt")==0) return IuToExtEnum;
+	else if (strcmp(name,"MassFlux")==0) return MassFluxEnum;
+	else if (strcmp(name,"MaxPenetration")==0) return MaxPenetrationEnum;
+	else if (strcmp(name,"MeltingOffset")==0) return MeltingOffsetEnum;
+	else if (strcmp(name,"Misfit")==0) return MisfitEnum;
+	else if (strcmp(name,"NumberNodeToElementConnectivity")==0) return NumberNodeToElementConnectivityEnum;
+	else if (strcmp(name,"Pressure")==0) return PressureEnum;
+	else if (strcmp(name,"PressurePicard")==0) return PressurePicardEnum;
+	else if (strcmp(name,"QmuPressure")==0) return QmuPressureEnum;
+	else if (strcmp(name,"QmuVx")==0) return QmuVxEnum;
+	else if (strcmp(name,"QmuVy")==0) return QmuVyEnum;
+	else if (strcmp(name,"QmuVz")==0) return QmuVzEnum;
+	else if (strcmp(name,"QmuThickness")==0) return QmuThicknessEnum;
+	else if (strcmp(name,"QmuBed")==0) return QmuBedEnum;
+	else if (strcmp(name,"QmuSurface")==0) return QmuSurfaceEnum;
+	else if (strcmp(name,"QmuMelting")==0) return QmuMeltingEnum;
+	else if (strcmp(name,"ResetPenalties")==0) return ResetPenaltiesEnum;
+	else if (strcmp(name,"SegmentOnIceShelf")==0) return SegmentOnIceShelfEnum;
+	else if (strcmp(name,"SurfaceAbsVelMisfit")==0) return SurfaceAbsVelMisfitEnum;
+	else if (strcmp(name,"SurfaceArea")==0) return SurfaceAreaEnum;
+	else if (strcmp(name,"SurfaceAverageVelMisfit")==0) return SurfaceAverageVelMisfitEnum;
+	else if (strcmp(name,"SurfaceLogVelMisfit")==0) return SurfaceLogVelMisfitEnum;
+	else if (strcmp(name,"SurfaceLogVxVyMisfit")==0) return SurfaceLogVxVyMisfitEnum;
+	else if (strcmp(name,"SurfaceRelVelMisfit")==0) return SurfaceRelVelMisfitEnum;
+	else if (strcmp(name,"SurfaceSlopeX")==0) return SurfaceSlopeXEnum;
+	else if (strcmp(name,"SurfaceSlopeY")==0) return SurfaceSlopeYEnum;
+	else if (strcmp(name,"Temperature")==0) return TemperatureEnum;
+	else if (strcmp(name,"TemperatureOld")==0) return TemperatureOldEnum;
+	else if (strcmp(name,"TemperaturePicard")==0) return TemperaturePicardEnum;
+	else if (strcmp(name,"ThicknessAbsMisfit")==0) return ThicknessAbsMisfitEnum;
+	else if (strcmp(name,"Type")==0) return TypeEnum;
+	else if (strcmp(name,"Vel")==0) return VelEnum;
+	else if (strcmp(name,"Velocity")==0) return VelocityEnum;
+	else if (strcmp(name,"VxAverage")==0) return VxAverageEnum;
+	else if (strcmp(name,"Vx")==0) return VxEnum;
+	else if (strcmp(name,"VxPicard")==0) return VxPicardEnum;
+	else if (strcmp(name,"VyAverage")==0) return VyAverageEnum;
+	else if (strcmp(name,"Vy")==0) return VyEnum;
+	else if (strcmp(name,"VyPicard")==0) return VyPicardEnum;
+	else if (strcmp(name,"Vz")==0) return VzEnum;
+	else if (strcmp(name,"VzMacAyeal")==0) return VzMacAyealEnum;
+	else if (strcmp(name,"VzPattyn")==0) return VzPattynEnum;
+	else if (strcmp(name,"VzPicard")==0) return VzPicardEnum;
+	else if (strcmp(name,"VzStokes")==0) return VzStokesEnum;
+	else if (strcmp(name,"VxMesh")==0) return VxMeshEnum;
+	else if (strcmp(name,"VyMesh")==0) return VyMeshEnum;
+	else if (strcmp(name,"VzMesh")==0) return VzMeshEnum;
+	else if (strcmp(name,"Enthalpy")==0) return EnthalpyEnum;
+	else if (strcmp(name,"EnthalpyPicard")==0) return EnthalpyPicardEnum;
+	else if (strcmp(name,"ThicknessAbsGradient")==0) return ThicknessAbsGradientEnum;
+	else if (strcmp(name,"StepResponses")==0) return StepResponsesEnum;
+	else if (strcmp(name,"IntMatParam")==0) return IntMatParamEnum;
+	else if (strcmp(name,"RheologyBbarAbsGradient")==0) return RheologyBbarAbsGradientEnum;
+	else if (strcmp(name,"DragCoefficientAbsGradient")==0) return DragCoefficientAbsGradientEnum;
+	else if (strcmp(name,"TransientInput")==0) return TransientInputEnum;
+	else if (strcmp(name,"Outputfilename")==0) return OutputfilenameEnum;
+	else if (strcmp(name,"Waterfraction")==0) return WaterfractionEnum;
+	else if (strcmp(name,"Watercolumn")==0) return WatercolumnEnum;
+	else if (strcmp(name,"BasalFriction")==0) return BasalFrictionEnum;
+	else if (strcmp(name,"ViscousHeating")==0) return ViscousHeatingEnum;
+	else if (strcmp(name,"QmuTemperature")==0) return QmuTemperatureEnum;
+	else if (strcmp(name,"HydrologyWaterVx")==0) return HydrologyWaterVxEnum;
+	else if (strcmp(name,"HydrologyWaterVy")==0) return HydrologyWaterVyEnum;
+	else if (strcmp(name,"StressTensor")==0) return StressTensorEnum;
+	else if (strcmp(name,"StressTensorxx")==0) return StressTensorxxEnum;
+	else if (strcmp(name,"StressTensorxy")==0) return StressTensorxyEnum;
+	else if (strcmp(name,"StressTensorxz")==0) return StressTensorxzEnum;
+	else if (strcmp(name,"StressTensoryy")==0) return StressTensoryyEnum;
+	else if (strcmp(name,"StressTensoryz")==0) return StressTensoryzEnum;
+	else if (strcmp(name,"StressTensorzz")==0) return StressTensorzzEnum;
+	else if (strcmp(name,"IceVolume")==0) return IceVolumeEnum;
+	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,"BoolElementResult")==0) return BoolElementResultEnum;
+	else if (strcmp(name,"BoolExternalResult")==0) return BoolExternalResultEnum;
+	else if (strcmp(name,"DoubleElementResult")==0) return DoubleElementResultEnum;
+	else if (strcmp(name,"DoubleExternalResult")==0) return DoubleExternalResultEnum;
+	else if (strcmp(name,"DoubleMatExternalResult")==0) return DoubleMatExternalResultEnum;
+	else if (strcmp(name,"DoubleVecExternalResult")==0) return DoubleVecExternalResultEnum;
+	else if (strcmp(name,"IntExternalResult")==0) return IntExternalResultEnum;
+	else if (strcmp(name,"J")==0) return JEnum;
+	else if (strcmp(name,"Patch")==0) return PatchEnum;
+	else if (strcmp(name,"PatchNodes")==0) return PatchNodesEnum;
+	else if (strcmp(name,"PatchVertices")==0) return PatchVerticesEnum;
+	else if (strcmp(name,"PentaP1ElementResult")==0) return PentaP1ElementResultEnum;
+	else if (strcmp(name,"PetscVecExternalResult")==0) return PetscVecExternalResultEnum;
+	else if (strcmp(name,"StringExternalResult")==0) return StringExternalResultEnum;
+	else if (strcmp(name,"Time")==0) return TimeEnum;
+	else if (strcmp(name,"TriaP1ElementResult")==0) return TriaP1ElementResultEnum;
+	else if (strcmp(name,"WaterColumnOld")==0) return WaterColumnOldEnum;
+	else if (strcmp(name,"MinVel")==0) return MinVelEnum;
+	else if (strcmp(name,"MaxVel")==0) return MaxVelEnum;
+	else if (strcmp(name,"MinVx")==0) return MinVxEnum;
+	else if (strcmp(name,"MaxVx")==0) return MaxVxEnum;
+	else if (strcmp(name,"MaxAbsVx")==0) return MaxAbsVxEnum;
+	else if (strcmp(name,"MinVy")==0) return MinVyEnum;
+	else if (strcmp(name,"MaxVy")==0) return MaxVyEnum;
+	else if (strcmp(name,"MaxAbsVy")==0) return MaxAbsVyEnum;
+	else if (strcmp(name,"MinVz")==0) return MinVzEnum;
+	else if (strcmp(name,"MaxVz")==0) return MaxVzEnum;
+	else if (strcmp(name,"MaxAbsVz")==0) return MaxAbsVzEnum;
+	else if (strcmp(name,"Relative")==0) return RelativeEnum;
+	else if (strcmp(name,"Absolute")==0) return AbsoluteEnum;
+	else if (strcmp(name,"Incremental")==0) return IncrementalEnum;
+	else if (strcmp(name,"AgressiveMigration")==0) return AgressiveMigrationEnum;
+	else if (strcmp(name,"None")==0) return NoneEnum;
+	else if (strcmp(name,"SoftMigration")==0) return SoftMigrationEnum;
+	else if (strcmp(name,"StokesSolver")==0) return StokesSolverEnum;
+	else if (strcmp(name,"Adjoint")==0) return AdjointEnum;
+	else if (strcmp(name,"Colinear")==0) return ColinearEnum;
+	else if (strcmp(name,"ControlSteady")==0) return ControlSteadyEnum;
+	else if (strcmp(name,"Fset")==0) return FsetEnum;
+	else if (strcmp(name,"Gradient1")==0) return Gradient1Enum;
+	else if (strcmp(name,"Gradient2")==0) return Gradient2Enum;
+	else if (strcmp(name,"Gradient3")==0) return Gradient3Enum;
+	else if (strcmp(name,"Gradient")==0) return GradientEnum;
+	else if (strcmp(name,"GroundinglineMigration")==0) return GroundinglineMigrationEnum;
+	else if (strcmp(name,"Gset")==0) return GsetEnum;
+	else if (strcmp(name,"Index")==0) return IndexEnum;
+	else if (strcmp(name,"Indexed")==0) return IndexedEnum;
+	else if (strcmp(name,"Intersect")==0) return IntersectEnum;
+	else if (strcmp(name,"Nodal")==0) return NodalEnum;
+	else if (strcmp(name,"OldGradient")==0) return OldGradientEnum;
+	else if (strcmp(name,"OutputFilePointer")==0) return OutputFilePointerEnum;
+	else if (strcmp(name,"PetscOptionsAnalyses")==0) return PetscOptionsAnalysesEnum;
+	else if (strcmp(name,"PetscOptionsStrings")==0) return PetscOptionsStringsEnum;
+	else if (strcmp(name,"QmuErrName")==0) return QmuErrNameEnum;
+	else if (strcmp(name,"QmuInName")==0) return QmuInNameEnum;
+	else if (strcmp(name,"QmuOutName")==0) return QmuOutNameEnum;
+	else if (strcmp(name,"Regular")==0) return RegularEnum;
+	else if (strcmp(name,"Scaled")==0) return ScaledEnum;
+	else if (strcmp(name,"Separate")==0) return SeparateEnum;
+	else if (strcmp(name,"Sset")==0) return SsetEnum;
+	else if (strcmp(name,"Verbose")==0) return VerboseEnum;
+	else if (strcmp(name,"TriangleInterp")==0) return TriangleInterpEnum;
+	else if (strcmp(name,"BilinearInterp")==0) return BilinearInterpEnum;
+	else if (strcmp(name,"NearestInterp")==0) return NearestInterpEnum;
+	else if (strcmp(name,"XY")==0) return XYEnum;
+	else if (strcmp(name,"XYZP")==0) return XYZPEnum;
+	else if (strcmp(name,"Option")==0) return OptionEnum;
+	else if (strcmp(name,"OptionCell")==0) return OptionCellEnum;
+	else if (strcmp(name,"OptionChar")==0) return OptionCharEnum;
+	else if (strcmp(name,"OptionStruct")==0) return OptionStructEnum;
+	else if (strcmp(name,"OptionDouble")==0) return OptionDoubleEnum;
+	else if (strcmp(name,"OptionLogical")==0) return OptionLogicalEnum;
+	else if (strcmp(name,"Paterson")==0) return PatersonEnum;
+	else if (strcmp(name,"Arrhenius")==0) return ArrheniusEnum;
+	else _error_("Enum %s not found",name);
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/StringToEnumx/StringToEnumx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/StringToEnumx/StringToEnumx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/StringToEnumx/StringToEnumx.h	(revision 11330)
@@ -0,0 +1,10 @@
+/*
+ * \file StringToEnumx
+ * \brief: convert String to Enum
+ */
+
+#ifndef _STRING_TO_ENUMX_
+
+int StringToEnumx(const char* string_in);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file SurfaceAbsVelMisfitx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./SurfaceAbsVelMisfitx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void SurfaceAbsVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+
+	/*Intermediary*/
+	int i;
+	Element* element=NULL;
+
+	/*output: */
+	double J=0;
+	double J_sum;
+
+	/*Compute Misfit: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		J+=element->SurfaceAbsVelMisfit(process_units,weight_index);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  SurfaceAbsVelMisfitx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _SURFACEABSVELMISFITX_H
+#define _SURFACEABSVELMISFITX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void SurfaceAbsVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/SurfaceAreax/SurfaceAreax.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 11330)
@@ -0,0 +1,39 @@
+/*!\file SurfaceAreax
+ * \brief: compute Surface area
+ */
+
+#include "./SurfaceAreax.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../InputUpdateFromConstantx/InputUpdateFromConstantx.h"
+
+void SurfaceAreax( double* pS, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+	
+	/*Intermediary*/
+	Element* element=NULL;
+	int i;
+
+	/*output: */
+	double S=0;
+	double S_sum;
+	
+	/*Compute gradients: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		S+=element->SurfaceArea();
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	MPI_Reduce (&S,&S_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&S_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+	S=S_sum;
+
+	/*add surface area to element inputs:*/
+	InputUpdateFromConstantx(elements,nodes,vertices,loads,materials,parameters,S,SurfaceAreaEnum);
+
+	/*Assign output pointers: */
+	if(pS) *pS=S;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/SurfaceAreax/SurfaceAreax.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  SurfaceAreax.h
+ * \brief header file for ...
+ */ 
+
+#ifndef _SURFACEAREAX_H
+#define _SURFACEAREAX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void SurfaceAreax( double* pS, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+
+#endif  /* _SURFACEAREAX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 11330)
@@ -0,0 +1,39 @@
+/*!\file SurfaceAverageVelMisfitx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./SurfaceAverageVelMisfitx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../SurfaceAreax/SurfaceAreax.h"
+
+void SurfaceAverageVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+
+	/*Intermediary*/
+	int i;
+	Element* element=NULL;
+
+	/*output: */
+	double J=0;
+	double J_sum;
+
+	/*Compute surface area and add to elements inputs */
+	SurfaceAreax(NULL,elements,nodes,vertices, loads,materials,parameters);
+
+	/*Compute Misfit: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		J+=element->SurfaceAverageVelMisfit(process_units,weight_index);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  SurfaceAverageVelMisfitx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _SURFACEAVERAGEVELMISFITX_H
+#define _SURFACEAVERAGEVELMISFITX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void SurfaceAverageVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file SurfaceLogVelMisfitx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./SurfaceLogVelMisfitx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void SurfaceLogVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+
+	/*Intermediary*/
+	int i;
+	Element* element=NULL;
+
+	/*output: */
+	double J=0;
+	double J_sum;
+
+	/*Compute Misfit: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		J+=element->SurfaceLogVelMisfit(process_units,weight_index);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  SurfaceLogVelMisfitx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _SURFACELOGVELMISFITX_H
+#define _SURFACELOGVELMISFITX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void SurfaceLogVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file SurfaceLogVxVyMisfitx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./SurfaceLogVxVyMisfitx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void SurfaceLogVxVyMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+
+	/*Intermediary*/
+	int i;
+	Element* element=NULL;
+
+	/*output: */
+	double J=0;
+	double J_sum;
+
+	/*Compute Misfit: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		J+=element->SurfaceLogVxVyMisfit(process_units,weight_index);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  SurfaceLogVxVyMisfitx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _SURFACELOGVXVYMISFITX_H
+#define _SURFACELOGVXVYMISFITX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void SurfaceLogVxVyMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file SurfaceRelVelMisfitx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./SurfaceRelVelMisfitx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void SurfaceRelVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+
+	/*Intermediary*/
+	int i;
+	Element* element=NULL;
+
+	/*output: */
+	double J=0;
+	double J_sum;
+
+	/*Compute Misfit: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		J+=element->SurfaceRelVelMisfit(process_units,weight_index);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  SurfaceRelVelMisfitx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _SURFACERELVELMISFITX_H
+#define _SURFACERELVELMISFITX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void SurfaceRelVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/SystemMatricesx/SystemMatricesx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SystemMatricesx/SystemMatricesx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SystemMatricesx/SystemMatricesx.cpp	(revision 11330)
@@ -0,0 +1,149 @@
+/*!\file SystemMatricesx
+ * \brief: create system matrices (stiffness matrix, loads vector)
+ */
+
+#include "./SystemMatricesx.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void SystemMatricesx(Mat* pKff, Mat* pKfs, Vec* ppf, Vec* pdf, double* pkmax,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,bool kflag,bool pflag,bool penalty_kflag,bool penalty_pflag){
+	
+	/*intermediary: */
+	int      i,j;
+	int      fsize,ssize;
+	int      connectivity, numberofdofspernode;
+	int      analysis_type, configuration_type;
+	Element *element = NULL;
+	Load    *load    = NULL;
+	
+	/*output: */
+	Mat    Kff  = NULL;
+	Mat    Kfs  = NULL;
+	Vec    pf   = NULL;
+	Vec    df=NULL;
+	double kmax = 0;
+
+	/*Display message*/
+	_printf_(VerboseModule(),"   Generating matrices\n");
+
+	/*retrive parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	parameters->FindParam(&connectivity,MeshAverageVertexConnectivityEnum);
+
+	/*Get size of matrices: */
+	fsize=nodes->NumberOfDofs(configuration_type,FsetEnum);
+	ssize=nodes->NumberOfDofs(configuration_type,SsetEnum);
+
+	numberofdofspernode=nodes->MaxNumDofs(configuration_type,GsetEnum);
+
+	/*Checks in debugging mode {{{1*/
+	if(penalty_kflag)_assert_(kflag);
+	if(penalty_pflag)_assert_(pflag);
+	/*}}}*/
+
+	/*Compute penalty free mstiffness matrix and load vector*/
+	if(kflag){
+
+		Kff=NewMat(fsize,fsize,connectivity,numberofdofspernode);
+		Kfs=NewMat(fsize,ssize,connectivity,numberofdofspernode);
+		df=NewVec(fsize);
+
+		/*Fill stiffness matrix from elements: */
+		for (i=0;i<elements->Size();i++){
+			element=(Element*)elements->GetObjectByOffset(i);
+			element->CreateKMatrix(Kff,Kfs,df);
+		}
+
+		/*Fill stiffness matrix from loads if loads have the current configuration_type: */
+		for (i=0;i<loads->Size();i++){
+			load=(Load*)loads->GetObjectByOffset(i);
+			if (load->InAnalysis(configuration_type)) load->CreateKMatrix(Kff,Kfs);
+		}
+
+		/*Assemble matrix and doftypes and compress matrix to save memory: */
+		MatAssemblyBegin(Kff,MAT_FINAL_ASSEMBLY);
+		MatAssemblyEnd(Kff,MAT_FINAL_ASSEMBLY);
+		#if _PETSC_MAJOR_ == 2 
+		MatCompress(Kff);
+		#endif
+
+		MatAssemblyBegin(Kfs,MAT_FINAL_ASSEMBLY);
+		MatAssemblyEnd(Kfs,MAT_FINAL_ASSEMBLY);
+		#if _PETSC_MAJOR_ == 2 
+		MatCompress(Kfs);
+		#endif
+		VecAssemblyBegin(df);
+		VecAssemblyEnd(df);
+		
+	}
+	
+	if(pflag){
+
+		pf=NewVec(fsize);
+
+		/*Fill right hand side vector, from elements: */
+		for (i=0;i<elements->Size();i++){
+			element=(Element*)elements->GetObjectByOffset(i);
+			element->CreatePVector(pf);
+		}
+
+		/*Fill right hand side from loads if loads have the current configuration_type: */
+		for (i=0;i<loads->Size();i++){
+			load=(Load*)loads->GetObjectByOffset(i);
+			if (load->InAnalysis(configuration_type)) load->CreatePVector(pf);
+		}
+
+		VecAssemblyBegin(pf);
+		VecAssemblyEnd(pf);
+	}
+
+	/*Now, figure out maximum value of K_gg, so that we can penalize it correctly: */
+	MatNorm(Kff,NORM_INFINITY,&kmax);
+
+	/*Now, deal with penalties*/
+	if(penalty_kflag){
+
+		/*Fill stiffness matrix from loads: */
+		for (i=0;i<loads->Size();i++){
+			load=(Load*)loads->GetObjectByOffset(i);
+			if (load->InAnalysis(configuration_type)) load->PenaltyCreateKMatrix(Kff,Kfs,kmax);
+		}
+
+		/*Assemble matrix and compress matrix to save memory: */
+		MatAssemblyBegin(Kff,MAT_FINAL_ASSEMBLY);
+		MatAssemblyEnd(Kff,MAT_FINAL_ASSEMBLY);
+		#if _PETSC_MAJOR_ == 2 
+		MatCompress(Kff);
+		#endif
+
+		MatAssemblyBegin(Kfs,MAT_FINAL_ASSEMBLY);
+		MatAssemblyEnd(Kfs,MAT_FINAL_ASSEMBLY);
+		#if _PETSC_MAJOR_ == 2 
+		MatCompress(Kfs);
+		#endif
+	}
+
+	
+	if(penalty_pflag){
+
+		/*Fill right hand side vector, from loads: */
+		for (i=0;i<loads->Size();i++){
+			load=(Load*)loads->GetObjectByOffset(i);
+			if (load->InAnalysis(configuration_type)) load->PenaltyCreatePVector(pf,kmax);
+		}
+
+		VecAssemblyBegin(pf);
+		VecAssemblyEnd(pf);
+	}
+
+	/*Assign output pointers: */
+	if(pKff) *pKff=Kff;
+	if(pKfs) *pKfs=Kfs;
+	if(ppf)  *ppf=pf;
+	if(pdf)  *pdf=df;
+	if(pkmax) *pkmax=kmax;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/SystemMatricesx/SystemMatricesx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/SystemMatricesx/SystemMatricesx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/SystemMatricesx/SystemMatricesx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  SystemMatricesx.h
+ * \brief header file for degree of freedoms distribution routines.
+ */ 
+
+#ifndef _SYSTEMMATRICESX_H
+#define _SYSTEMMATRICESX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void SystemMatricesx(Mat* pKff, Mat* pKfs, Vec* ppf, Vec* pdf, double* pkmax,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,
+			bool kflag=true,bool pflag=true,bool penalty_kflag=true,bool penalty_pflag=true);
+
+#endif  /* _SYSTEMMATRICESX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file ThicknessAbsGradientx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./ThicknessAbsGradientx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void ThicknessAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+
+	/*Intermediary*/
+	int i;
+	Element* element=NULL;
+
+	/*output: */
+	double J=0;
+	double J_sum;
+
+	/*Compute Misfit: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		J+=element->ThicknessAbsGradient(process_units,weight_index);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  ThicknessAbsGradientx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _THICKNESSABSGRADIENT_H
+#define _THICKNESSABSGRADIENT_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void ThicknessAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file ThicknessAbsMisfitx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./ThicknessAbsMisfitx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void ThicknessAbsMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+
+	/*Intermediary*/
+	int i;
+	Element* element=NULL;
+
+	/*output: */
+	double J=0;
+	double J_sum;
+
+	/*Compute Misfit: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		J+=element->ThicknessAbsMisfit(process_units,weight_index);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  ThicknessAbsMisfitx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _THICKNESSABSMISFITX_H
+#define _THICKNESSABSMISFITX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void ThicknessAbsMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/TimeAdaptx/TimeAdaptx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/TimeAdaptx/TimeAdaptx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/TimeAdaptx/TimeAdaptx.cpp	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file TimeAdaptx
+*\brief: update time steps to respect CFL condition
+ */
+
+#include "./TimeAdaptx.h"
+#include "../modules.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../Container/Container.h"
+
+void TimeAdaptx(double* pdt, Elements* elements, Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials, Parameters* parameters){
+
+	int      i;
+
+	/*output: */
+	double   dt;
+
+	/*intermediary: */
+	Element *element     = NULL;
+	double   min_dt      = 0;
+	double   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=(Element*)elements->GetObjectByOffset(i);
+		dt=element->TimeAdapt();
+		if(dt<min_dt)min_dt=dt;
+	}
+
+	#ifdef _PARALLEL_
+	/*Figure out minimum across the cluster: */
+	MPI_Reduce (&min_dt,&node_min_dt,1,MPI_DOUBLE,MPI_MIN,0,MPI_COMM_WORLD );
+	MPI_Bcast(&node_min_dt,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	min_dt=node_min_dt;
+	#endif
+
+	/*Assign output pointers:*/
+	*pdt=min_dt;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/TimeAdaptx/TimeAdaptx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/TimeAdaptx/TimeAdaptx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/TimeAdaptx/TimeAdaptx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  TimeAdaptx.h
+ */ 
+
+#ifndef _TIMEADAPTX_H
+#define _TIMEADAPTX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void TimeAdaptx(double* pdt, Elements* elements, Nodes* nodes,Vertices* vertices,Loads* loads, Materials* materials, Parameters* parameters);
+
+#endif  /* _TIMEADAPTX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/TriaSearchx/TriaSearchx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/TriaSearchx/TriaSearchx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/TriaSearchx/TriaSearchx.cpp	(revision 11330)
@@ -0,0 +1,57 @@
+/*!\file TriaSearchx
+ */
+
+#include "./TriaSearchx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../objects/objects.h"
+#include "../modules.h"
+
+using namespace bamg;
+using namespace std;
+
+void TriaSearchx(double** ptria,double* index,int nel, double* x, double* y, int nods,double* x0, double* y0,int numberofnodes){
+
+	/*Output*/
+	double* tria=NULL;
+
+	/*allocate: */
+	tria=(double*)xmalloc(numberofnodes*sizeof(double));
+
+	/*Intermediary*/
+	R2     r;
+	I2     I;
+	int    i,j,k;
+	int    i0,i1,i2;
+	double areacoord[3];
+	double aa,bb;
+	double data_value;
+	Icoor2 dete[3];
+	int verbose=0;
+
+	// 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/trunk-jpl-damage/src/c/modules/TriaSearchx/TriaSearchx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/TriaSearchx/TriaSearchx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/TriaSearchx/TriaSearchx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  TriaSearchx.h
+ * \brief header file for Bamg module
+ */ 
+
+#ifndef _TRIASEARCHX_H
+#define _TRIASEARCHX_H
+
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void TriaSearchx(double** ptria,double* index,int nel, double* x, double* y, int nods,double* x0, double* y0,int numberofnodes);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.cpp	(revision 11330)
@@ -0,0 +1,32 @@
+/*!\file UpdateConstraintsx
+ * \brief: update constraints and nodes (especially degree of freedom distribution) at time t.
+ */
+
+#include "./UpdateConstraintsx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../modules/modules.h"
+#include "../../io/io.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void UpdateConstraintsx(Nodes* nodes,Constraints* constraints,Parameters* parameters){
+
+	double time;
+	int    analysis_type;
+
+	/*retrieve parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	parameters->FindParam(&time,TimeEnum);
+
+	/*start module: */
+	_printf_(VerboseModule(),"%s%g\n","   Updating constraints for time: ",time);
+	
+	/*First, update dof constraints in nodes, using constraints: */
+	SpcNodesx(nodes,constraints,parameters,analysis_type); 
+
+	/*Now, update degrees of freedoms: */
+	NodesDofx(nodes,parameters,analysis_type);
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  UpdateConstraintsx.h
+ * \brief header file for node and constraints update
+ */ 
+
+#ifndef _UPDATECONSTRAINTSX_H
+#define _UPDATECONSTRAINTSX_H
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+#include "../../toolkits/toolkits.h"
+
+/* local prototypes: */
+void UpdateConstraintsx(Nodes* nodes,Constraints* constraints,Parameters* parameters);
+
+#endif  /* _UPDATECONSTRAINTSX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 11330)
@@ -0,0 +1,37 @@
+/*!\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 "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void UpdateDynamicConstraintsx(Constraints* constraints,Nodes* nodes,Parameters* parameters,Vec yg){
+	
+	int configuration_type;
+	double* yg_serial=NULL;
+
+	/*Get current configuration*/
+	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	/*serialize yg, so nodes can index into it: */
+	VecToMPISerial(&yg_serial,yg);
+
+	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:*/
+	xfree((void**)&yg_serial);
+}
Index: /issm/trunk-jpl-damage/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  UpdateDynamicConstraintsx.h
+ * \brief header file for updating single point constraints  for next time step
+ */ 
+
+#ifndef _UPDATEDYNAMICCONSTRAINTSXX_H
+#define _UPDATEDYNAMICCONSTRAINTSXX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+void UpdateDynamicConstraintsx(Constraints* constraints,Nodes* nodes,Parameters* parameters,Vec yg);
+
+#endif  /* _UPDATESPCSX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/UpdateVertexPositionsx/UpdateVertexPositionsx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/UpdateVertexPositionsx/UpdateVertexPositionsx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/UpdateVertexPositionsx/UpdateVertexPositionsx.cpp	(revision 11330)
@@ -0,0 +1,45 @@
+/*!\file UpdateVertexPositionsx
+ * \brief update vertex positions using new geometry defined by new thickness and new bed.
+ */
+
+#include "./UpdateVertexPositionsx.h"
+#include "../modules.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+int UpdateVertexPositionsx(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters){
+
+	int     i;
+	Vec     vz        = NULL;
+	Vertex *vertex    = NULL;
+	double *thickness = NULL;
+	double *bed       = NULL;
+
+	/*get vertex vectors for bed and thickness: */
+	GetVectorFromInputsx(&thickness,elements,nodes, vertices, loads, materials, parameters, ThicknessEnum,VertexEnum);
+	GetVectorFromInputsx(&bed      ,elements,nodes, vertices, loads, materials, parameters, BedEnum,      VertexEnum);
+
+	/*Allocate vector*/
+	vz=NewVec(vertices->NumberOfVertices());
+
+	/*Update verices new geometry: */
+	for (i=0;i<vertices->Size();i++){
+		vertex=(Vertex*)vertices->GetObjectByOffset(i);
+		vertex->UpdatePosition(vz,parameters,thickness,bed);
+	}
+
+	/*Assemble mesh velocity*/
+	VecAssemblyBegin(vz);
+	VecAssemblyEnd(vz);
+
+	/*Update element inputs*/
+	InputUpdateFromVectorx(elements,nodes,vertices,loads,materials,parameters,vz,VzMeshEnum,VertexEnum);
+
+	/*Free ressources:*/
+	xfree((void**)&thickness);
+	xfree((void**)&bed);
+	VecFree(&vz);
+	return 1;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/UpdateVertexPositionsx/UpdateVertexPositionsx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/UpdateVertexPositionsx/UpdateVertexPositionsx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/UpdateVertexPositionsx/UpdateVertexPositionsx.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  UpdateVertexPositionsx.h
+ * \brief header file for updating node positions using new geometry defined by new thickness and new bed.
+ */ 
+
+#ifndef _UPDATEVERTEXPOSITIONSXX_H
+#define _UPDATEVERTEXPOSITIONSXX_H
+
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+int UpdateVertexPositionsx(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters);
+
+#endif  /* _UPDATEVERTEXPOSITIONSXX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/VecMergex/VecMergex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/VecMergex/VecMergex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/VecMergex/VecMergex.cpp	(revision 11330)
@@ -0,0 +1,48 @@
+/*!\file VecMergex
+ * \brief: merge one vector into another
+ */
+
+#include "./VecMergex.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void VecMergex(Vec ug, Vec uf, Nodes* nodes, Parameters* parameters, int SetEnum){
+
+	/*variables: */
+	int i;
+	int configuration_type;
+	double* uf_serial=NULL;
+
+	/*retrieve parameters: */
+	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	
+	/*serialize uf: */
+	VecToMPISerial(&uf_serial,uf);
+
+	/*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:*/
+	xfree((void**)&uf_serial);
+
+	/*Assemble vector: */
+	VecAssemblyBegin(ug);
+	VecAssemblyEnd(ug);
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/VecMergex/VecMergex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/VecMergex/VecMergex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/VecMergex/VecMergex.h	(revision 11330)
@@ -0,0 +1,14 @@
+/*!\file:  VecMergex.h
+ * \brief header file for merging one vector into another
+ */ 
+
+#ifndef _VECMERGEX_H
+#define _VECMERGEX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void VecMergex(Vec ug, Vec uf, Nodes* nodes, Parameters* parameters, int SetEnum);
+
+#endif  /* _VECMERGEX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/VerticesDofx/VerticesDofx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/VerticesDofx/VerticesDofx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/VerticesDofx/VerticesDofx.cpp	(revision 11330)
@@ -0,0 +1,33 @@
+/*!\file VerticesDofx
+ * \brief: establish degrees of freedom for all vertices: */
+
+#include "./VerticesDofx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void VerticesDofx( Vertices* vertices, Parameters* parameters) {
+
+	int i;
+
+	int  found=0;
+	extern int num_procs;
+	extern int my_rank;
+	
+	/*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 1 dof at a time. When a  vertex has already been distributed his dof on a cpu, 
+	 * all other cpus with the same vertex cannot distribute it anymore. Use clone field to be sure of that: */
+	vertices->DistributeDofs(numberofvertices,1); //only 1 dof per vertex.
+
+}
Index: /issm/trunk-jpl-damage/src/c/modules/VerticesDofx/VerticesDofx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/VerticesDofx/VerticesDofx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/VerticesDofx/VerticesDofx.h	(revision 11330)
@@ -0,0 +1,15 @@
+/*!\file:  VerticesDofx.h
+ * \brief header file for degree of freedoms distribution routines.
+ */ 
+
+#ifndef _VERTICESDOFX_H
+#define _VERTICESDOFX_H
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+
+/* local prototypes: */
+void VerticesDofx( Vertices* vertices, Parameters* parameters);
+
+#endif  /* _VERTICESDOFX_H */
+
Index: /issm/trunk-jpl-damage/src/c/modules/Xy2llx/Xy2llx.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Xy2llx/Xy2llx.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Xy2llx/Xy2llx.cpp	(revision 11330)
@@ -0,0 +1,136 @@
+/*!\file Xy2llx.cpp
+ */
+
+#include "./Xy2llx.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include <math.h>
+
+int Xy2llx(double* lat, double* lon, double* x, double* y, int ncoord, int sgn){
+/*  This is a cpp conversion of the following:
+%XY2LL - converts xy to lat long
+%
+%   Converts Polar  Stereographic (X,Y) coordinates for the polar regions to
+%   latitude and longitude Stereographic (X,Y) coordinates for the polar
+%   regions.
+%   Author: Michael P. Schodlok, December 2003 (map2xy.m)
+%
+%   Usage:
+%      [lat,lon] = xy2ll(x,y,sgn);
+%      [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel);
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+*/
+	double  central_meridian,standard_parallel;
+
+	Xy2lldef(&central_meridian,&standard_parallel,sgn);
+
+	return(Xy2llx(lat,lon,x,y,ncoord,sgn,central_meridian,standard_parallel));
+}
+
+int Xy2llx(double* lat, double* lon, double* x, double* y, int ncoord, int sgn, double central_meridian, double standard_parallel){
+/*  This is a cpp conversion of the following:
+%XY2LL - converts xy to lat long
+%
+%   Converts Polar  Stereographic (X,Y) coordinates for the polar regions to
+%   latitude and longitude Stereographic (X,Y) coordinates for the polar
+%   regions.
+%   Author: Michael P. Schodlok, December 2003 (map2xy.m)
+%
+%   Usage:
+%      [lat,lon] = xy2ll(x,y,sgn);
+%      [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel);
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+*/
+
+	int     i,iret=0;
+	double  delta,slat;
+	double  cde,re,ex2,ex;
+	double  sl,rho,cm,T,chi;
+
+	if((sgn!=1) && (sgn!=-1)) _error_("Sign should be either +1 or -1.\n");
+
+	delta = central_meridian;
+	slat  = standard_parallel;
+
+	/*  Conversion constant from degrees to radians  */
+	cde  = 57.29577951;
+	/*  Radius of the earth in meters  */
+	re   = 6378.273*pow(10.,3.);
+	/*  Eccentricity of the Hughes ellipsoid squared  */
+	ex2  = 0.006693883;
+	/*  Eccentricity of the Hughes ellipsoid  */
+	ex   =  sqrt(ex2);
+
+	/*  loop over all the coordinate pairs  */
+	for(i=0; i<ncoord; i++){
+		sl = slat*PI/180.;
+		cm = cos(sl)/sqrt(1.0-ex2*(pow(sin(sl),2.)));
+		rho= sqrt(pow(x[i],2.) + pow(y[i],2.));
+		T  = tan((PI/4.0) - (sl/2.0))/pow(((1.0-ex*sin(sl))/(1.0+ex*sin(sl))),(ex/2.0));
+
+		if(fabs(slat-90.) < 1.e-5)
+			T =rho*sqrt(pow((1.+ex),(1.+ex))*pow((1.-ex),(1.-ex)))/2./re;
+		else
+			T =rho*T/(re*cm);
+
+		chi = (PI / 2.0) - 2.0 * atan(T);
+		lat[i] = chi + ((ex2 / 2.0) + (5.0 * pow(ex2,2.0) / 24.0) + (pow(ex2,3.0) / 12.0)) *
+			   sin(2.0 * chi) + ((7.0 * pow(ex2,2.0) / 48.0) + (29.0 * pow(ex2,3.0) / 240.0)) *
+			   sin(4.0 * chi) + (7.0 * pow(ex2,3.0) / 120.0) * sin(6.0 * chi) ;
+
+		lat[i] = (double)sgn * lat[i];
+		lon[i] = atan2((double)sgn * x[i],-(double)sgn * y[i]);
+		lon[i] = (double)sgn * lon[i];
+
+		if(rho <= 0.1){
+			lat[i] = 90. * (double)sgn;
+			lon[i] = 0.0;
+			iret=1;
+		}
+
+		lon[i] = lon[i] * 180. / PI;
+		lat[i] = lat[i] * 180. / PI;
+		lon[i] = lon[i] - delta; 
+	}
+
+	return(iret);
+}
+
+void Xy2lldef(double* pdelta, double* pslat, int sgn){
+/*  This is a cpp conversion of the following:
+%XY2LL - converts xy to lat long
+%
+%   Converts Polar  Stereographic (X,Y) coordinates for the polar regions to
+%   latitude and longitude Stereographic (X,Y) coordinates for the polar
+%   regions.
+%   Author: Michael P. Schodlok, December 2003 (map2xy.m)
+%
+%   Usage:
+%      [lat,lon] = xy2ll(x,y,sgn);
+%      [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel);
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+*/
+	bool    flag=true;
+
+	/*  Get central_meridian and standard_parallel depending on hemisphere  */
+	if (sgn == 1) {
+		*pdelta= 45;
+		*pslat = 70;
+		_printf_(flag,"Warning: expecting coordinates in polar stereographic (Std Latitude: 70N Meridian: 45).\n");
+	}
+	else if (sgn == -1) {
+		*pdelta= 0;
+		*pslat = 71;
+		_printf_(flag,"Warning: expecting coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).\n");
+	}
+	else _error_("Sign should be either +1 or -1.\n");
+
+	return;
+}
Index: /issm/trunk-jpl-damage/src/c/modules/Xy2llx/Xy2llx.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/Xy2llx/Xy2llx.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/Xy2llx/Xy2llx.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  Xy2llx.h
+ * \brief header file for x/y to lat/long coordinate functions.
+ */ 
+
+#ifndef _XY2LLX_H
+#define _XY2LLX_H
+
+/* local prototypes: */
+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  /* _XY2LLX_H */
Index: /issm/trunk-jpl-damage/src/c/modules/modules.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/modules/modules.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/modules/modules.h	(revision 11330)
@@ -0,0 +1,118 @@
+/*! \file modules.h: 
+ *  \brief header file for all the ISSM modules
+ */
+
+#ifndef _ISSM_MODULES_H_
+#define _ISSM_MODULES_H_
+
+/*Modules: */
+#include "./AddExternalResultx/AddExternalResultx.h"
+#include "./AverageFilterx/AverageFilterx.h"
+#include "./AverageOntoPartitionx/AverageOntoPartitionx.h"
+#include "./Bamgx/Bamgx.h"
+#include "./BamgConvertMeshx/BamgConvertMeshx.h"
+#include "./BamgTriangulatex/BamgTriangulatex.h"
+#include "./Chacox/Chacox.h"
+#include "./ComputeBasalStressx/ComputeBasalStressx.h"
+#include "./ComputeStrainRatex/ComputeStrainRatex.h"
+#include "./ConfigureObjectsx/ConfigureObjectsx.h"
+#include "./ContourToMeshx/ContourToMeshx.h"
+#include "./ContourToNodesx/ContourToNodesx.h"
+#include "./ControlInputGetGradientx/ControlInputGetGradientx.h"
+#include "./ControlInputSetGradientx/ControlInputSetGradientx.h"
+#include "./ControlInputScaleGradientx/ControlInputScaleGradientx.h"
+#include "./CostFunctionx/CostFunctionx.h"
+#include "./CreateNodalConstraintsx/CreateNodalConstraintsx.h"
+#include "./DakotaResponsesx/DakotaResponsesx.h"
+#include "./DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h"
+#include "./ElementConnectivityx/ElementConnectivityx.h"
+#include "./EnumToStringx/EnumToStringx.h"
+#include "./StringToEnumx/StringToEnumx.h"
+#include "./GetSolutionFromInputsx/GetSolutionFromInputsx.h"
+#include "./GetVectorFromInputsx/GetVectorFromInputsx.h"
+#include "./Gradjx/Gradjx.h"
+#include "./GroundinglineMigrationx/GroundinglineMigrationx.h"
+#include "./HoleFillerx/HoleFillerx.h"
+#include "./IceVolumex/IceVolumex.h"
+#include "./InputControlUpdatex/InputControlUpdatex.h"
+#include "./InputConvergencex/InputConvergencex.h"
+#include "./InputDuplicatex/InputDuplicatex.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 "./InputToResultx/InputToResultx.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 "./InputArtificialNoisex/InputArtificialNoisex.h"
+#include "./IoModelToConstraintsx/IoModelToConstraintsx.h"
+#include "./KMLFileReadx/KMLFileReadx.h"
+#include "./KMLMeshWritex/KMLMeshWritex.h"
+#include "./KMLOverlayx/KMLOverlayx.h"
+#include "./Xy2llx/Xy2llx.h"
+#include "./Ll2xyx/Ll2xyx.h"
+#include "./Exp2Kmlx/Exp2Kmlx.h"
+#include "./Kml2Expx/Kml2Expx.h"
+#include "./Shp2Kmlx/Shp2Kmlx.h"
+#include "./MassFluxx/MassFluxx.h"
+#include "./MaxAbsVxx/MaxAbsVxx.h"
+#include "./MaxAbsVyx/MaxAbsVyx.h"
+#include "./MaxAbsVzx/MaxAbsVzx.h"
+#include "./MaxVelx/MaxVelx.h"
+#include "./ElementResponsex/ElementResponsex.h"
+#include "./MaxVxx/MaxVxx.h"
+#include "./MaxVyx/MaxVyx.h"
+#include "./MaxVzx/MaxVzx.h"
+#include "./Mergesolutionfromftogx/Mergesolutionfromftogx.h"
+#include "./MeshPartitionx/MeshPartitionx.h"
+#include "./MeshProfileIntersectionx/MeshProfileIntersectionx.h"
+#include "./MinVelx/MinVelx.h"
+#include "./MinVxx/MinVxx.h"
+#include "./MinVyx/MinVyx.h"
+#include "./MinVzx/MinVzx.h"
+#include "./SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h"
+#include "./SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h"
+#include "./SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h"
+#include "./SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h"
+#include "./SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h"
+#include "./ModelProcessorx/ModelProcessorx.h"
+#include "./ParsePetscOptionsx/ParsePetscOptionsx.h"
+#include "./NodalValuex/NodalValuex.h"
+#include "./NodeConnectivityx/NodeConnectivityx.h"
+#include "./NodesDofx/NodesDofx.h"
+#include "./Orthx/Orthx.h"
+#include "./OutputResultsx/OutputResultsx.h"
+#include "./ConstraintsStatex/ConstraintsStatex.h"
+#include "./PointCloudFindNeighborsx/PointCloudFindNeighborsx.h"
+#include "./PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h"
+#include "./Dakotax/Dakotax.h"
+#include "./Reduceloadx/Reduceloadx.h"
+#include "./Reducevectorgtosx/Reducevectorgtosx.h"
+#include "./Reducevectorgtofx/Reducevectorgtofx.h"
+#include "./RequestedOutputsx/RequestedOutputsx.h"
+#include "./ResetConstraintsx/ResetConstraintsx.h"
+#include "./ResetCoordinateSystemx/ResetCoordinateSystemx.h"
+#include "./Responsex/Responsex.h"
+#include "./RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h"
+#include "./Scotchx/Scotchx.h"
+#include "./Solverx/Solverx.h"
+#include "./SpcNodesx/SpcNodesx.h"
+#include "./SurfaceAreax/SurfaceAreax.h"
+#include "./SystemMatricesx/SystemMatricesx.h"
+#include "./TimeAdaptx/TimeAdaptx.h"
+#include "./TriaSearchx/TriaSearchx.h"
+#include "./ThicknessAbsMisfitx/ThicknessAbsMisfitx.h"
+#include "./ThicknessAbsGradientx/ThicknessAbsGradientx.h"
+#include "./UpdateVertexPositionsx/UpdateVertexPositionsx.h"
+#include "./UpdateConstraintsx/UpdateConstraintsx.h"
+#include "./UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h"
+#include "./VerticesDofx/VerticesDofx.h"
+#include "./VecMergex/VecMergex.h"
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/AdjacentTriangle.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/AdjacentTriangle.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/AdjacentTriangle.cpp	(revision 11330)
@@ -0,0 +1,76 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "AdjacentTriangle.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+
+	/*Constructors/Destructors*/
+	//See header file
+
+	/*Methods*/
+	/*FUNCTION AdjacentTriangle::Locked {{{1*/
+	int  AdjacentTriangle::Locked() const {
+		return t->AdjEdgeIndex[a] & 4;
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::MarkUnSwap {{{1*/
+	int  AdjacentTriangle::MarkUnSwap() const {
+		return t->AdjEdgeIndex[a] & 8;
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::GetAllFlag_UnSwap {{{1*/
+	int  AdjacentTriangle::GetAllFlag_UnSwap() const {
+		// take all flag except MarkUnSwap
+		return t->AdjEdgeIndex[a] & 1012;
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::SetLock {{{1*/
+	void AdjacentTriangle::SetLock(){
+		t->SetLocked(a);
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::Adj {{{1*/
+	AdjacentTriangle AdjacentTriangle::Adj() const {
+		return  t->Adj(a);
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::EdgeVertex {{{1*/
+	BamgVertex* AdjacentTriangle::EdgeVertex(const int & i) const {
+		return t->vertices[VerticesOfTriangularEdge[a][i]];
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::OppositeVertex {{{1*/
+	BamgVertex* AdjacentTriangle::OppositeVertex() const {
+		return t->vertices[bamg::OppositeVertex[a]]; 
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::det {{{1*/
+	Icoor2 & AdjacentTriangle::det() const {
+		return t->det;
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::swap {{{1*/
+	int AdjacentTriangle::swap(){
+		return  t->swap(a);
+	}
+	/*}}}*/
+	/*FUNCTION AdjacentTriangle::SetAdj2 {{{1*/
+	void AdjacentTriangle::SetAdj2(const AdjacentTriangle & ta, int l  ){
+		//set Adjacent Triangle of a triangle
+		if(t) {
+			t->adj[a]=ta.t;
+			t->AdjEdgeIndex[a]=ta.a|l;
+		}
+		if(ta.t) {
+			ta.t->adj[ta.a] = t ;
+			ta.t->AdjEdgeIndex[ta.a] = a| l ;
+		}
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/AdjacentTriangle.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/AdjacentTriangle.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/AdjacentTriangle.h	(revision 11330)
@@ -0,0 +1,46 @@
+#ifndef _TRIANGLEADJACENT_H_
+#define _TRIANGLEADJACENT_H_
+
+#include "./include.h"
+#include "./BamgVertex.h"
+
+namespace bamg {
+
+	//classes
+	class Triangle;
+	class Triangle;
+
+	class AdjacentTriangle {
+
+		public:
+			Triangle* t; //pointer toward the triangle
+			int  a;      //Edge number
+
+			//Constructors
+			AdjacentTriangle():a(0),t(NULL) {};
+			AdjacentTriangle(Triangle* tt,int  aa): t(tt),a(aa &3) {};
+
+			//Operators
+			operator Triangle * () const {return t;}
+			operator Triangle & () const {return *t;}
+			operator int() const {return a;}
+			AdjacentTriangle & operator++(){ a= NextEdge[a]; return *this; }
+			AdjacentTriangle operator--(){ a= PreviousEdge[a]; return *this; }
+
+			//Methods
+
+			//Methods
+			int  Locked() const;
+			int  MarkUnSwap() const;
+			int  GetAllFlag_UnSwap() const;
+			void SetLock();
+			void SetAdj2(const AdjacentTriangle &ta, int l=0);
+			int  swap();
+			AdjacentTriangle Adj() const;
+			BamgVertex* EdgeVertex(const int & i) const;
+			BamgVertex* OppositeVertex() const;
+			Icoor2& det() const;
+	};
+}
+#endif
+
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgGeom.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgGeom.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgGeom.cpp	(revision 11330)
@@ -0,0 +1,124 @@
+#include <stdio.h>
+#include "../objects.h"
+#include "../../io/io.h"
+
+/*Constructors/Destructors*/
+/*FUNCTION BamgGeom::BamgGeom(){{{1*/
+BamgGeom::BamgGeom(){
+
+	this->VerticesSize[0]=0,          this->VerticesSize[1]=0;          this->Vertices=NULL;
+	this->EdgesSize[0]=0,             this->EdgesSize[1]=0;             this->Edges=NULL;
+	this->TangentAtEdgesSize[0]=0,    this->TangentAtEdgesSize[1]=0;    this->TangentAtEdges=NULL;
+	this->CornersSize[0]=0,           this->CornersSize[1]=0;           this->Corners=NULL;
+	this->RequiredVerticesSize[0]=0,  this->RequiredVerticesSize[1]=0;  this->RequiredVertices=NULL;
+	this->RequiredEdgesSize[0]=0,     this->RequiredEdgesSize[1]=0;     this->RequiredEdges=NULL;
+	this->CrackedEdgesSize[0]=0,      this->CrackedEdgesSize[1]=0;      this->CrackedEdges=NULL;
+	this->SubDomainsSize[0]=0,        this->SubDomainsSize[1]=0;        this->SubDomains=NULL;
+
+}
+/*}}}*/
+/*FUNCTION BamgGeom::BamgGeom(mxArray* matlab_struct){{{1*/
+#ifdef _SERIAL_
+BamgGeom::BamgGeom(mxArray* matlab_struct){
+
+	FetchMatlabData(&this->Vertices,        &this->VerticesSize[0],        &this->VerticesSize[1],        mxGetAssignedField(matlab_struct,0,"Vertices"));
+	FetchMatlabData(&this->Edges,           &this->EdgesSize[0],           &this->EdgesSize[1],           mxGetAssignedField(matlab_struct,0,"Edges"));
+	this->TangentAtEdgesSize[0]=0,    this->TangentAtEdgesSize[1]=0;    this->TangentAtEdges=NULL;
+	FetchMatlabData(&this->Corners,         &this->CornersSize[0],         &this->CornersSize[1],         mxGetAssignedField(matlab_struct,0,"Corners"));
+	FetchMatlabData(&this->RequiredVertices,&this->RequiredVerticesSize[0],&this->RequiredVerticesSize[1],mxGetAssignedField(matlab_struct,0,"RequiredVertices"));
+	FetchMatlabData(&this->RequiredEdges,   &this->RequiredEdgesSize[0],   &this->RequiredEdgesSize[1],   mxGetAssignedField(matlab_struct,0,"RequiredEdges"));
+	FetchMatlabData(&this->CrackedEdges,    &this->CrackedEdgesSize[0],    &this->CrackedEdgesSize[1],    mxGetAssignedField(matlab_struct,0,"CrackedEdges"));
+	FetchMatlabData(&this->SubDomains,      &this->SubDomainsSize[0],      &this->SubDomainsSize[1],      mxGetAssignedField(matlab_struct,0,"SubDomains"));
+
+}
+#endif
+/*}}}*/
+/*FUNCTION BamgGeom::~BamgGeom(){{{1*/
+BamgGeom::~BamgGeom(){
+
+	xfree((void**)&this->Vertices);
+	xfree((void**)&this->Edges);
+	xfree((void**)&this->TangentAtEdges);
+	xfree((void**)&this->Corners);
+	xfree((void**)&this->RequiredVertices);
+	xfree((void**)&this->RequiredEdges);
+	xfree((void**)&this->CrackedEdges);
+	xfree((void**)&this->SubDomains);
+
+}
+/*}}}*/
+
+/*Methods*/
+/*FUNCTION BamgGeom::SetMatlabStructureFields{{{1*/
+#ifdef _SERIAL_
+void BamgGeom::SetMatlabStructureFields(mxArray** matlab_struct){
+
+	/*Intermediary*/
+	int         i;
+	mxArray*    output=NULL;
+	const int         numfields=7;
+	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++] = "RequiredVertices";
+	fnames[i++] = "RequiredEdges";
+	fnames[i++] = "CrackedEdges";
+	fnames[i++] = "SubDomains";
+	_assert_(i==numfields);
+
+	/*Initialize Matlab structure*/
+	output=mxCreateStructArray(ndim,dimensions,numfields,fnames);
+
+	/*set each matlab each field*/
+	i=0;
+	i++; SetMatlabStructureField(output,"Vertices",        this->VerticesSize[0],        this->VerticesSize[1],        this->Vertices);
+	i++; SetMatlabStructureField(output,"Edges",           this->EdgesSize[0],           this->EdgesSize[1],           this->Edges);
+	i++; SetMatlabStructureField(output,"TangentAtEdges",  this->TangentAtEdgesSize[0],  this->TangentAtEdgesSize[1],  this->TangentAtEdges);
+	i++; SetMatlabStructureField(output,"RequiredVertices",this->RequiredVerticesSize[0],this->RequiredVerticesSize[1],this->RequiredVertices);
+	i++; SetMatlabStructureField(output,"RequiredEdges",   this->RequiredEdgesSize[0],   this->RequiredEdgesSize[1],   this->RequiredEdges);
+	i++; SetMatlabStructureField(output,"CrackedEdges",    this->CrackedEdgesSize[0],    this->CrackedEdgesSize[1],    this->CrackedEdges);
+	i++; SetMatlabStructureField(output,"SubDomains",      this->SubDomainsSize[0],      this->SubDomainsSize[1],      this->SubDomains);
+	_assert_(i==numfields);
+
+	/*Assign output*/
+	*matlab_struct=output;
+
+}
+#endif
+/*}}}*/
+/*FUNCTION BamgGeom::SetMatlabStructureField{{{1*/
+#ifdef _SERIAL_
+void BamgGeom::SetMatlabStructureField(mxArray* matlab_struct,const char* fieldname,int fieldrows,int fieldcols,double* fieldpointer){
+
+	/*Intermediary*/
+	int         i1,i2;
+	mxArray*    pfield=NULL;
+	mxArray*    pfield2=NULL;
+
+	/*Copy field*/
+	double*  fieldcopy=NULL;
+	if (fieldrows*fieldcols){
+		fieldcopy=(double*)xmalloc(fieldrows*fieldcols*sizeof(double));
+		for(i1=0;i1<fieldrows;i1++){
+			for(i2=0;i2<fieldcols;i2++){
+				fieldcopy[fieldcols*i1+i2]=fieldpointer[fieldcols*i1+i2];
+			}
+		}
+	}
+
+	/*Set matlab field*/
+	pfield=mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pfield,fieldcols);
+	mxSetN(pfield,fieldrows);
+	mxSetPr(pfield,fieldcopy);
+	mexCallMATLAB(1,&pfield2,1,&pfield,"transpose");//transpose
+	mxSetField(matlab_struct,0,fieldname,pfield2);
+}
+#endif
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgGeom.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgGeom.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgGeom.h	(revision 11330)
@@ -0,0 +1,43 @@
+/*!\file:  BamgGeom.h
+ */ 
+
+#ifndef _BAMGGEOM_H_
+#define _BAMGGEOM_H_
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+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();
+		#ifdef _SERIAL_
+		BamgGeom(mxArray* matlab_struct);
+		#endif
+		~BamgGeom();
+
+		#ifdef _SERIAL_
+		void SetMatlabStructureFields(mxArray** matlab_struct);
+		void SetMatlabStructureField(mxArray* matlab_struct,const char* fieldname,int fieldrows,int fieldcols,double* fieldpointer);
+		#endif
+};
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgMesh.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgMesh.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgMesh.cpp	(revision 11330)
@@ -0,0 +1,182 @@
+#include <stdio.h>
+#include "../objects.h"
+#include "../../io/io.h"
+
+/*Constructors/Destructors*/
+/*FUNCTION BamgMesh::BamgMesh(){{{1*/
+BamgMesh::BamgMesh(){
+
+	this->VerticesSize[0]=0,                  this->VerticesSize[1]=0;                 this->Vertices=NULL;
+	this->EdgesSize[0]=0,                     this->EdgesSize[1]=0;                    this->Edges=NULL;
+	this->TrianglesSize[0]=0,                 this->TrianglesSize[1]=0;                this->Triangles=NULL;
+	this->QuadrilateralsSize[0]=0,            this->QuadrilateralsSize[1]=0;           this->Quadrilaterals=NULL;
+
+	this->SubDomainsSize[0]=0,                this->SubDomainsSize[1]=0;               this->SubDomains=NULL;
+	this->SubDomainsFromGeomSize[0]=0,        this->SubDomainsFromGeomSize[1]=0;       this->SubDomainsFromGeom=NULL;
+	this->CrackedVerticesSize[0]=0,           this->CrackedVerticesSize[1]=0;          this->CrackedVertices=NULL;
+	this->CrackedEdgesSize[0]=0,              this->CrackedEdgesSize[1]=0;             this->CrackedEdges=NULL;
+
+	this->VerticesOnGeomVertexSize[0]=0, this->VerticesOnGeomVertexSize[1]=0;this->VerticesOnGeomVertex=NULL;
+	this->VerticesOnGeomEdgeSize[0]=0,   this->VerticesOnGeomEdgeSize[1]=0;  this->VerticesOnGeomEdge=NULL;
+	this->EdgesOnGeomEdgeSize[0]=0,      this->EdgesOnGeomEdgeSize[1]=0;     this->EdgesOnGeomEdge=NULL;
+
+	this->IssmEdgesSize[0]=0,                 this->IssmEdgesSize[1]=0;                this->IssmEdges=NULL;
+	this->IssmSegmentsSize[0]=0,              this->IssmSegmentsSize[1]=0;             this->IssmSegments=NULL;
+
+	this->ElementConnectivitySize[0]=0,       this->ElementConnectivitySize[1]=0;      this->ElementConnectivity=NULL;
+	this->NodalConnectivitySize[0]=0,         this->NodalConnectivitySize[1]=0;        this->NodalConnectivity=NULL;
+	this->NodalElementConnectivitySize[0]=0,  this->NodalElementConnectivitySize[1]=0; this->NodalElementConnectivity=NULL;
+
+
+}
+/*}}}*/
+/*FUNCTION BamgMesh::BamgMesh(mxArray* matlab_struct){{{1*/
+#ifdef _SERIAL_
+BamgMesh::BamgMesh(mxArray* matlab_struct){
+
+	int lines,cols;
+
+	FetchMatlabData(&this->Vertices,            &this->VerticesSize[0],            &this->VerticesSize[1],            mxGetAssignedField(matlab_struct,0,"Vertices"));
+	FetchMatlabData(&this->Edges,               &this->EdgesSize[0],               &this->EdgesSize[1],               mxGetAssignedField(matlab_struct,0,"Edges"));
+	FetchMatlabData(&this->Triangles,           &this->TrianglesSize[0],           &this->TrianglesSize[1],           mxGetAssignedField(matlab_struct,0,"Triangles"));
+	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;
+	FetchMatlabData(&this->CrackedEdges,        &this->CrackedEdgesSize[0],        &this->CrackedEdgesSize[1],        mxGetAssignedField(matlab_struct,0,"CrackedEdges"));
+
+	FetchMatlabData(&this->VerticesOnGeomEdge,  &this->VerticesOnGeomEdgeSize[0],  &this->VerticesOnGeomEdgeSize[1],  mxGetAssignedField(matlab_struct,0,"VerticesOnGeomEdge"));
+	FetchMatlabData(&this->VerticesOnGeomVertex,&this->VerticesOnGeomVertexSize[0],&this->VerticesOnGeomVertexSize[1],mxGetAssignedField(matlab_struct,0,"VerticesOnGeomVertex"));
+	FetchMatlabData(&this->EdgesOnGeomEdge,     &this->EdgesOnGeomEdgeSize[0],     &this->EdgesOnGeomEdgeSize[1],     mxGetAssignedField(matlab_struct,0,"EdgesOnGeomEdge"));
+
+	this->IssmEdgesSize[0]=0,             this->IssmEdgesSize[1]=0;          this->IssmEdges=NULL;
+	FetchMatlabData(&this->IssmSegments,        &this->IssmSegmentsSize[0],        &this->IssmSegmentsSize[1],        mxGetAssignedField(matlab_struct,0,"IssmSegments"));
+
+	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;
+
+}
+#endif
+/*}}}*/
+/*FUNCTION BamgMesh::~BamgMesh(){{{1*/
+BamgMesh::~BamgMesh(){
+
+	xfree((void**)&this->Vertices);
+	xfree((void**)&this->Edges);
+	xfree((void**)&this->Triangles);
+	xfree((void**)&this->Quadrilaterals);
+
+	xfree((void**)&this->SubDomains);
+	xfree((void**)&this->SubDomainsFromGeom);
+	xfree((void**)&this->CrackedVertices);
+	xfree((void**)&this->CrackedEdges);
+
+	xfree((void**)&this->VerticesOnGeomVertex);
+	xfree((void**)&this->VerticesOnGeomEdge);
+	xfree((void**)&this->EdgesOnGeomEdge);
+
+	xfree((void**)&this->IssmEdges);
+	xfree((void**)&this->IssmSegments);
+
+	xfree((void**)&this->ElementConnectivity);
+	xfree((void**)&this->NodalConnectivity);
+	xfree((void**)&this->NodalElementConnectivity);
+
+
+}
+/*}}}*/
+
+/*Methods*/
+/*FUNCTION BamgMesh::SetMatlabStructureFields{{{1*/
+#ifdef _SERIAL_
+void BamgMesh::SetMatlabStructureFields(mxArray** matlab_struct){
+
+	/*Intermediary*/
+	int         i;
+	mxArray*    output=NULL;
+	const int         numfields=16;
+	const char* fnames[numfields];
+	mwSize      ndim=2;
+	mwSize      dimensions[2]={1,1};
+
+	/*Initialize field names*/
+	i=0;
+	fnames[i++] = "Triangles";
+	fnames[i++] = "Vertices";
+	fnames[i++] = "Edges";
+	fnames[i++] = "IssmSegments";
+	fnames[i++] = "IssmEdges";
+	fnames[i++] = "Quadrilaterals";
+	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*/
+	output=mxCreateStructArray(ndim,dimensions,numfields,fnames);
+
+	/*set each matlab each field*/
+	i=0;
+	i++; SetMatlabStructureField(output,"Triangles",                this->TrianglesSize[0],                this->TrianglesSize[1],                 this->Triangles);
+	i++; SetMatlabStructureField(output,"Vertices",                 this->VerticesSize[0],                 this->VerticesSize[1],                  this->Vertices);
+	i++; SetMatlabStructureField(output,"Edges",                    this->EdgesSize[0],                    this->EdgesSize[1],                     this->Edges);
+	i++; SetMatlabStructureField(output,"IssmSegments",             this->IssmSegmentsSize[0],             this->IssmSegmentsSize[1],              this->IssmSegments);
+	i++; SetMatlabStructureField(output,"IssmEdges",                this->IssmEdgesSize[0],                this->IssmEdgesSize[1],                 this->IssmEdges);
+	i++; SetMatlabStructureField(output,"Quadrilaterals",           this->QuadrilateralsSize[0],           this->QuadrilateralsSize[1],            this->Quadrilaterals);
+	i++; SetMatlabStructureField(output,"VerticesOnGeomVertex",this->VerticesOnGeomVertexSize[0],this->VerticesOnGeomVertexSize[1], this->VerticesOnGeomVertex);
+	i++; SetMatlabStructureField(output,"VerticesOnGeomEdge",  this->VerticesOnGeomEdgeSize[0],  this->VerticesOnGeomEdgeSize[1],   this->VerticesOnGeomEdge);
+	i++; SetMatlabStructureField(output,"EdgesOnGeomEdge",     this->EdgesOnGeomEdgeSize[0],     this->EdgesOnGeomEdgeSize[1],      this->EdgesOnGeomEdge);
+	i++; SetMatlabStructureField(output,"SubDomains",               this->SubDomainsSize[0],               this->SubDomainsSize[1],                this->SubDomains);
+	i++; SetMatlabStructureField(output,"SubDomainsFromGeom",       this->SubDomainsFromGeomSize[0],       this->SubDomainsFromGeomSize[1],        this->SubDomainsFromGeom);
+	i++; SetMatlabStructureField(output,"ElementConnectivity",      this->ElementConnectivitySize[0],      this->ElementConnectivitySize[1],       this->ElementConnectivity);
+	i++; SetMatlabStructureField(output,"NodalConnectivity",        this->NodalConnectivitySize[0],        this->NodalConnectivitySize[1],         this->NodalConnectivity);
+	i++; SetMatlabStructureField(output,"NodalElementConnectivity", this->NodalElementConnectivitySize[0], this->NodalElementConnectivitySize[1],  this->NodalElementConnectivity);
+	i++; SetMatlabStructureField(output,"CrackedVertices",          this->CrackedVerticesSize[0],          this->CrackedVerticesSize[1],           this->CrackedVertices);
+	i++; SetMatlabStructureField(output,"CrackedEdges",             this->CrackedEdgesSize[0],             this->CrackedEdgesSize[1],              this->CrackedEdges);
+	_assert_(i==numfields);
+
+	/*Assign output*/
+	*matlab_struct=output;
+
+}
+#endif
+/*}}}*/
+/*FUNCTION BamgMesh::SetMatlabStructureField{{{1*/
+#ifdef _SERIAL_
+void BamgMesh::SetMatlabStructureField(mxArray* matlab_struct,const char* fieldname,int fieldrows,int fieldcols,double* fieldpointer){
+
+	/*Intermediary*/
+	int         i1,i2;
+	mxArray*    pfield=NULL;
+	mxArray*    pfield2=NULL;
+
+	/*Copy field*/
+	double*  fieldcopy=NULL;
+	if (fieldrows*fieldcols){
+		fieldcopy=(double*)xmalloc(fieldrows*fieldcols*sizeof(double));
+		for(i1=0;i1<fieldrows;i1++){
+			for(i2=0;i2<fieldcols;i2++){
+				fieldcopy[fieldcols*i1+i2]=fieldpointer[fieldcols*i1+i2];
+			}
+		}
+	}
+
+	/*Set matlab field*/
+	pfield=mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pfield,fieldcols);
+	mxSetN(pfield,fieldrows);
+	mxSetPr(pfield,fieldcopy);
+	mexCallMATLAB(1,&pfield2,1,&pfield,"transpose");//transpose
+	mxSetField(matlab_struct,0,fieldname,pfield2);
+}
+#endif
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgMesh.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgMesh.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgMesh.h	(revision 11330)
@@ -0,0 +1,65 @@
+/*!\file:  BamgMesh.h
+ */ 
+
+#ifndef _BAMGMESH_H_
+#define _BAMGMESH_H_
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+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();
+		#ifdef _SERIAL_
+		BamgMesh(mxArray* matlab_struct);
+		#endif
+		~BamgMesh();
+
+		#ifdef _SERIAL_
+		void SetMatlabStructureFields(mxArray** matlab_struct);
+		void SetMatlabStructureField(mxArray* matlab_struct,const char* fieldname,int fieldrows,int fieldcols,double* fieldpointer);
+		#endif
+
+};
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgOpts.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgOpts.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgOpts.cpp	(revision 11330)
@@ -0,0 +1,129 @@
+#include <stdio.h>
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../objects.h"
+#include "../../io/io.h"
+
+/*Constructors/Destructors*/
+/*FUNCTION BamgOpts::BamgOpts() {{{1*/
+BamgOpts::BamgOpts(){
+
+	this->anisomax=0;
+	this->cutoff=0;
+	this->coeff=0;
+	this->errg=0;
+	this->gradation=0;
+	this->Hessiantype=0;
+	this->MaxCornerAngle=0;
+	this->maxnbv=0;
+	this->maxsubdiv=0;
+	this->Metrictype=0;
+	this->nbjacobi=0;
+	this->nbsmooth=0;
+	this->omega=0;
+	this->power=0;
+	this->verbose=0;
+
+	this->Crack=0;
+	this->geometricalmetric=0;
+	this->KeepVertices=0;
+	this->splitcorners=0;
+
+	this->hmin=0;
+	this->hmax=0;
+	this->hminVertices=NULL; this->hminVerticesSize[0]=this->hminVerticesSize[1]=0;
+	this->hmaxVertices=NULL; this->hmaxVerticesSize[0]=this->hmaxVerticesSize[1]=0;
+	this->hVertices=NULL;    this->hVerticesSize[0]=this->hVerticesSize[1]=0;
+	this->metric=NULL;       this->metricSize[0]=this->metricSize[1]=0;
+	this->field=NULL;        this->fieldSize[0]=this->fieldSize[1]=0;
+	this->err=NULL;          this->errSize[0]=this->errSize[1]=0;
+
+}
+/*}}}*/
+/*FUNCTION BamgOpts::BamgOpts(mxArray* matlab_struct){{{1*/
+#ifdef _SERIAL_
+BamgOpts::BamgOpts(mxArray* matlab_struct){
+
+	FetchMatlabData(&this->anisomax,mxGetField(matlab_struct,0,"anisomax"));
+	FetchMatlabData(&this->cutoff,mxGetField(matlab_struct,0,"cutoff"));
+	FetchMatlabData(&this->coeff,mxGetField(matlab_struct,0,"coeff"));
+	FetchMatlabData(&this->errg,mxGetField(matlab_struct,0,"errg"));
+	FetchMatlabData(&this->gradation,mxGetField(matlab_struct,0,"gradation"));
+	FetchMatlabData(&this->Hessiantype,mxGetField(matlab_struct,0,"Hessiantype"));
+	FetchMatlabData(&this->MaxCornerAngle,mxGetField(matlab_struct,0,"MaxCornerAngle"));
+	FetchMatlabData(&this->maxnbv,mxGetField(matlab_struct,0,"maxnbv"));
+	FetchMatlabData(&this->maxsubdiv,mxGetField(matlab_struct,0,"maxsubdiv"));
+	FetchMatlabData(&this->Metrictype,mxGetField(matlab_struct,0,"Metrictype"));
+	FetchMatlabData(&this->nbjacobi,mxGetField(matlab_struct,0,"nbjacobi"));
+	FetchMatlabData(&this->nbsmooth,mxGetField(matlab_struct,0,"nbsmooth"));
+	FetchMatlabData(&this->omega,mxGetField(matlab_struct,0,"omega"));
+	FetchMatlabData(&this->power,mxGetField(matlab_struct,0,"power"));
+	FetchMatlabData(&this->verbose,mxGetField(matlab_struct,0,"verbose"));
+
+	FetchMatlabData(&this->Crack,mxGetField(matlab_struct,0,"Crack"));
+	FetchMatlabData(&this->geometricalmetric,mxGetField(matlab_struct,0,"geometricalmetric"));
+	FetchMatlabData(&this->KeepVertices,mxGetField(matlab_struct,0,"KeepVertices"));
+	FetchMatlabData(&this->splitcorners,mxGetField(matlab_struct,0,"splitcorners"));
+
+	FetchMatlabData(&this->hmin,mxGetField(matlab_struct,0,"hmin"));
+	FetchMatlabData(&this->hmax,mxGetField(matlab_struct,0,"hmax"));
+	FetchMatlabData(&this->hminVertices,&this->hminVerticesSize[0],&this->hminVerticesSize[1],mxGetField(matlab_struct,0,"hminVertices"));
+	FetchMatlabData(&this->hmaxVertices,&this->hmaxVerticesSize[0],&this->hmaxVerticesSize[1],mxGetField(matlab_struct,0,"hmaxVertices"));
+	FetchMatlabData(&this->hVertices,&this->hVerticesSize[0],&this->hVerticesSize[1],mxGetField(matlab_struct,0,"hVertices"));
+	FetchMatlabData(&this->metric,&this->metricSize[0],&this->metricSize[1],mxGetField(matlab_struct,0,"metric"));
+	FetchMatlabData(&this->field,&this->fieldSize[0],&this->fieldSize[1],mxGetField(matlab_struct,0,"field"));
+	FetchMatlabData(&this->err,&this->errSize[0],&this->errSize[1],mxGetField(matlab_struct,0,"err"));
+
+	/*Additional checks*/
+	this->Check();
+
+}
+#endif
+/*}}}*/
+/*FUNCTION BamgOpts::~BamgOpts() {{{1*/
+BamgOpts::~BamgOpts(){
+
+	xfree((void**)&this->hminVertices);
+	xfree((void**)&this->hmaxVertices);
+	xfree((void**)&this->hVertices);
+	xfree((void**)&this->metric);
+	xfree((void**)&this->field);
+	xfree((void**)&this->err);
+
+}
+/*}}}*/
+
+/*Methods*/
+/*FUNCTION BamgOpts::Check{{{1*/
+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=%g",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 %i x %i",1,this->fieldSize[1]);
+		for (i=0;i<this->fieldSize[1];i++) {if (this->err[i]<=0) _error_("'err' option should be >0");};
+	}
+
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgOpts.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgOpts.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgOpts.h	(revision 11330)
@@ -0,0 +1,64 @@
+/*!\file:  BamgOpts.h
+ * \brief place holder for optimization function arguments
+ */ 
+
+#ifndef _BAMGOPTS_H_
+#define _BAMGOPTS_H_
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+class BamgOpts{
+
+	public:
+
+		/*Parameters*/
+		double  anisomax;
+		double  cutoff;
+		double  coeff;
+		double  errg;
+		double  gradation;
+		int     Hessiantype;
+		double  MaxCornerAngle;
+		int     maxnbv;
+		double  maxsubdiv;
+		int     Metrictype;
+		int     nbjacobi;
+		int     nbsmooth;
+		double  omega;
+		double  power;
+		int     verbose;
+
+		/*Flags*/
+		int     Crack;
+		int     geometricalmetric;
+		int     KeepVertices;
+		int     splitcorners;
+
+		/*Metric related*/
+		double  hmin;
+		double  hmax;
+		int     hminVerticesSize[2];
+		double* hminVertices;
+		int     hmaxVerticesSize[2];
+		double* hmaxVertices;
+		int     hVerticesSize[2];
+		double* hVertices;
+		int     metricSize[2];
+		double* metric;
+		int     fieldSize[2];
+		double* field;
+		int     errSize[2];
+		double* err;
+
+		BamgOpts();
+		#ifdef _SERIAL_
+		BamgOpts(mxArray* matlab_struct);
+		#endif
+		~BamgOpts();
+
+		void Check(void);
+
+};
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgVertex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgVertex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgVertex.cpp	(revision 11330)
@@ -0,0 +1,256 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "../objects.h"
+
+namespace bamg {
+
+	/*Methods*/
+	/*FUNCTION BamgVertex::Echo {{{1*/
+
+	void BamgVertex::Echo(void){
+
+		printf("Vertex:\n");
+		printf("  integer   coordinates i.x: %i, i.y: %i\n",i.x,i.y);
+		printf("  Euclidean coordinates r.x: %g, r.y: %g\n",r.x,r.y);
+		printf("  ReferenceNumber = %i\n",ReferenceNumber);
+		m.Echo();
+
+		return;
+	}
+	/*}}}*/
+	/*FUNCTION BamgVertex::GetReferenceNumber{{{1*/
+	int  BamgVertex::GetReferenceNumber() const { 
+		return ReferenceNumber;
+	}
+	/*}}}*/
+	/*FUNCTION BamgVertex::MetricFromHessian{{{1*/
+	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 %i not supported yet (use 0,1 or 2(default))",Metrictype);
+		}
+
+		//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);
+
+	}
+	/*}}}1*/
+	/*FUNCTION BamgVertex::Optim {{{1*/
+	long BamgVertex::Optim(int i,int koption){ 
+		long ret=0;
+		if ( t && (IndexInTriangle >= 0 ) && (IndexInTriangle <3) ){
+			ret = t->Optim(IndexInTriangle,koption);
+			if(!i){
+				t =0; // for no future optime 
+				IndexInTriangle= 0;
+			}
+		}
+		return ret;
+	}
+	/*}}}*/
+	/*FUNCTION BamgVertex::Smoothing{{{1*/
+	double  BamgVertex::Smoothing(Mesh &Th,const Mesh &BTh,Triangle* &tstart ,double omega){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Smoothing)*/
+
+		register BamgVertex* s=this;
+		BamgVertex &vP = *s,vPsave=vP;
+
+		register Triangle* tbegin= t , *tria = t , *ttc;
+
+		register int k=0,kk=0,j = EdgesVertexTriangle[IndexInTriangle][0],jc;
+		R2 P(s->r),PNew(0,0);
+		do {
+			k++; 
+
+			if (!tria->Hidden(j)){
+				BamgVertex &vQ = (*tria)[VerticesOfTriangularEdge[j][0]]; 
+
+				R2 Q = vQ,QP(P-Q);
+				double lQP = LengthInterpole(vP,vQ,QP);
+				PNew += Q+QP/Max(lQP,1e-20);
+				kk ++;
+			}
+			ttc =  tria->TriangleAdj(j);
+			jc = NextEdge[tria->NuEdgeTriangleAdj(j)];
+			tria = ttc;
+			j = NextEdge[jc];
+			if (k>=2000){
+				_error_("k>=2000 (Maximum number of iterations reached)");
+			}
+		} while ( tbegin != tria); 
+		if (kk<4) return 0;
+		PNew = PNew/(double)kk;
+		R2 Xmove((PNew-P)*omega);
+		PNew = P+Xmove;
+		double delta=Norme2_2(Xmove); 
+
+		Icoor2 deta[3];
+		I2 IBTh  = BTh.R2ToI2(PNew);
+
+		tstart=BTh.TriangleFindFromCoord(IBTh,deta,tstart);  
+
+		if (tstart->det <0){ // outside
+			double ba,bb;
+			AdjacentTriangle edge= CloseBoundaryEdge(IBTh,tstart,ba,bb) ;
+			tstart = edge;
+			vP.m= Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1));
+		}
+		else { // inside
+			double   aa[3];
+			double s = deta[0]+deta[1]+deta[2];
+			aa[0]=deta[0]/s;
+			aa[1]=deta[1]/s;
+			aa[2]=deta[2]/s;
+			vP.m = Metric(aa,(*tstart)[0],(*tstart)[1],(*tstart)[2]);
+		}
+
+		// recompute the det of the triangle
+		vP.r = PNew;
+
+		vP.i = Th.R2ToI2(PNew);
+
+		BamgVertex vPnew = vP;
+
+		int ok=1;
+		int loop=1;
+		k=0;
+		while (ok){
+			ok =0;
+			do {
+				k++; 
+				double detold = tria->det;
+				tria->det =  bamg::det( (*tria)[0],(*tria)[1]  ,(*tria)[2]);
+				if (loop) {
+					BamgVertex *v0,*v1,*v2,*v3;
+					if (tria->det<0) ok =1;			       
+					else if (tria->Quadrangle(v0,v1,v2,v3))
+					  {
+						vP = vPsave;
+						double qold =QuadQuality(*v0,*v1,*v2,*v3);
+						vP = vPnew;
+						double qnew =QuadQuality(*v0,*v1,*v2,*v3);
+						if (qnew<qold) ok = 1;
+					  }
+					else if ( (double)tria->det < detold/2 ) ok=1;
+
+				}
+				tria->SetUnMarkUnSwap(0);
+				tria->SetUnMarkUnSwap(1);
+				tria->SetUnMarkUnSwap(2);
+				ttc =  tria->TriangleAdj(j);
+				jc = NextEdge[tria->NuEdgeTriangleAdj(j)];
+				tria = ttc;
+				j = NextEdge[jc];
+				if (k>=2000){
+					_error_("k>=2000");
+				}
+			}while ( tbegin != tria); 
+
+			if (ok && loop) vP=vPsave; // no move 
+			loop=0;
+		}
+		return delta;
+	}
+	/*}}}1*/
+
+	/*Intermediary*/
+	/*FUNCTION QuadQuality{{{1*/
+	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)));
+	}
+	/*}}}1*/
+
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgVertex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgVertex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/BamgVertex.h	(revision 11330)
@@ -0,0 +1,58 @@
+#ifndef _BAMGVERTEX_H_
+#define _BAMGVERTEX_H_
+
+#include "./include.h"
+#include "./Metric.h"
+#include "./Direction.h"
+#include "./BamgOpts.h"
+
+namespace bamg {
+
+	//classes
+	class Triangle;
+	class Mesh;
+	class VertexOnGeom;
+	class VertexOnEdge;
+
+	class BamgVertex {
+
+		public:
+
+			/*Fields*/
+			I2        i;                 // integer coordinates
+			R2        r;                 // real coordinates
+			Metric    m;
+			long      ReferenceNumber;
+			Direction DirOfSearch;
+			short     IndexInTriangle;              // the vertex number in triangle; varies between 0 and 2 in t
+
+			union {
+				Triangle     *t;                      // one triangle which is containing the vertex
+				long          color;
+				BamgVertex   *MeshVertexHook;         // used in geometry BamgVertex to know the Mesh Vertex associated
+				VertexOnGeom *GeomEdgeHook;    // if IndexInTriangle == 8; // set with Mesh::SetVertexFieldOn()
+				BamgVertex   *BackgroundVertexHook;   // if IndexInTriangle == 16 on Background vertex Mesh::SetVertexFieldOnBTh()
+				VertexOnEdge *BackgroundEdgeHook;     // if IndexInTriangle == 32 on Background edge
+			};
+
+			/*Operators*/
+			operator I2() const {return i;}             // Cast operator
+			operator const R2 & () const {return r;}    // Cast operator
+			operator Metric () const {return m;}        // Cast operator
+			double operator()(R2 x) const { return m(x);} // Get x in the metric m
+
+			/*methods (No constructor and no destructors...)*/
+			double Smoothing(Mesh & ,const Mesh & ,Triangle  * & ,double =1);
+			void   MetricFromHessian(const double Hxx,const double Hyx, const double Hyy, const double smin,const double smax,const double s,const double err,BamgOpts* bamgopts);
+			void   Echo();
+			int    GetReferenceNumber() const;
+			long   Optim(int =1,int =0); 
+
+			//inline functions
+			inline void Set(const BamgVertex &rec,const Mesh & ,Mesh & ){*this=rec;}
+	};
+
+	//Intermediary
+	double QuadQuality(const BamgVertex &,const BamgVertex &,const BamgVertex &,const BamgVertex &);
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/CrackedEdge.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/CrackedEdge.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/CrackedEdge.cpp	(revision 11330)
@@ -0,0 +1,33 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "CrackedEdge.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION CrackedEdge() {{{1*/
+	CrackedEdge::CrackedEdge() {
+		a=NULL;
+		b=NULL;
+		E=NULL;
+		e1=NULL;
+		e2=NULL;
+		indexa[0]=-1;
+		indexa[1]=-1;
+		indexa[2]=-1;
+		indexb[0]=-1;
+		indexb[1]=-1;
+		indexb[2]=-1;
+		length=0;
+		normal.x=0;
+		normal.y=0;
+
+	}
+	/*}}}*/
+
+	/*Methods*/
+
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/CrackedEdge.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/CrackedEdge.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/CrackedEdge.h	(revision 11330)
@@ -0,0 +1,31 @@
+#ifndef _CRACKEDEDGE_H_
+#define _CRACKEDEDGE_H_
+
+#include "./typedefs.h"
+
+namespace bamg {
+
+	//classes
+	class Triangle;
+	class GeomEdge;
+	class Edge;
+
+	class CrackedEdge {
+
+		public:
+			Triangle* a;
+			Triangle* b; 
+			GeomEdge* E;
+			Edge* e1;
+			Edge* e2;
+			double length;
+			R2     normal;
+			long   indexa[3];
+			long   indexb[3];
+
+			//Constructors
+			CrackedEdge();
+	};
+
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Curve.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Curve.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Curve.cpp	(revision 11330)
@@ -0,0 +1,37 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Curve.h"
+#include "Geometry.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION Curve::Curve(){{{1*/
+	Curve::Curve(){
+		FirstEdge=NULL;
+		LastEdge=NULL;
+		FirstVertexIndex=0;
+		LastVertexIndex=0;
+	} 
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION Curve::Reverse {{{1*/
+	void Curve::Reverse() {
+		/*reverse the direction of the curve */
+		Exchange(FirstEdge,LastEdge);
+		Exchange(FirstVertexIndex,LastVertexIndex);
+	}
+	/*}}}*/
+	/*FUNCTION Curve::Set {{{1*/
+	void Curve::Set(const Curve & rec,const Geometry & Gh ,Geometry & GhNew){
+		*this = rec;
+		FirstEdge = GhNew.edges + Gh.GetId(FirstEdge);    
+		LastEdge = GhNew.edges + Gh.GetId(LastEdge); 
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Curve.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Curve.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Curve.h	(revision 11330)
@@ -0,0 +1,27 @@
+#ifndef _CURVE_H_
+#define _CURVE_H_
+
+#include "../../shared/Bamg/shared.h"
+
+namespace bamg {
+
+	//classes
+	class GeomEdge;
+	class Curve;
+	class Geometry;
+
+	class Curve {
+		public:
+			GeomEdge *FirstEdge; //First edge of the curve
+			GeomEdge *LastEdge;  //Last edge of the curve
+			int FirstVertexIndex;       //Last vertex index in the last edge
+			int LastVertexIndex;        //First Vertex index in the first edge
+
+			//Methods
+			Curve();
+			void Reverse(void);
+			void Set(const Curve & rec,const Geometry & Th ,Geometry & ThNew);
+	};
+
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Direction.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Direction.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Direction.cpp	(revision 11330)
@@ -0,0 +1,36 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Direction.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION Direction() {{{1*/
+	Direction::Direction():
+		dir(MaxICoor){
+
+	}/*}}}*/
+	/*FUNCTION Direction(Icoor1 i,Icoor1 j) {{{1*/
+	Direction::Direction(Icoor1 i,Icoor1 j) {
+		Icoor2 n2 = 2*(Abs(i)+Abs(j));  
+		Icoor2 r  = MaxICoor* (Icoor2) i;
+		Icoor1 r1 = (Icoor1) (2*(r/ n2)); // odd number 
+		dir = (j>0) ? r1 : r1+1;          // odd-> j>0 even-> j<0
+	}/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION Direction::direction{{{1*/
+	int Direction::direction(Icoor1 i,Icoor1 j) {
+		int r =1; 
+		if (dir!= MaxICoor) {
+			Icoor2 x(dir/2),y1(MaxICoor/2-Abs(x)),y(dir%2?-y1:y1);
+			r = (x*i + y*j) >=0;
+		}
+		return r;
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Direction.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Direction.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Direction.h	(revision 11330)
@@ -0,0 +1,21 @@
+#ifndef _DIRECTION_H_
+#define _DIRECTION_H_
+
+#include "./include.h"
+#include "../../shared/Bamg/shared.h"
+
+namespace bamg {
+
+	class Direction {
+		private:
+			Icoor1 dir;
+
+		public:
+			//Methods
+			Direction();
+			Direction(Icoor1 i,Icoor1 j);
+			int direction(Icoor1 i,Icoor1 j);
+	};
+}
+#endif
+
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/DoubleAndInt.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/DoubleAndInt.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/DoubleAndInt.h	(revision 11330)
@@ -0,0 +1,19 @@
+#ifndef _DOUBLEANDINT_H_
+#define _DOUBLEANDINT_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	class DoubleAndInt {
+		//class used by Mesh::MakeQuadrangles
+
+		public:
+			double q;
+			long i3j;
+
+			//Operators
+			int operator<(DoubleAndInt a){return q > a.q;}
+	};
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Edge.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Edge.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Edge.cpp	(revision 11330)
@@ -0,0 +1,54 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Edge.h"
+#include "Mesh.h"
+#include "Geometry.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+
+	/*Methods*/
+	/*FUNCTION Edge::Set {{{1*/
+	void Edge::Set(const Mesh & Th ,long i,Mesh & ThNew){ 
+		*this = Th.edges[i];
+		v[0] = ThNew.vertices + Th.GetId(v[0]);    
+		v[1] = ThNew.vertices + Th.GetId(v[1]);
+		if (GeomEdgeHook) 
+		 GeomEdgeHook =  ThNew.Gh.edges+Th.Gh.GetId(GeomEdgeHook);
+		if (adj[0]) adj[0] =   ThNew.edges +   Th.GetId(adj[0]);
+		if (adj[1]) adj[1] =   ThNew.edges +   Th.GetId(adj[1]);
+	}
+	/*}}}*/
+	/*FUNCTION Edge::Echo {{{1*/
+	void Edge::Echo(void){ 
+		printf("Edge:\n");
+		printf("   pointers towards two vertices: %p %p\n",v[0],v[1]);
+		printf("   ReferenceNumber = %i\n",ReferenceNumber);
+		printf("   GeomEdgeHook = %p\n",GeomEdgeHook);
+		printf("   two adjacent edges on the same curve: %p %p\n",adj[0],adj[1]);
+	}
+	/*}}}*/
+	/*FUNCTION Edge::Renumbering{{{1*/
+	void Edge::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){
+
+		if (v[0] >=vb && v[0] <ve) v[0] = vb + renu[v[0]-vb];
+		if (v[1] >=vb && v[1] <ve) v[1] = vb + renu[v[1]-vb];
+
+	}
+	/*}}}*/
+	/*FUNCTION Edge::Intersection{{{1*/
+	int Edge::Intersection(const  Edge & e){ 
+
+		/*some shecks*/
+		if (!(adj[0]==&e || adj[1]==&e)){ _error_("Intersection bug"); }
+		_assert_(adj[0]==&e || adj[1]==&e);
+
+		return adj[0]==&e?0:1;
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Edge.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Edge.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Edge.h	(revision 11330)
@@ -0,0 +1,38 @@
+#ifndef _EDGE_H_
+#define _EDGE_H_
+
+#include "./include.h"
+#include "./BamgVertex.h"
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "./GeomEdge.h"
+
+namespace bamg {
+
+	//classes
+	class Mesh;
+	
+	class Edge {
+
+		public:
+			BamgVertex      *v[2];
+			long             ReferenceNumber;
+			GeomEdge *GeomEdgeHook;
+			Edge            *adj[2];       // the 2 adj edges if on the same curve
+
+			//Operators
+			BamgVertex       &operator[](int i){return *v[i];   };
+			BamgVertex       *operator()(int     i){return v[i];};
+			R2                operator()(double  t) const;// return the point
+			const BamgVertex &operator[](int i) const{return *v[i];};
+
+			//Methods
+			void Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu);
+			int  Intersection(const  Edge & e);
+			void Set(const Mesh &,long,Mesh &);
+			void Echo(void);
+
+	};
+}
+#endif
+
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/EigenMetric.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/EigenMetric.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/EigenMetric.cpp	(revision 11330)
@@ -0,0 +1,168 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Metric.h"
+
+namespace bamg {
+
+	/*Constructor*/
+	/*FUNCTION EigenMetric::EigenMetric(const Metric M){{{1*/
+	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;
+			}
+		}
+
+	}
+	/*}}}1*/
+	/*FUNCTION EigenMetric::EigenMetric(double r1,double r2,const D2 vp1){{{1*/
+	EigenMetric::EigenMetric(double r1,double r2,const D2& vp1): lambda1(r1),lambda2(r2),v(vp1){
+
+	}/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION EigenMetric::Abs{{{1*/
+	void   EigenMetric::Abs(){
+		lambda1=bamg::Abs(lambda1),lambda2=bamg::Abs(lambda2);
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Aniso{{{1*/
+	double EigenMetric::Aniso() const  { 
+		return sqrt( Aniso2());
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Aniso2{{{1*/
+	double EigenMetric::Aniso2() const  { 
+		return lmax()/lmin();
+	}/*}}}*/
+	/*FUNCTION EigenMetric::BoundAniso{{{1*/
+	void   EigenMetric::BoundAniso(const double c){ 
+		BoundAniso2(1/(c*c));
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Echo {{{1*/
+	void EigenMetric::Echo(void){
+
+		printf("EigenMetric:\n");
+		printf("   lambda1: %g\n",lambda1);
+		printf("   lambda2: %g\n",lambda2);
+		printf("   v.x: %g\n",v.x);
+		printf("   v.y: %g\n",v.y);
+
+		return;
+	}
+	/*}}}*/
+	/*FUNCTION EigenMetric::hmin{{{1*/
+	double EigenMetric::hmin() const {
+		return sqrt(1/bamg::Max3(lambda1,lambda2,1e-30));
+	}/*}}}*/
+	/*FUNCTION EigenMetric::hmax{{{1*/
+	double EigenMetric::hmax() const {
+		return sqrt(1/bamg::Max(bamg::Min(lambda1,lambda2),1e-30));
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Isotrope{{{1*/
+	void   EigenMetric::Isotrope() {
+		lambda1=lambda2=bamg::Max(lambda1,lambda2);
+	}/*}}}*/
+	/*FUNCTION EigenMetric::lmax{{{1*/
+	double EigenMetric::lmax() const {
+		return bamg::Max3(lambda1,lambda2,1e-30);
+	}/*}}}*/
+	/*FUNCTION EigenMetric::lmin{{{1*/
+	double EigenMetric::lmin() const {
+		return bamg::Max(bamg::Min(lambda1,lambda2),1e-30);
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Min{{{1*/
+	void   EigenMetric::Min(double a) { 
+		lambda1=bamg::Min(a,lambda1); lambda2=bamg::Min(a,lambda2) ;
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Max{{{1*/
+	void   EigenMetric::Max(double a) { 
+		//change eigen values
+		lambda1=bamg::Max(a,lambda1); lambda2=bamg::Max(a,lambda2) ;
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Minh{{{1*/
+	void   EigenMetric::Minh(double h) {
+		Min(1.0/(h*h));
+	}/*}}}*/
+	/*FUNCTION EigenMetric::Maxh{{{1*/
+	void   EigenMetric::Maxh(double h) {
+		//Call Max function
+		Max(1.0/(h*h));
+	}/*}}}*/
+	/*FUNCTION EigenMetric::pow{{{1*/
+	void   EigenMetric::pow(double p){
+		lambda1=::pow(lambda1,p);lambda2=::pow(lambda2,p);
+	}/*}}}*/
+
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomEdge.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomEdge.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomEdge.cpp	(revision 11330)
@@ -0,0 +1,190 @@
+#include <cstdio>
+#include <string.h>
+#include <cmath>
+
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+
+#include "GeomEdge.h"
+#include "Geometry.h"
+
+using namespace std;
+
+namespace bamg {
+
+	/*Constructor/Destructor*/
+
+	/*Methods*/
+	/*FUNCTION GeomEdge::Cracked{{{1*/
+	int    GeomEdge::Cracked() const  {
+		return type &1;  
+	}/*}}}*/
+	/*FUNCTION GeomEdge::F{{{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;
+	  }
+	/*}}}1*/
+	/*FUNCTION GeomEdge::Mark{{{1*/
+	int    GeomEdge::Mark()    const  {
+		return type &16; 
+	}/*}}}*/
+	/*FUNCTION GeomEdge::R1tg{{{1*/
+	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;
+	}
+	/*}}}1*/
+	/*FUNCTION GeomEdge::Required{{{1*/
+	int    GeomEdge::Required()       {
+		return type &64; 
+	}/*}}}*/
+	/*FUNCTION GeomEdge::Set {{{1*/
+	void GeomEdge::Set(const GeomEdge & rec,const Geometry & Gh ,Geometry & GhNew){ 
+		*this = rec;
+		v[0] = GhNew.vertices + Gh.GetId(v[0]);    
+		v[1] = GhNew.vertices + Gh.GetId(v[1]); 
+		if (Adj[0]) Adj[0] =  GhNew.edges + Gh.GetId(Adj[0]);     
+		if (Adj[1]) Adj[1] =  GhNew.edges + Gh.GetId(Adj[1]);     
+	}
+	/*}}}*/
+	/*FUNCTION GeomEdge::SetCracked{{{1*/
+	void   GeomEdge::SetCracked()     { 
+		type |= 1;/*=>1st digit to 1*/
+	}/*}}}*/
+	/*FUNCTION GeomEdge::SetTgA{{{1*/
+	void   GeomEdge::SetTgA()         { 
+		type |=4; /*=>2d digit to 1*/
+	}/*}}}*/
+	/*FUNCTION GeomEdge::SetTgB{{{1*/
+	void   GeomEdge::SetTgB()         { 
+		type |=8; /*=> 3d digit to 1*/
+	}/*}}}*/
+	/*FUNCTION GeomEdge::SetMark{{{1*/
+	void   GeomEdge::SetMark()        { 
+		type |=16;/*=> 4th digiy to 1*/
+	}/*}}}*/
+	/*FUNCTION GeomEdge::SetUnMark{{{1*/
+	void   GeomEdge::SetUnMark()      { 
+		type &= 1007 /* 1023-16 = 000111110111 => 4th digit to 0*/;
+	}/*}}}*/
+	/*FUNCTION GeomEdge::SetRequired{{{1*/
+	void   GeomEdge::SetRequired()    { 
+		type |= 64;/*=>6th digit to 1*/ 
+	}/*}}}*/
+	  /*FUNCTION GeomEdge::Tg{{{1*/
+	int    GeomEdge::Tg(int i) const  {
+		return i==0 ? TgA() : TgB();
+	}/*}}}*/
+	/*FUNCTION GeomEdge::TgA{{{1*/
+	int    GeomEdge::TgA()     const  {
+		return type &4;  
+	}/*}}}*/
+	/*FUNCTION GeomEdge::TgB{{{1*/
+	int    GeomEdge::TgB()     const  {
+		return type &8;  
+	}/*}}}*/
+}
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomEdge.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomEdge.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomEdge.h	(revision 11330)
@@ -0,0 +1,47 @@
+#ifndef _GEOMETRICALEDGE_H_
+#define _GEOMETRICALEDGE_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	//classes
+	class GeomVertex;
+	class Geometry;
+
+	class GeomEdge {
+
+		public:
+			GeomVertex *v[2];
+			long               ReferenceNumber;
+			long               CurveNumber;
+			R2                 tg[2];              // the 2 tangentes (tg[0] =0 => no continuity)
+			GeomEdge   *Adj[2];
+			int                AdjVertexIndex[2]; // for a given vertex, this gives the index of the vertex in the adjacent edge (0 or 1)
+			int                type;
+
+			//Operators
+			GeomVertex       & operator[](int i){return *v[i];};
+			const GeomVertex & operator[](int i) const { return *v[i];};
+			GeomVertex       * operator()(int i){return v[i];};  
+
+			//Methods
+			R2     F(double theta) const ; // parametrization of the curve edge
+			double R1tg(double theta,R2 &t) const ; // 1/radius of curvature + tangente
+			int    Tg(int i) const;
+			int    Cracked() const;
+			int    TgA()     const;
+			int    TgB()     const;
+			int    Mark()    const;
+			int    Required();
+			void   SetCracked();
+			void   SetTgA();
+			void   SetTgB();
+			void   SetMark();
+			void   SetUnMark();
+			void   SetRequired();
+			void   Set(const GeomEdge & rec,const Geometry & Th ,Geometry & ThNew);
+	};
+
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomSubDomain.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomSubDomain.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomSubDomain.cpp	(revision 11330)
@@ -0,0 +1,20 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "GeomSubDomain.h"
+#include "Geometry.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+
+	/*Methods*/
+	/*FUNCTION GeomSubDomain::Set {{{1*/
+	void GeomSubDomain::Set(const GeomSubDomain & rec,const Geometry & Gh ,const Geometry & GhNew){
+		*this = rec;
+		edge = Gh.GetId(edge) + GhNew.edges;
+	}/*}}}*/
+
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomSubDomain.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomSubDomain.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomSubDomain.h	(revision 11330)
@@ -0,0 +1,23 @@
+#ifndef _GEOMETRICALSUBDOMAIN_H_
+#define _GEOMETRICALSUBDOMAIN_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	//classes
+	class GeomEdge;
+	class Geometry;
+
+	class GeomSubDomain {
+		public:
+			GeomEdge *edge;
+			int              direction;   // -1 or 1
+			long             ReferenceNumber;
+
+			//Methods
+			void Set(const GeomSubDomain &,const Geometry & ,const Geometry &);
+	};
+
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomVertex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomVertex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomVertex.cpp	(revision 11330)
@@ -0,0 +1,38 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "GeomVertex.h"
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	//See header file
+
+	/*Methods*/
+	/*FUNCTION GeomVertex::Corner {{{1*/
+	int  GeomVertex::Corner() const {
+		return type & 4;
+	}
+	/*}}}*/
+	/*FUNCTION GeomVertex::Required {{{1*/
+	int  GeomVertex::Required()const {
+		// a corner is required
+		return type & 6;
+	}
+	/*}}}*/
+	/*FUNCTION GeomVertex::SetCorner {{{1*/
+	void GeomVertex::SetCorner(){
+		type |= 4;
+	}
+	/*}}}*/
+	/*FUNCTION GeomVertex::SetRequired {{{1*/
+	void GeomVertex::SetRequired(){
+		type |= 2;
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomVertex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomVertex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/GeomVertex.h	(revision 11330)
@@ -0,0 +1,30 @@
+#ifndef _GEOMETRICALVERTEX_H_
+#define _GEOMETRICALVERTEX_H_
+
+#include "./include.h"
+#include "BamgVertex.h"
+
+namespace bamg {
+
+	class Geometry;
+
+	class GeomVertex : public BamgVertex { 
+
+		public:
+			friend class Geometry;
+
+			int type;
+
+			//Constructors
+			GeomVertex():type(0){};
+
+			//Methods
+			int  Corner() const;
+			int  Required()const;
+			void SetCorner();
+			void SetRequired();
+
+	};
+
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Geometry.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Geometry.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Geometry.cpp	(revision 11330)
@@ -0,0 +1,971 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "../objects.h"
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+
+namespace bamg {
+
+	static const  Direction NoDirOfSearch=Direction();
+
+	/*Constructors/Destructors*/
+	/*FUNCTION Geometry::Geometry(){{{1*/
+	Geometry::Geometry(){
+		Init();
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::Geometry(BamgGeom* bamggeom, BamgOpts* bamgopts){{{1*/
+	Geometry::Geometry(BamgGeom* bamggeom, BamgOpts* bamgopts){
+		Init();
+		ReadGeometry(bamggeom,bamgopts);
+		PostRead();
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::Geometry(const Geometry & Gh) (COPY operator){{{1*/
+	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);
+	}
+	/*}}}1*/
+	/*FUNCTION Geometry::~Geometry(){{{1*/
+	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();
+	}
+	/*}}}1*/
+
+	/*IO*/
+	/*FUNCTION Geometry::ReadGeometry{{{1*/
+	void Geometry::ReadGeometry(BamgGeom* bamggeom,BamgOpts* bamgopts){
+
+		int verbose;
+		nbv=0;
+		nbe=0;
+		nbcurves=0;
+
+		double Hmin = HUGE_VAL;// the infinie value 
+		int i,j,k,n,i0,i1,i2,i3;
+
+		/*initialize some variables*/
+		verbose= bamgopts->verbose;
+		nbv    = bamggeom->VerticesSize[0];
+		nbe    = bamggeom->EdgesSize[0];
+
+		//some checks
+		if (bamggeom->Vertices==NULL) _error_("the domain provided does not contain any vertex");
+		if (bamggeom->Edges==NULL) _error_("the domain provided does not contain any edge");
+
+		//Vertices
+		if (bamggeom->Vertices){
+			if(verbose>5) 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 (!isnan(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 %i]",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 %i]",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 %i]",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 %i] (edge number)",nbe);
+				subdomains[i].edge=edges + (i1-1);
+				subdomains[i].direction = (int) i2;
+				subdomains[i].ReferenceNumber = i3;
+			}
+		}
+	}
+	/*}}}1*/
+	/*FUNCTION Geometry::WriteGeometry{{{1*/
+	void Geometry::WriteGeometry(BamgGeom* bamggeom, BamgOpts* bamgopts){
+
+		int verbose;
+		int nbreq=0;
+		int nbreqv=0;
+		int nbtan=0;
+		int nbcracked=0;
+		int i,count;
+
+		/*Get options*/
+		verbose=bamgopts->verbose;
+
+		/*Vertices*/
+		if(verbose>5) printf("      writing Vertices\n");
+		bamggeom->VerticesSize[0]=nbv;
+		bamggeom->VerticesSize[1]=3;
+		if (nbv){
+			bamggeom->Vertices=(double*)xmalloc(3*nbv*sizeof(double));
+			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=(double*)xmalloc(3*nbe*sizeof(double));
+			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 %i RequiredEdges\n",nbreq);
+		bamggeom->RequiredEdgesSize[0]=nbreq;
+		bamggeom->RequiredEdgesSize[1]=1;
+		if (nbreq){
+			bamggeom->RequiredEdges=(double*)xmalloc(1*nbreq*sizeof(double));
+			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 %i RequiredVertices\n",nbreqv);
+		bamggeom->RequiredVerticesSize[0]=nbreqv;
+		bamggeom->RequiredVerticesSize[1]=1;
+		if (nbreqv){
+			bamggeom->RequiredVertices=(double*)xmalloc(1*nbreqv*sizeof(double));
+			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=(double*)xmalloc(4*nbsubdomains*sizeof(double));
+			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=(double*)xmalloc(4*nbtan*sizeof(double));
+			count=0;
+			for (i=0;i<nbe;i++){
+				if (edges[i].TgA() && edges[i][0].Corner()){
+					bamggeom->TangentAtEdges[4*i+0]=i+1; //back to Matlab indexing
+					bamggeom->TangentAtEdges[4*i+1]=1;
+					bamggeom->TangentAtEdges[4*i+2]=edges[i].tg[0].x;
+					bamggeom->TangentAtEdges[4*i+3]=edges[i].tg[0].y;
+				}
+				if (edges[i].TgB() && edges[i][1].Corner()){
+					bamggeom->TangentAtEdges[4*i+0]=i+1; //back to Matlab indexing
+					bamggeom->TangentAtEdges[4*i+1]=2;
+					bamggeom->TangentAtEdges[4*i+2]=edges[i].tg[1].x;
+					bamggeom->TangentAtEdges[4*i+3]=edges[i].tg[1].y;
+				}
+				count=count+1;
+			}
+		}
+	}
+	/*}}}1*/
+
+	/*Methods*/
+	/*FUNCTION Geometry::Echo {{{1*/
+	void Geometry::Echo(void){
+
+		printf("Geometry:\n");
+		printf("   nbv  (number of vertices) : %i\n",nbv);
+		printf("   nbe  (number of edges)    : %i\n",nbe);
+		printf("   nbsubdomains: %i\n",nbsubdomains);
+		printf("   nbcurves: %i\n",nbcurves);
+		printf("   vertices: %p\n",vertices);
+		printf("   edges: %p\n",edges);
+		printf("   quadtree: %p\n",quadtree);
+		printf("   subdomains: %p\n",subdomains);
+		printf("   curves: %p\n",curves);
+		printf("   pmin (x,y): (%g %g)\n",pmin.x,pmin.y);
+		printf("   pmax (x,y): (%g %g)\n",pmax.x,pmax.y);
+		printf("   coefIcoor: %g\n",coefIcoor);
+		printf("   MaxCornerAngle: %g\n",MaxCornerAngle);
+
+		return;
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::Init{{{1*/
+	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
+	}
+	/*}}}1*/
+	/*FUNCTION Geometry::MinimalHmin{{{1*/
+	double Geometry::MinimalHmin() {
+		/* coeffIcoor = (2^30-1)/D
+		 * We cannot go beyond hmin = D/2^30 because of the quadtree
+		 * hmin is therefore approximately 2/coeffIcoor */
+		return 2.0/coefIcoor;
+	}/*}}}*/
+	/*FUNCTION Geometry::MaximalHmax{{{1*/
+	double Geometry::MaximalHmax() {
+		return Max(pmax.x-pmin.x,pmax.y-pmin.y);
+	}/*}}}*/
+	/*FUNCTION Geometry::GetId(const GeomVertex &t){{{1*/
+	long Geometry::GetId(const GeomVertex & t) const  {
+		return &t - vertices;
+	}/*}}}*/
+	/*FUNCTION Geometry::GetId(const GeomVertex * t){{{1*/
+	long Geometry::GetId(const GeomVertex * t) const  {
+		return t - vertices;
+	}/*}}}*/
+	/*FUNCTION Geometry::GetId(const GeomEdge & t){{{1*/
+	long Geometry::GetId(const GeomEdge & t) const  {
+		return &t - edges;
+	}/*}}}*/
+	/*FUNCTION Geometry::GetId(const GeomEdge * t){{{1*/
+	long Geometry::GetId(const GeomEdge * t) const  {
+		return t - edges;
+	}/*}}}*/
+	/*FUNCTION Geometry::GetId(const Curve * c){{{1*/
+	long Geometry::GetId(const Curve * c) const  {
+		return c - curves;
+	}/*}}}*/
+	/*FUNCTION Geometry::Containing{{{1*/
+	GeomEdge* Geometry::Containing(const R2 P,  GeomEdge * start) const {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/Contening)*/
+
+		GeomEdge* on =start,* pon=0;
+		// walk with the cos on geometry
+		int counter=0;
+		while(pon != on){  
+			counter++;
+			_assert_(counter<100);
+			pon = on;
+			R2 A= (*on)[0];
+			R2 B= (*on)[1];
+			R2 AB = B-A;
+			R2 AP = P-A;
+			R2 BP = P-B;
+			if ( (AB,AP) < 0) 
+			 on = on->Adj[0];
+			else if ( (AB,BP)  > 0) 
+			 on = on->Adj[1];
+			else
+			 return on;
+		}
+		return on;
+	}
+	/*}}}1*/
+	/*FUNCTION Geometry::PostRead{{{1*/
+	void Geometry::PostRead(){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/AfterRead)*/
+
+		long               i,j,k;
+		int                jj;
+		long              *head_v   = new long[nbv];
+		long              *next_p   = new long[2*nbe];
+		float             *eangle   = new float[nbe];
+		double             eps      = 1e-20;
+		QuadTree           quadtree; // build quadtree to find duplicates
+		BamgVertex        *v0       = vertices;
+		GeomVertex *v0g      = (GeomVertex*) (void*)v0;
+
+		k=0;
+
+		//build quadtree for this geometry
+		for (i=0;i<nbv;i++){
+
+			/*build integer coordinates (non unique)
+			  these coordinates are used by the quadtree to group
+			  the vertices by groups of 5:
+			  All the coordinates are transformed to ]0,1[^2
+			  then, the integer coordinates are computed using 
+			  the transformation ]0,1[^2 -> [0 2^30-1[^2 for a quadtree of depth 30*/
+			vertices[i].i=R2ToI2(vertices[i].r); 
+
+			/*find nearest vertex already present in the quadtree (NULL if empty)*/
+			BamgVertex* v=quadtree.NearestVertex(vertices[i].i.x,vertices[i].i.y); 
+
+			/*if there is a vertex found that is to close to vertices[i] -> error*/
+			if( v && Norme1(v->r - vertices[i].r) < eps ){
+				printf("reference numbers: %i %i\n",v->ReferenceNumber,vertices[i].ReferenceNumber);
+				printf("Id: %i\n",i+1);
+				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",i);
+			}
+			//compute angle in [-Pi Pi]
+			eangle[i] = atan2(v10.y,v10.x);
+			//build chains head_v and next_p
+			for (j=0;j<2;j++){
+				long v=GetId(edges[i].v[j]);
+				next_p[k]=head_v[v];
+				head_v[v]=k++; //post increment: head_v[v]=k; and then k=k+1;
+			}
+		}
+
+		//sort head_v by order of increasing edges angle
+		for (i=0;i<nbv;i++) {
+			int exch=1,ord=0;      
+
+			//exchange vertices position in head_v and next_p till tey are sorted
+			while (exch){
+				long *p=head_v+i;               
+				long *po=p;                     
+				long  n=*p;                     
+				register float angleold=-1000 ; // angle = - infinity
+				ord=0; exch=0;
+
+				// loop over the edges that contain the vertex i (till -1)
+				while (n >=0){
+					ord++;
+					long  i1=n/2;       // i1 = floor (n/2)      -> Edge number
+					long  j1=n%2;       // j1 = 1 if n is odd    -> Vertex index for this edge (0 or 1)
+					long* pn=next_p+n;
+
+					//Next vertex index
+					n=*pn;                       
+
+					//compute angle between horizontal axis and v0->v1
+					float angle = j1 ? OppositeAngle(eangle[i1]):  eangle[i1]; 
+
+					//exchange if the current edge angle is smaller than the previous one
+					if (angleold > angle){
+						exch=1;
+						*pn=*po;  // next_p[n] = n + 1
+						*po=*p;   // 
+						*p=n;     // next_p[n+1] = n
+						po=pn;    // po now point toward pn (invert next and current)
+					}
+
+					//else, continue going to the next edge position
+					else{                        //  to have : po -> p -> pn
+						angleold=angle; // update maximum angle
+						po=p;           // po now point toward p  (current position)
+						p=pn;           // p  now point toward pn (next position)
+					}
+				}
+			}
+
+			// angular test on current vertex to guess whether it is a corner (ord = number of edges holding i)
+			if(ord==2) { 
+				long  n1 = head_v[i];
+				long  n2 = next_p[n1];
+				long  i1 = n1/2, i2 = n2/2; // edge number
+				long  j1 = n1%2, j2 = n2%2; // vertex in the edge 
+				float angle1=  j1 ? OppositeAngle(eangle[i1]) : eangle[i1];
+				float angle2= !j2 ? OppositeAngle(eangle[i2]) : eangle[i2];
+				float da12 = Abs(angle2-angle1);
+				if (( da12 >= MaxCornerAngle ) && (da12 <= 2*Pi -MaxCornerAngle)) {
+					vertices[i].SetCorner() ; 
+				}
+				// if the edge type/referencenumber a changing then is SetRequired();
+				if (edges[i1].type != edges[i2].type || edges[i1].Required()){
+					vertices[i].SetRequired();
+				}
+				if (edges[i1].ReferenceNumber != edges[i2].ReferenceNumber) {
+					vertices[i].SetRequired();
+				}
+			}
+			if(ord != 2) {
+				vertices[i].SetCorner();
+			}
+
+			/*close the list around the vertex to have a circular loop*/
+			long no=-1, ne = head_v[i];
+			while (ne >=0) ne = next_p[no=ne];        
+			if(no>=0) next_p[no] = head_v[i];
+		}
+
+		/*Check that the list makes sense (we have all the time the same vertex)
+		 * and build adjacent edges*/
+		k =0;
+		for (i=0;i<nbe;i++){
+			for (j=0;j<2;j++){
+
+				long n1 = next_p[k++]; 
+				long i1 = n1/2 ,j1=n1%2;
+
+				if( edges[i1].v[j1] != edges[i].v[j]) _error_("Problem while processing edges: check the edge list");
+
+				edges[i1].Adj[j1] = edges + i;
+				edges[i1].AdjVertexIndex[j1] = j;
+			}
+		}
+
+		/* generation of  all the tangents*/
+		for (i=0;i<nbe;i++) {
+			R2    AB =edges[i].v[1]->r -edges[i].v[0]->r;// AB = vertex0 -> vertex1
+			double lAB=Norme2(AB);                       // Get length of AB
+			double ltg2[2]={0.0};                        // initialize tangent
+
+			//loop over the 2 vertices of the edge
+			for (j=0;j<2;j++) {
+				R2     tg =edges[i].tg[j];
+				double ltg=Norme2(tg);
+
+				//by default, tangent=[0 0]
+				if(ltg==0){
+					//if the current vertex of the edge is not a corner
+					if(!edges[i].v[j]->Corner()){
+						/*The tangent is set as the vector between the
+						 * previous and next vertices connected to current vertex
+						 * normed by the edge length*/
+						tg = edges[i].v[1-j]->r - edges[i].Adj[j]->v[1-edges[i].AdjVertexIndex[j]]->r;
+						ltg= Norme2(tg);
+						tg = tg *(lAB/ltg);
+						ltg= lAB;
+					}
+					//else:  a Corner no tangent => nothing to do    
+				}
+				else{
+					//tangent has already been computed
+					tg = tg*(lAB/ltg),ltg=lAB;
+				}
+
+				ltg2[j] = ltg;
+
+				if ((tg,AB)<0) tg = -tg;
+
+				edges[i].tg[j]=tg;
+			}
+			if (ltg2[0]!=0) edges[i].SetTgA();
+			if (ltg2[1]!=0) edges[i].SetTgB();
+		} 
+
+		/* generation of  all curves (from corner to corner)*/
+		/*We proceed in 2 steps: first allocate, second build*/
+		for (int step=0;step<2;step++){
+
+			//unmark all edges
+			for (i=0;i<nbe;i++) edges[i].SetUnMark();
+			long  nb_marked_edges=0;
+
+			//initialize number of curves
+			nbcurves = 0;
+
+			for (int level=0;level<2 && nb_marked_edges!=nbe;level++){
+				for (i=0;i<nbe;i++){
+
+					GeomEdge & ei=edges[i];   
+					for(j=0;j<2;j++){
+						/*If current edge ei is unmarked and (level=1 or vertex i is required (corner)):
+						 * we do have the first edge of a new curve*/
+						if (!ei.Mark() && (level || ei[j].Required())) { 
+							int k0=j,k1;
+							GeomEdge   *e=&ei;
+							GeomVertex *a=(*e)(k0); // begin 
+							if(curves){
+								curves[nbcurves].FirstEdge=e;
+								curves[nbcurves].FirstVertexIndex=k0;
+							}
+							int nee=0;
+							for(;;){ 
+								nee++;
+								k1 = 1-k0; // next vertex of the edge 
+								e->SetMark();
+								nb_marked_edges++;
+								e->CurveNumber=nbcurves;
+								GeomVertex *b=(*e)(k1);
+
+								//break if we have reached the other end of the curve
+								if (a==b || b->Required()){
+									if(curves){
+										curves[nbcurves].LastEdge=e;
+										curves[nbcurves].LastVertexIndex=k1;
+									}
+									break;
+								}
+								//else: go to next edge (adjacent)
+								else{
+									k0 = e->AdjVertexIndex[k1];//  vertex in next edge
+									e  = e->Adj[k1]; // next edge
+								}
+							}
+							nbcurves++;
+							if(level) a->SetRequired();
+						}
+					}
+				} 
+			}
+			_assert_(nb_marked_edges && nbe);
+			//allocate if first step
+			if(step==0) curves=new Curve[nbcurves];
+		} 
+
+		/*clean up*/
+		delete [] next_p;
+		delete [] head_v;
+		delete [] eangle;
+
+	}
+	/*}}}1*/
+	/*FUNCTION Geometry::ProjectOnCurve {{{1*/
+	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 %i geometrical edges\n",mxe/2);
+					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 %i geometrical edges\n",mxe/2);
+				printf(" 2)  code bug : be sure that we call   Mesh::SetVertexFieldOn() before\n");
+				printf("To solve the problem do a coarsening of the geometrical mesh or change the constant value of mxe (dangerous)\n");
+				_error_("see above");
+			}
+			GeomEdge* tmpge = eg1;
+			ge[++tge] =eg1 = eg1->Adj[direction1];
+			directionge[tge]= direction1 = 1-tmpge->AdjVertexIndex[direction1];
+			_assert_(tge>=0 && tge<=mxe);
+		}
+
+
+		if ((*eg0)(direction0)==(GeomVertex*)vg0)
+		 vg0=VertexOnGeom(*(BamgVertex*) vg0,*eg0,direction0); //vg0 = absisce
+
+		if ((*eg1)(direction1)==(GeomVertex*)vg1)
+		 vg1=VertexOnGeom(*(BamgVertex*) vg1,*eg1,direction1);
+
+		double sg;
+		if (eg0 == eg1) { 
+			register double s0=vg0,s1=vg1;
+			sg =  s0*(1.0-s) +  s*s1;
+			on=eg0;
+		}
+		else {
+			R2 AA=V0,BB;
+			double s0,s1;
+			int i=bge;
+			double ll=0;
+			for(i=bge;i<tge;i++){
+				_assert_(i>=0 && i<=mxe);
+				BB =  (*ge[i])[directionge[i]];
+				lge[i]=ll += Norme2(AA-BB);
+				AA=BB ;}
+				lge[tge]=ll+=Norme2(AA-V1); 
+				// search the geometrical edge
+				_assert_(s<=1.0);
+				double ls= s*ll;
+				on =0;
+				s0 = vg0;
+				s1= directionge[bge];
+				double l0=0,l1;
+				i=bge;
+				while (  (l1=lge[i]) < ls ) {
+					_assert_(i>=0 && i<=mxe);
+					i++,s0=1-(s1=directionge[i]),l0=l1;
+				}
+				on=ge[i];
+				if (i==tge) 
+				 s1=vg1;
+
+				s  =(ls-l0)/(l1-l0);
+				sg =s0*(1.0-s)+s*s1;    
+		} 
+		_assert_(on);
+		V.r= on->F(sg);
+		GV=VertexOnGeom(V,*on,sg);
+		return on;
+	}
+	/*}}}1*/
+	/*FUNCTION Geometry::R2ToI2{{{1*/
+	I2 Geometry::R2ToI2(const R2 & P) const {
+		/*coefIcoor is the coefficient used for integer coordinates:
+		 *                       (x-pmin.x)
+		 * Icoor x = (2^30 -1) ------------ 
+		 *                          D
+		 * where D is the longest side of the domain (direction x or y)
+		 * so that (x-pmin.x)/D is in ]0 1[
+		 *
+		 * coefIcoor = (2^30 -1)/D
+		 */
+		return  I2( (Icoor1) (coefIcoor*(P.x-pmin.x)) ,(Icoor1) (coefIcoor*(P.y-pmin.y)) );
+	}/*}}}*/
+	/*FUNCTION Geometry::UnMarkEdges{{{1*/
+	void Geometry::UnMarkEdges() {
+		for (int i=0;i<nbe;i++) edges[i].SetUnMark();
+	}/*}}}*/
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Geometry.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Geometry.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Geometry.h	(revision 11330)
@@ -0,0 +1,68 @@
+#ifndef _GEOMETRY_H_
+#define _GEOMETRY_H_
+
+#include "./include.h"
+#include "./BamgGeom.h"
+#include "./BamgOpts.h"
+#include "./GeomVertex.h"
+#include "./GeomEdge.h"
+#include "./Curve.h"
+
+namespace bamg {
+
+	class Triangle;
+	class QuadTree;
+	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;
+			QuadTree             *quadtree;
+			GeomSubDomain *subdomains;
+			Curve                *curves;
+			R2                    pmin,pmax;                     // domain extrema coordinates
+			double                coefIcoor;                     // coef to integer Icoor1;
+			double                MaxCornerAngle;
+
+			//Constructor/Destructors
+			~Geometry(); 
+			Geometry();
+			Geometry(const Geometry & Gh);
+			Geometry(BamgGeom* bamggeom, BamgOpts* bamgopts);
+
+			//Operators
+			const GeomVertex &operator[](long i) const { return vertices[i]; };
+			GeomVertex       &operator[](long i) { return vertices[i];       };
+			const GeomEdge   &operator()(long i) const { return edges[i];    };
+			GeomEdge         &operator()(long  i) { return edges[i];                };
+
+			//Methods
+			void             Echo();
+			I2               R2ToI2(const R2 &P) const;
+			double           MinimalHmin();
+			double           MaximalHmax();
+			void             ReadGeometry(BamgGeom *bamggeom, BamgOpts*bamgopts);
+			void             Init(void);
+			void             PostRead();
+			long             GetId(const GeomVertex &t) const;
+			long             GetId(const GeomVertex *t) const;
+			long             GetId(const GeomEdge &t) const;
+			long             GetId(const GeomEdge *t) const;
+			long             GetId(const Curve *c) const;
+			void             UnMarkEdges();
+			GeomEdge *ProjectOnCurve(const Edge &,double,BamgVertex &,VertexOnGeom &) const;
+			GeomEdge *Containing(const R2 P, GeomEdge *start) const;
+			void             WriteGeometry(BamgGeom *bamggeom, BamgOpts*bamgopts);
+	};
+	
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/ListofIntersectionTriangles.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/ListofIntersectionTriangles.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/ListofIntersectionTriangles.cpp	(revision 11330)
@@ -0,0 +1,425 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "../objects.h"
+
+namespace bamg {
+
+	/*Constructors Destructors*/
+	/*FUNCTION ListofIntersectionTriangles::ListofIntersectionTriangles{{{1*/
+	ListofIntersectionTriangles::ListofIntersectionTriangles(int n,int m)
+	  : MaxSize(n), Size(0), len(-1),state(-1),lIntTria(new IntersectionTriangles[n]) ,
+	  NbSeg(0), MaxNbSeg(m), lSegsI(new SegInterpolation[m]){
+	  }
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::~ListofIntersectionTriangles{{{1*/
+	ListofIntersectionTriangles::~ListofIntersectionTriangles(){
+		if (lIntTria) delete [] lIntTria,lIntTria=0;
+		if (lSegsI) delete [] lSegsI,lSegsI=0;
+	} 
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION ListofIntersectionTriangles::Init{{{1*/
+	void ListofIntersectionTriangles::Init(void){
+		state=0;
+		len=0;
+		Size=0;
+	}
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::Length{{{1*/
+	double  ListofIntersectionTriangles::Length(){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Length)*/
+
+		// computation of the length
+
+		// check Size
+		if (Size<=0){
+			_error_("Size<=0");
+		}
+
+		Metric Mx,My;
+		int ii,jj;
+		R2 x,y,xy;
+
+		SegInterpolation* SegI=lSegsI;
+		SegI=lSegsI;
+		lSegsI[NbSeg].last=Size;
+		int EndSeg=Size;
+
+		y = lIntTria[0].x;
+		double sxy, s = 0;
+		lIntTria[0].s =0;
+		SegI->lBegin=s;
+
+		for (jj=0,ii=1;ii<Size;jj=ii++) {  
+			// seg jj,ii
+			x  = y;
+			y  = lIntTria[ii].x;
+			xy = y-x;
+			Mx = lIntTria[ii].m;
+			My = lIntTria[jj].m;
+			sxy= LengthInterpole(Mx,My,xy);
+			s += sxy;
+			lIntTria[ii].s = s;
+			if (ii == EndSeg){
+				SegI->lEnd=s;
+				SegI++;
+				EndSeg=SegI->last;
+				SegI->lBegin=s;
+			}
+		}
+		len = s;
+		SegI->lEnd=s;
+
+		return s;
+	}
+	/*}}}1*/
+	/*FUNCTION ListofIntersectionTriangles::NewItem(Triangle * tt,double d0,double d1,double d2) {{{1*/
+	int  ListofIntersectionTriangles::NewItem(Triangle * tt,double d0,double d1,double d2) { 
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewItem)*/
+
+		register int n;
+		R2 x(0,0);
+		if ( d0) x =      (*tt)[0].r * d0;
+		if ( d1) x = x +  (*tt)[1].r * d1;
+		if ( d2) x = x +  (*tt)[2].r * d2;
+		// newer add same point 
+		if(!Size ||  Norme2_2(lIntTria[Size-1].x-x)) {
+			if (Size==MaxSize) ReShape();
+			lIntTria[Size].t=tt;
+			lIntTria[Size].bary[0]=d0;
+			lIntTria[Size].bary[1]=d1;
+			lIntTria[Size].bary[2]=d2;
+			lIntTria[Size].x = x;
+			Metric m0,m1,m2;
+			register BamgVertex * v;
+			if ((v=(*tt)(0))) m0    = v->m;
+			if ((v=(*tt)(1))) m1    = v->m;
+			if ((v=(*tt)(2))) m2    = v->m;
+			lIntTria[Size].m =  Metric(lIntTria[Size].bary,m0,m1,m2);
+			n=Size++;}
+		else n=Size-1;
+		return n;
+	}
+	/*}}}1*/
+	/*FUNCTION ListofIntersectionTriangles::NewItem(R2 A,const Metric & mm){{{1*/
+	int ListofIntersectionTriangles::NewItem(R2 A,const Metric & mm) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewItem)*/
+
+		register int n;
+		if(!Size ||  Norme2_2(lIntTria[Size-1].x-A)) {
+			if (Size==MaxSize) ReShape();
+			lIntTria[Size].t=0;
+			lIntTria[Size].x=A;
+			lIntTria[Size].m=mm;
+			n=Size++;
+		}
+		else  n=Size-1;
+		return  n; 
+	}
+	/*}}}1*/
+	/*FUNCTION ListofIntersectionTriangles::NewPoints{{{1*/
+	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 = %g, cy=%g\n",cx,cy);
+
+			si += sint;
+			if ( nbv<maxnbv) {
+				vertices[nbv].r = C;
+				vertices[nbv++].m = Metric(cx,lIntTria[ii-1].m,cy,lIntTria[ii].m);
+			}
+			else return nbv-nbvold;
+		  }
+		return nbv-nbvold;
+	}
+	/*}}}1*/
+	/*FUNCTION ListofIntersectionTriangles::NewSubSeg{{{1*/
+	void  ListofIntersectionTriangles::NewSubSeg(GeomEdge *e,double s0,double s1){ 
+		long int verbosity=0;
+		if (NbSeg>=MaxNbSeg) {
+			int mneo= MaxNbSeg;
+			MaxNbSeg *= 2;
+			if (verbosity>3){
+				printf("   reshape lSegsI from %i to %i\n",mneo,MaxNbSeg);
+			}
+			_assert_(lSegsI && NbSeg<MaxNbSeg);
+			SegInterpolation * lEn =  new SegInterpolation[MaxNbSeg];
+			for (int i=0;i< NbSeg;i++) lEn[i] = lSegsI[MaxNbSeg]; // copy old to new            
+			delete []  lSegsI; // remove old
+			lSegsI = lEn;        
+		}
+		if (NbSeg) lSegsI[NbSeg-1].last=Size;
+		lSegsI[NbSeg].e=e;
+		lSegsI[NbSeg].sBegin=s0;
+		lSegsI[NbSeg].sEnd=s1;     
+		NbSeg++;           
+	}
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::ReShape{{{1*/
+	void ListofIntersectionTriangles::ReShape(){ 
+
+		register int newsize = MaxSize*2;
+		IntersectionTriangles* nw = new IntersectionTriangles[newsize];
+		_assert_(nw);
+
+		// recopy
+		for (int i=0;i<MaxSize;i++) nw[i] = lIntTria[i];       
+		long int verbosity=0;
+		if(verbosity>3) printf("   ListofIntersectionTriangles  ReShape Maxsize %i -> %i\n",MaxSize,MaxNbSeg);
+		MaxSize = newsize; 
+		delete [] lIntTria;// remove old
+		lIntTria = nw; // copy pointer
+	}
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::SplitEdge{{{1*/
+	void ListofIntersectionTriangles::SplitEdge(const Mesh & Bh, const R2 &A,const R2  &B,int nbegin) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ListofIntersectionTriangles)*/
+
+		Triangle *tbegin, *t;
+
+		long int verbose=2;
+		Icoor2 deta[3], deti,detj;
+		double ba[3];
+		int nbt =0,ifirst=-1,ilast;
+		int i0,i1,i2;
+		int ocut,i,j,k=-1;
+		//  int OnAVertices =0;
+		Icoor2 dt[3];
+		I2 a = Bh.R2ToI2(A) ,b= Bh.R2ToI2(B);// compute  the Icoor a,b
+		I2 vi,vj;  
+		int iedge =-1;// not a edge
+
+		if(nbegin)  {// optimisation 
+			// we suppose  knowing the starting  triangle
+			t=tbegin=lIntTria[ilast=(Size-1)].t;
+			if (tbegin->det>=0) 
+			 ifirst = ilast;}  
+		else {// not optimisation 
+			Init();
+			t=tbegin = Bh.TriangleFindFromCoord(a,deta);
+			if( t->det>=0)
+			 ilast=NewItem(t,double(deta[0])/t->det,double(deta[1])/t->det,double(deta[2])/t->det);
+			else 
+			  {// find the nearest boundary edge  of the vertex A
+				// find a edge or such normal projection a the edge IJ is on the edge
+				//   <=> IJ.IA >=0 && IJ.AJ >=0
+				ilast=ifirst;
+				double ba,bb;
+				AdjacentTriangle edge=CloseBoundaryEdge(a,t,ba,bb);
+				BamgVertex & v0 = *edge.EdgeVertex(0), & v1 = *edge.EdgeVertex(1);
+				NewItem(A,Metric(ba,v0,bb,v1));
+				t=edge;
+				// test if the point b is in the same side
+				if (det(v0.i,v1.i,b)>=0) {
+					AdjacentTriangle edge=CloseBoundaryEdge(a,t,ba,bb);
+					BamgVertex & v0 = *edge.EdgeVertex(0), & v1 = *edge.EdgeVertex(1);
+					NewItem(A,Metric(ba,v0,bb,v1));
+					return;
+				}
+			  } // find the nearest boundary edge  of the vertex A
+		} // end not optimisation 
+		if (t->det<0) {  // outside departure
+			while (t->det <0) { // intersection boundary edge and a,b,
+				k=(*t)(0) ?  ((  (*t)(1) ? ( (*t)(2) ? -1 : 2) : 1  )) : 0;
+				if (k<0){
+					_error_("k<0");
+				}
+				ocut = OppositeEdge[k];
+				i=VerticesOfTriangularEdge[ocut][0];
+				j=VerticesOfTriangularEdge[ocut][1];
+				vi=(*t)[i];
+				vj=(*t)[j];
+				deti = bamg::det(a,b,vi);
+				detj = bamg::det(a,b,vj);
+				if (deti>0) // go to  i direction on gamma
+				 ocut = PreviousEdge[ocut];      
+				else if (detj<=0) // go to j direction on gamma
+				 ocut = NextEdge[ocut];         
+				AdjacentTriangle tadj =t->Adj(ocut);
+				t = tadj;
+				iedge= tadj; 
+				if (t == tbegin) { // 
+					double ba,bb;
+					long int verbose=2;
+					AdjacentTriangle edge=CloseBoundaryEdge(a,t,ba,bb);
+					BamgVertex & v0 = *edge.EdgeVertex(0), & v1 = *edge.EdgeVertex(1);
+					NewItem(A,Metric(ba,v0,bb,v1));
+					return;
+				}
+			} //  end while (t->det <0)
+			// theoriticaly we have: deti =<0 and detj>0
+
+			// computation of barycentric coor
+			// test if the point b is on size on t
+			// we revert vi,vj because vi,vj is def in Adj triangle
+			if ( det(vi,vj,b)>=0) {
+				t=tbegin;
+				double ba,bb;
+				AdjacentTriangle edge=CloseBoundaryEdge(b,t,ba,bb);
+				NewItem(B,Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1)));
+				return;
+			}
+			else
+			  {
+				k = OppositeVertex[iedge];
+				i=VerticesOfTriangularEdge[iedge][0];
+				j=VerticesOfTriangularEdge[iedge][1];
+				double dij = detj-deti;
+				if (i+j+k != 0 + 1 +2){
+					_error_("i+j+k != 0 + 1 +2");
+				}
+				ba[j] =  detj/dij;
+				ba[i] = -deti/dij;
+				ba[k] = 0;
+				ilast=NewItem(t,ba[0],ba[1],ba[2]); }
+		}  //  outside departure
+
+
+
+		// recherche the intersection of [a,b] with Bh Mesh.
+		// we know  a triangle ta contening the vertex a
+		// we have 2 case for intersection [a,b] with a edge [A,B] of Bh
+		// 1) the intersection point is in ]A,B[
+		// 2)                        is A or B
+		// first version --- 
+		for (;;) {
+			//    t->Draw();
+			if (iedge < 0) {
+				i0 =0;i1=1;i2=2;
+				dt[0] =bamg::det(a,b,(*t)[0]);
+				dt[1] =bamg::det(a,b,(*t)[1]);
+				dt[2] =bamg::det(a,b,(*t)[2]);}
+			else {
+				i2 = iedge;
+				i0 = NextEdge[i2];
+				i1 = NextEdge[i0]; 
+				dt[VerticesOfTriangularEdge[iedge][0]] = detj;// we revert i,j because
+				dt[VerticesOfTriangularEdge[iedge][1]] = deti;// we take the Triangle by the other side
+				dt[iedge] = det(a,b,(*t)[OppositeVertex[iedge]]);}
+
+				// so we have just to see the transition from - to + of the det0..2 on edge of t
+				// because we are going from a to b
+				if       ((dt[i=VerticesOfTriangularEdge[i0][0]] <  0) &&
+							( dt[j=VerticesOfTriangularEdge[i0][1]] > 0))
+				 ocut =i0;
+				else  if ((dt[i=VerticesOfTriangularEdge[i1][0]] <  0) &&
+							(dt[j=VerticesOfTriangularEdge[i1][1]] >  0))
+				 ocut =i1;
+				else  if ((dt[i=VerticesOfTriangularEdge[i2][0]] <  0) && 
+							(dt[j=VerticesOfTriangularEdge[i2][1]] >  0))
+				 ocut =i2;
+				else if   ((dt[i=VerticesOfTriangularEdge[i0][0]] == 0) &&
+							( dt[j=VerticesOfTriangularEdge[i0][1]] >  0))
+				 ocut =i0;
+				else  if ((dt[i=VerticesOfTriangularEdge[i1][0]] == 0) &&
+							(dt[j=VerticesOfTriangularEdge[i1][1]] >  0))
+				 ocut =i1;
+				else  if ((dt[i=VerticesOfTriangularEdge[i2][0]] == 0) && 
+							(dt[j=VerticesOfTriangularEdge[i2][1]] >  0))
+				 ocut =i2;
+				else if   ((dt[i=VerticesOfTriangularEdge[i0][0]] <  0) &&
+							( dt[j=VerticesOfTriangularEdge[i0][1]] == 0))
+				 ocut =i0;
+				else  if ((dt[i=VerticesOfTriangularEdge[i1][0]] <  0) &&
+							(dt[j=VerticesOfTriangularEdge[i1][1]] == 0))
+				 ocut =i1;
+				else  if ((dt[i=VerticesOfTriangularEdge[i2][0]] <  0) && 
+							(dt[j=VerticesOfTriangularEdge[i2][1]] == 0))
+				 ocut =i2;
+				else { //  On a edge (2 zero)
+					k =0;
+					if (dt[0]) ocut=0,k++; 
+					if (dt[1]) ocut=1,k++; 
+					if (dt[2]) ocut=2,k++;
+					if(k == 1) {
+						if (dt[ocut] >0) // triangle upper AB
+						 ocut = NextEdge[ocut];
+						i= VerticesOfTriangularEdge[ocut][0];
+						j= VerticesOfTriangularEdge[ocut][1];
+					}
+					else {
+						_error_("Bug Split Edge");
+					}
+				}
+
+				k = OppositeVertex[ocut];
+
+				Icoor2 detbij = bamg::det((*t)[i],(*t)[j],b);
+
+
+				if (detbij >= 0) { //we find the triangle contening b
+					dt[0]=bamg::det((*t)[1],(*t)[2],b);
+					dt[1]=bamg::det((*t)[2],(*t)[0],b);
+					dt[2]=bamg::det((*t)[0],(*t)[1],b);
+					double dd = t->det;
+					NewItem(t,dt[0]/dd,dt[1]/dd,dt[2]/dd);      
+					return ;}
+				else { // next triangle by  adjacent by edge ocut 
+					deti = dt[i];
+					detj = dt[j];
+					double dij = detj-deti;
+					ba[i] =  detj/dij;
+					ba[j] = -deti/dij;
+					ba[3-i-j ] = 0;
+					ilast=NewItem(t, ba[0],ba[1],ba[2]);      
+
+					AdjacentTriangle ta =t->Adj(ocut);
+					t = ta;
+					iedge= ta; 
+					if (t->det <= 0)  {
+						double ba,bb;
+						AdjacentTriangle edge=CloseBoundaryEdge(b,t,ba,bb);
+						NewItem(B,Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1)));
+						return;
+					}
+				}// we  go outside of omega 
+		} // for(;;)
+	}
+	/*}}}1*/
+
+}
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/ListofIntersectionTriangles.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/ListofIntersectionTriangles.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/ListofIntersectionTriangles.h	(revision 11330)
@@ -0,0 +1,73 @@
+#ifndef _LISTOFINTERSECTIONTRIANGLES_H_
+#define _LISTOFINTERSECTIONTRIANGLES_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	class Triangle;
+
+	class ListofIntersectionTriangles {
+
+		class IntersectionTriangles {
+
+			public: 
+				Triangle *t;
+				double    bary[3];   // use if t != 0
+				R2        x;
+				Metric    m;
+				double    s;         // curvilinear coordinate
+				double    sp;        // length of the previous segment in m
+				double    sn;        // length of the next segment in m
+		};
+
+		class SegInterpolation {
+
+			public:
+				GeomEdge *e;
+				double           sBegin  ,sEnd; // abscisse of the seg on edge parameter
+				double           lBegin  ,lEnd; // length abscisse set in ListofIntersectionTriangles::Length
+				int              last;          // last index in ListofIntersectionTriangles for this Sub seg of edge
+
+				//Methods
+				R2 F(double s){ 
+					double c01=lEnd-lBegin, c0=(lEnd-s)/c01, c1=(s-lBegin)/c01;
+					if (lBegin>s || s>lEnd){
+						_error_("lBegin>s || s>lEnd");
+					}
+					return e->F(sBegin*c0+sEnd*c1);
+				}
+		};
+
+		public:
+
+			int                    MaxSize;
+			int                    Size;
+			double                 len;
+			int                    state;
+			IntersectionTriangles *lIntTria;
+			int                    NbSeg;
+			int                    MaxNbSeg;
+			SegInterpolation      *lSegsI;
+
+			//Constructors/Destructors
+			ListofIntersectionTriangles(int n=256,int m=16);
+			~ListofIntersectionTriangles();
+
+			//Operators
+			IntersectionTriangles & operator[](int i) {return lIntTria[i];}
+			operator int&() {return Size;}
+
+			//Methods
+			void   Init();
+			int    NewItem(Triangle *tt,double d0,double d1,double d2);
+			int    NewItem(R2 ,const Metric &);
+			void   SplitEdge(const Mesh &,const R2 &,const R2 &,int nbegin=0);
+			double Length();
+			long   NewPoints(BamgVertex *,long &nbv,long maxnbv);
+			void   NewSubSeg(GeomEdge *e,double s0,double s1);
+			void   ReShape();
+	};
+
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Mesh.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Mesh.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Mesh.cpp	(revision 11330)
@@ -0,0 +1,6004 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "../objects.h"
+
+namespace bamg {
+
+	static const  Direction NoDirOfSearch=Direction();
+
+	/*Constructors/Destructors*/
+	/*FUNCTION Mesh::Mesh(BamgGeom* bamggeom,BamgMesh* bamgmesh, BamgOpts* bamgopts){{{1*/
+	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();
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::Mesh(double* index,double* x,double* y,int nods,int nels){{{1*/
+	Mesh::Mesh(double* index,double* x,double* y,int nods,int nels):Gh(*(new Geometry())),BTh(*this){
+
+		Init(0);
+		ReadMesh(index,x,y,nods,nels);
+		SetIntCoor();
+		ReconstructExistingMesh();
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::Mesh(double* x,double* y,int nods){{{1*/
+	Mesh::Mesh(double* x,double* y,int nods):Gh(*(new Geometry())),BTh(*this){
+		Triangulate(x,y,nods);
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::Mesh(const Mesh & Tho,const int *flag ,const int *bb){{{1*/
+	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 %i, remove = %i\n",k,Tho.nbv - k);
+		  printf("   number of triangles %i, remove = %i\n",kt,nbInT-kt);
+		  printf("   number of New boundary edge %i\n",nbNewBedge);
+		  long imaxnbv =k;
+		  Init(imaxnbv);
+		  for (i=0;i<Tho.nbv;i++)
+			if (kk[i]>=0) 
+			  {
+				vertices[nbv] = Tho.vertices[i];
+				if (!vertices[nbv].GetReferenceNumber())
+				 vertices[nbv].ReferenceNumber = refv[i];
+				nbv++;
+			  }
+		  if (imaxnbv != nbv){
+			  delete [] kk;
+			  delete [] refv;
+			  _error_("imaxnbv != nbv");
+		  }
+		  for (i=0;i<Tho.nbt;i++)
+			if(  reft[i] >=0 && flag[i]) 
+			  {
+				const Triangle & t = Tho.triangles[i];
+				int i0 = Tho.GetId(t[0]);
+				int i1 = Tho.GetId(t[1]);
+				int i2 = Tho.GetId(t[2]);
+				if (i0<0 || i1<0 || i2<0){
+					delete [] refv;
+					_error_("i0<0 || i1<0 || i2< 0");
+				}
+				if (i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv){
+					_error_("i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv");
+				}
+				triangles[nbt] = Triangle(this,kk[i0],kk[i1],kk[i2]);
+				triangles[nbt].color = Tho.subdomains[reft[i]].ReferenceNumber; 
+				nbt++;           
+			  }
+		  if (kt!=nbt){
+			  _error_("kt!=nbt");
+		  }
+		  if (nbt==0 && nbv==0) {
+			  _error_("All triangles have been removed");
+		  }
+		  delete [] kk;
+		  delete [] reft;
+		  delete [] refv;
+		  //double cutoffradian = 10.0/180.0*Pi;
+		  BuildGeometryFromMesh(bamgopts);
+		  Gh.PostRead(); 
+		  SetIntCoor();
+		  ReconstructExistingMesh();
+
+		  if (!nbsubdomains){
+			  _error_("nbsubdomains==0");
+		  }
+		  if (!subdomains[0].head || !subdomains[0].head->link){
+			  _error_("!subdomains[0].head || !subdomains[0].head->link");
+		  }
+
+	  }
+	/*}}}1*/
+	/*FUNCTION Mesh::Mesh(Mesh & Th,Geometry * pGh,Mesh * pBth,long maxnbv_in) COPY{{{1*/
+	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;
+
+	  }
+	/*}}}1*/
+	/*FUNCTION Mesh::Mesh(long maxnbv,Mesh & BT,BamgOpts* bamgopts,int keepBackVertices){{{1*/
+	Mesh::Mesh(long imaxnbv,Mesh & BT,BamgOpts* bamgopts,int keepBackVertices) :Gh(BT.Gh),BTh(BT) {
+		this->Init(imaxnbv);
+		TriangulateFromGeom1(bamgopts,keepBackVertices);
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::Mesh(long maxnbv,Geometry & G,BamgOpts* bamgopts){{{1*/
+	Mesh::Mesh(long imaxnbv,Geometry & G,BamgOpts* bamgopts):Gh(G),BTh(*this){
+		Init(imaxnbv);
+		TriangulateFromGeom0(bamgopts);
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::~Mesh(){{{1*/
+	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 
+	}
+	/*}}}1*/
+
+	/*IO*/
+	/*FUNCTION Mesh::ReadMesh(double* index,double* x,double* y,int nods,int nels){{{1*/
+	void Mesh::ReadMesh(double* index,double* x,double* y,int nods,int nels){
+
+		double Hmin = HUGE_VAL;// the infinie value 
+		long i1,i2,i3;
+		long i,j;
+		Metric M1(1);
+		int verbose=0;
+		bool* nodeflags=NULL;
+
+		nbv=nods;
+		maxnbv=nbv;
+		nbt=nels;
+
+		//Vertices
+		if (verbose) printf("Reading vertices (%i)\n",nbv);
+		vertices=(BamgVertex*)xmalloc(nbv*sizeof(BamgVertex));
+		orderedvertices=(BamgVertex**)xmalloc(nbv*sizeof(BamgVertex*));
+		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 (%i)\n",nbt);
+		triangles =new Triangle[maxnbt]; //we cannot allocate only nbt triangles since 
+		nodeflags=(bool*)xmalloc(nbv*sizeof(bool));
+		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 does not belong to any element\n",i+1);
+				isorphan=true;
+			}
+		}
+		if(isorphan) _error_("Orphan found in mesh, see ids above");
+
+		/*Clean up*/
+		xfree((void**)&nodeflags);
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts){{{1*/
+	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=(BamgVertex*)xmalloc(nbv*sizeof(BamgVertex));
+			orderedvertices=(BamgVertex**)xmalloc(nbv*sizeof(BamgVertex*));
+
+			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,iref;
+			triangles =new Triangle[nbt];
+			for (i=0;i<bamgmesh->QuadrilateralsSize[0];i++){
+				//divide the quad into two triangles
+				Triangle & t1 = triangles[2*i];
+				Triangle & t2 = triangles[2*i+1];
+				i1=(long)bamgmesh->Quadrilaterals[i*5+0]-1; //for C indexing
+				i2=(long)bamgmesh->Quadrilaterals[i*5+1]-1; //for C indexing
+				i3=(long)bamgmesh->Quadrilaterals[i*5+2]-1; //for C indexing
+				i4=(long)bamgmesh->Quadrilaterals[i*5+3]-1; //for C indexing
+				t1=Triangle(this,i1,i2,i3);
+				t2=Triangle(this,i3,i4,i1);
+				t1.color=(long)bamgmesh->Quadrilaterals[i*5+4];
+				t2.color=(long)bamgmesh->Quadrilaterals[i*5+4];
+				t1.SetHidden(OppositeEdge[1]); // two times  because the adj was not created 
+				t2.SetHidden(OppositeEdge[1]); 
+			}
+		}
+
+		//VerticesOnGeomEdge
+		if(bamgmesh->VerticesOnGeomEdge){
+			if(verbose>5) 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 %i: [%i %i]) is incorrect (must be positive, [0<i<nbe=%i 0<j<Gh.nbe=%i]",i1+1,i+1,j+1,nbe,Gh.nbe);
+				}
+				edges[i].GeomEdgeHook=Gh.edges+j;
+			}
+		}
+
+		//SubDomain
+		if(bamgmesh->SubDomains){
+			long i3,head,direction;
+			if(verbose>5) printf("      processing SubDomains\n");
+			nbsubdomains=bamgmesh->SubDomainsSize[0];
+			subdomains = new SubDomain [ nbsubdomains ];
+			for (i=0;i<nbsubdomains;i++) {
+				i3  =(int)bamgmesh->SubDomains[i*3+0];
+				head=(int)bamgmesh->SubDomains[i*3+1]-1;//C indexing
+				direction=(int)bamgmesh->SubDomains[i*3+2];
+				if (i3!=23) _error_("Bad Subdomain definition: first number should be 3");
+				if (head<0 || head>=nbt) _error_("Bad Subdomain definition: head should in [1 %i] (triangle number)",nbt);
+				subdomains[i].head = triangles+head;
+			}
+		}
+
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::WriteMesh {{{1*/
+	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=(int*)xmalloc(nbv*sizeof(int));
+		next_1=(int*)xmalloc(3*nbt*sizeof(int));
+		connectivitysize_1=(int*)xmalloc(nbv*sizeof(int));
+
+		//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 = %i, nbt = %i",k,nbt);
+					next_1[k]=head_1[v];
+					if (v>nbv-1 || v<0)   _error_("v = %i, nbv = %i",v,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=(double*)xmalloc(3*nbv*sizeof(double));
+			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=(double*)xmalloc(3*nbe*sizeof(double));
+			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=(double*)xmalloc(3*nbt*sizeof(double));
+		for (i=0;i<3*nbt;i++) elemedge[i]=NAN;
+		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=(double*)xmalloc(4*edge4->nb()*sizeof(double));
+		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;
+		xfree((void**)&elemedge);
+
+		/*IssmSegments*/
+		if(verbose>5) printf("      writing IssmSegments\n");
+		bamgmesh->IssmSegmentsSize[0]=NumIssmSegments;
+		bamgmesh->IssmSegmentsSize[1]=4;
+		bamgmesh->IssmSegments=(double*)xmalloc(4*NumIssmSegments*sizeof(double));
+		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 [%i %i] not found...",i1+1,i2+1);
+				}
+			}
+		}
+
+		/*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=(double*)xmalloc(4*k*sizeof(double));
+			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=(double*)xmalloc(5*nbq*sizeof(double));
+			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=(double*)xmalloc(4*nbsubdomains*sizeof(double));
+			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=(double*)xmalloc(4*Gh.nbsubdomains*sizeof(double));
+			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=(double*)xmalloc(2*NbVerticesOnGeomVertex*sizeof(double));
+			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=(double*)xmalloc(3*NbVerticesOnGeomEdge*sizeof(double));
+			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=(double*)xmalloc(2*(int)k*sizeof(double));
+			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=(double*)xmalloc(3*(nbt-nbtout)*sizeof(double));
+		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=(double*)xmalloc(connectivitymax_1*nbv*sizeof(double));
+		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=(int*)xmalloc(nbv*sizeof(int));
+		next_2=(int*)xmalloc(2*i1*sizeof(int));
+		connectivitysize_2=(int*)xmalloc(nbv*sizeof(int));
+		//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=%i not in [0 %i]",k,2*i1-1);
+				next_2[k]=head_2[v];
+				if (v>nbv-1 || v<0)   _error_("Index exceed matrix dimensions (v=%i not in [0 %i])",v,nbv-1);
+				head_2[v]=k++;
+				connectivitysize_2[v]+=1;
+			}
+		}
+		//Get maximum connectivity
+		for (i=0;i<nbv;i++){
+			if (connectivitysize_2[i]>connectivitymax_2) connectivitymax_2=connectivitysize_2[i];
+		}
+		//Build output
+		bamgmesh->NodalConnectivitySize[0]=nbv;
+		bamgmesh->NodalConnectivitySize[1]=connectivitymax_2;
+		bamgmesh->NodalConnectivity=(double*)xmalloc(connectivitymax_2*nbv*sizeof(double));
+		for (i=0;i<connectivitymax_2*nbv;i++) bamgmesh->NodalConnectivity[i]=NAN;
+		for (i=0;i<nbv;i++){
+			k=0;
+			for(j=head_2[i];j!=-1;j=next_2[j]){
+				_assert_(connectivitymax_2*i+k < connectivitymax_2*nbv);
+				num=(int)bamgmesh->IssmEdges[int(j/2)*i2+0];
+				if (i+1==num){ //carefull, ElementEdge is in M indexing
+					//i is the first vertex of the edge, it is therefore connected to the second vertex
+					bamgmesh->NodalConnectivity[connectivitymax_2*i+k]=bamgmesh->IssmEdges[int(j/2)*i2+1];
+				}
+				else{
+					bamgmesh->NodalConnectivity[connectivitymax_2*i+k]=num;
+				}
+				k++;
+			}
+		}
+
+		/*Cracked vertices*/
+		if(verbose>5) printf("      writing Cracked vertices\n");
+		bamgmesh->CrackedVerticesSize[0]=NbCrackedVertices;
+		bamgmesh->CrackedVerticesSize[1]=2;
+		if (NbCrackedVertices){
+			bamgmesh->CrackedVertices=(double*)xmalloc(2*NbCrackedVertices*sizeof(double));
+			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=(double*)xmalloc(2*NbCrackedEdges*sizeof(double));
+			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
+		xfree((void**)&connectivitysize_1);
+		xfree((void**)&head_1);
+		xfree((void**)&next_1);
+		xfree((void**)&connectivitysize_2);
+		xfree((void**)&head_2);
+		xfree((void**)&next_2);
+		delete [] reft;
+		delete [] numt;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::ReadMetric{{{1*/
+	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;
+				}
+			}
+		}
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::WriteMetric{{{1*/
+	void Mesh::WriteMetric(BamgOpts* bamgopts) {
+		int i;
+		xfree((void**)&bamgopts->metric);
+		bamgopts->metric=(double*)xmalloc(3*nbv*sizeof(double));
+		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;
+		}
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::WriteIndex{{{1*/
+	void Mesh::WriteIndex(int** pindex,int* pnels){
+
+		/*Intermediary*/
+		int i,k,num;
+		int verbose=0;
+
+		/*output*/
+		int* index=NULL;
+
+		/*Get number of triangles*/
+		k=0;
+		for (i=0;i<nbt;i++){
+			Triangle &t=triangles[i];
+			if(t.det>0) k++;
+		}
+
+		if (k){
+			index=(int*)xmalloc(3*k*sizeof(double));
+			num=0;
+			for (i=0;i<nbt;i++){
+				Triangle &t=triangles[i];
+				if (t.det>0 && !(t.Hidden(0)||t.Hidden(1) || t.Hidden(2) )){
+					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=k;
+	}
+	/*}}}1*/
+
+	/*Methods*/
+	/*FUNCTION Mesh::AddGeometryMetric{{{1*/
+	void Mesh::AddGeometryMetric(BamgOpts* bamgopts){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/IntersectGeomMetric)*/
+
+		/*Get options*/
+		int    verbose=bamgopts->verbose;
+		double anisomax =bamgopts->anisomax;
+		double errg     =bamgopts->errg;
+
+		double ss[2]={0.00001,0.99999};
+		double errC = 2*sqrt(2*errg);
+		double hmax = Gh.MaximalHmax();
+		double hmin = Gh.MinimalHmin();
+
+		//check that hmax is positive
+		if (hmax<=0){
+			_error_("hmax<=0");
+		}
+
+		//errC cannot be higher than 1
+		if (errC>1) errC=1;
+
+		//Set all vertices to "on"
+		SetVertexFieldOn();
+
+		//loop over all the vertices on edges
+		for (int  i=0;i<nbe;i++){
+			for (int j=0;j<2;j++){
+
+				BamgVertex V;
+				VertexOnGeom GV;
+				Gh.ProjectOnCurve(edges[i],ss[j],V,GV);
+
+				GeomEdge* eg = GV;
+				double s = GV;
+				R2 tg;
+				double  R1= eg->R1tg(s,tg);
+				double  ht=hmax;
+				// err relative to the length of the edge
+				if (R1>1.0e-20) {  
+					ht = Min(Max(errC/R1,hmin),hmax);
+				}
+				double hn=Min(hmax,ht*anisomax);
+
+				if (ht<=0 || hn<=0){
+					_error_("ht<=0 || hn<=0");
+				}
+				EigenMetric Vp(1/(ht*ht),1/(hn*hn),tg);
+				Metric MVp(Vp);
+				edges[i][j].m.IntersectWith(MVp);
+			}
+		}
+		// the problem is for the vertex on vertex 
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::AddMetric{{{1*/
+	void Mesh::AddMetric(BamgOpts* bamgopts){
+		//  Hessiantype = 0 =>  H is computed using double P2 projection
+		//  Hessiantype = 1 =>  H is computed with green formula
+
+		/*Options*/
+		int Hessiantype=bamgopts->Hessiantype;
+
+		if (Hessiantype==0){
+			BuildMetric0(bamgopts);
+		}
+		else if (Hessiantype==1){
+			BuildMetric1(bamgopts);
+		}
+		else{
+			_error_("Hessiantype %i not supported yet (1->use Green formula, 0-> double P2 projection)",Hessiantype);
+		}
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::AddVertex{{{1*/
+	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");
+			}
+		}
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::BoundAnisotropy{{{1*/
+	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 %g\n",anisomax);
+
+		double h1=1.e30,h2=1e-30;
+		double coef = 1./(anisomax*anisomax);
+		double hn1=1.e30,hn2=1e-30,rnx =1.e-30,rx=0;  
+
+		//loop over all vertices
+		for (int i=0;i<nbv;i++){
+			EigenMetric Vp(vertices[i]);
+			double lmax=Vp.lmax();
+			Vp*=Min(lminaniso,lmax)/lmax;
+			Vp.BoundAniso2(coef);
+			vertices[i].m = Vp;
+
+			//info to be displayed
+			if (verbose>2){
+				h1 =Min(h1,Vp.lmin());
+				h2 =Max(h2,Vp.lmax());
+				hn1=Min(hn1,Vp.lmin());
+				hn2=Max(hn2,Vp.lmax());
+				rx =Max(rx,Vp.Aniso2());
+				rnx= Max(rnx,Vp.Aniso2());
+			}
+		}
+
+		//display info
+		if (verbose>2){
+			printf("      input:  Hmin = %g, Hmax = %g, factor of anisotropy max  = %g\n",pow(h2,-0.5),pow(h1,-0.5),pow(rx,0.5));
+			printf("      output: Hmin = %g, Hmax = %g, factor of anisotropy max  = %g\n",pow(hn2,-0.5),pow(hn1,-0.5),pow(rnx,0.5));
+		}
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::BuildGeometryFromMesh{{{1*/
+	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 %i, nbe4=%i",nbe,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 (%i,%i) belongs to more than 2 triangles (%i)\n",GetId(triangles[i][VerticesOfTriangularEdge[j][0]]),GetId(triangles[i][VerticesOfTriangularEdge[j][1]]),k);
+					printf("Edge %i of triangle %i\n",j,i);
+					printf("Edge %i of triangle %i\n",(-st[k]+2)%3,(-st[k]+2)/3);
+					printf("Edge %i of triangle %i\n",triangles[(-st[k]+2)/3].NuEdgeTriangleAdj((int)((-st[k]+2)%3)),GetId(triangles[(-st[k]+2)/3].TriangleAdj((int)((-st[k]+2)%3))));
+					_error_("An edge belongs to more than 2 triangles");
+				}	
+			}
+		}
+
+		//delete edge4
+		long nbedges = edge4->nb(); // the total number of edges 
+		delete edge4; edge4=NULL;
+
+		//display info
+		if(verbose>5) {
+			printf("         info on Mesh:\n");
+			printf("            - number of vertices    = %i \n",nbv); 
+			printf("            - number of triangles   = %i \n",nbt); 
+			printf("            - number of given edges = %i \n",nbe); 
+			printf("            - number of all edges   = %i \n",nbedges); 
+			printf("            - Euler number 1 - nb of holes = %i \n"  ,nbt-nbedges+nbv); 
+		}
+
+		// check consistency of edge[].adj and geometrical required  vertices
+		k=0; kk=0;
+		for (i=0;i<nbedges;i++){
+			//internal edge
+			if (st[i] <-1) {
+				//get triangle number back
+				it =  (-2-st[i])/3;
+				//get edge position back
+				j  =  (int) ((-2-st[i])%3);
+				Triangle &tt=*triangles[it].TriangleAdj(j);
+				if (triangles[it].color != tt.color|| i < nbeold) k++;
+			}
+			//boundary edge (alone)
+			else if (st[i] >=0) 
+			 kk++;
+		}
+
+		/*Constructions of edges*/
+
+		k += kk;
+		kk=0;
+		if (k) {
+			nbe = k;
+			Edge* edgessave=edges;
+			edges = new Edge[nbe];
+			k =0;
+
+			//display info
+			if(verbose>4) printf("   Construction of the edges %i\n",nbe);
+
+			for (i=0;i<nbedges;i++){ 
+				long  add= -1;
+
+				//internal edge (belongs to two triangles)
+				if (st[i] <-1){ 
+					it =  (-2-st[i])/3;
+					j  =  (int) ((-2-st[i])%3);
+					Triangle & tt = * triangles[it].TriangleAdj(j);
+					if (triangles[it].color !=  tt.color || i < nbeold) add=k++;
+				}
+				//boundary edge
+				else if (st[i] >=0){
+					it = st[i]/3;
+					j  = (int) (st[i]%3);
+					add=k++;
+				}
+				if (add>=0 && add < nbe){
+					edges[add].v[0] = &triangles[it][VerticesOfTriangularEdge[j][0]];
+					edges[add].v[1] = &triangles[it][VerticesOfTriangularEdge[j][1]];
+					edges[add].GeomEdgeHook=NULL; 
+					//if already existed
+					if (i<nbeold){
+						edges[add].ReferenceNumber=edgessave[i].ReferenceNumber; 		      
+						edges[add].GeomEdgeHook=edgessave[i].GeomEdgeHook; //  HACK to get required edges
+						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 = %i\n",nbsubdomains); 
+
+		//build subdomains
+		long isd;
+		subdomains = new SubDomain[nbsubdomains];
+
+		//initialize subdomains[isd].head as 0
+		for (isd=0;isd<nbsubdomains;isd++) subdomains[isd].head =0;
+		  
+		k=0;
+		for (it=0;it<nbt;it++){
+			for (int j=0;j<3;j++){
+				tt=triangles[it].TriangleAdj(j);
+				if ((!tt || tt->color != triangles[it].color) && !subdomains[isd=colorT[it]].head){
+					subdomains[isd].head = triangles+it;
+					subdomains[isd].ReferenceNumber =  triangles[it].color;
+					subdomains[isd].direction = j; // hack
+					subdomains[isd].edge = 0;
+					k++;
+				}
+			}
+		}
+		//check that we have been through all subdomains
+		if (k!= nbsubdomains){
+			delete [] colorT;
+			_error_("k!= nbsubdomains");
+		}
+		//delete colorT and st
+		delete [] colorT;
+		delete [] st;
+
+		/*Reconstruct Geometry Gh*/
+
+		//build colorV -1 for all vertex and 0 for the vertices belonging to edges
+		long* colorV = new long[nbv];
+		for (i=0;i<nbv;i++) colorV[i]=-1;
+		for (i=0;i<nbe;i++){
+		 for ( j=0;j<2;j++) colorV[GetId(edges[i][j])]=0;
+		}
+		//number the vertices belonging to edges
+		k=0;
+		for (i=0;i<nbv;i++){
+		 if(!colorV[i]) colorV[i]=k++;
+		}
+
+		//Build Gh
+		Gh.nbv=k;
+		Gh.nbe = nbe;
+		Gh.vertices = new GeomVertex[k];
+		Gh.edges = new GeomEdge[nbe];
+		Gh.nbsubdomains = nbsubdomains;
+		Gh.subdomains = new GeomSubDomain[nbsubdomains];
+		if (verbose>3) printf("   number of vertices = %i\n   number of edges = %i\n",Gh.nbv,Gh.nbe);
+		NbVerticesOnGeomVertex = Gh.nbv;
+		VerticesOnGeomVertex = new VertexOnGeom[NbVerticesOnGeomVertex];
+		NbVerticesOnGeomEdge =0;
+		VerticesOnGeomEdge =0;
+
+		//Build VertexOnGeom
+		for (i=0;i<nbv;i++){
+			if((j=colorV[i])>=0){
+				BamgVertex & v = Gh.vertices[j];
+				v = vertices[i];
+				v.color =0;
+				VerticesOnGeomVertex[j] = VertexOnGeom(vertices[i], Gh.vertices[j]);
+			}
+		}
+
+		//Buid pmin and pmax of Gh (extrema coordinates)
+		Gh.pmin =  Gh.vertices[0].r;
+		Gh.pmax =  Gh.vertices[0].r;
+		// recherche des extrema des vertices pmin,pmax
+		for (i=0;i<Gh.nbv;i++) {
+			Gh.pmin.x = Min(Gh.pmin.x,Gh.vertices[i].r.x);
+			Gh.pmin.y = Min(Gh.pmin.y,Gh.vertices[i].r.y);
+			Gh.pmax.x = Max(Gh.pmax.x,Gh.vertices[i].r.x);
+			Gh.pmax.y = Max(Gh.pmax.y,Gh.vertices[i].r.y);
+		}
+		R2 DD05 = (Gh.pmax-Gh.pmin)*0.05;
+		Gh.pmin -=  DD05;
+		Gh.pmax +=  DD05;
+
+		//Build Gh.coefIcoor
+		Gh.coefIcoor= (MaxICoor)/(Max(Gh.pmax.x-Gh.pmin.x,Gh.pmax.y-Gh.pmin.y));
+		if (Gh.coefIcoor<=0){
+			delete [] colorV;
+			_error_("Gh.coefIcoor<=0 in infered Geometry (this should not happen)");
+		}
+
+		/*Build Gh.edges*/
+
+		//initialize len as 0
+		double * len = new double[Gh.nbv];
+		for(i=0;i<Gh.nbv;i++) len[i]=0;
+
+		//initialize edge4 again
+		edge4= new SetOfEdges4(nbe,nbv);  
+		double hmin = HUGE_VAL;
+		int kreq=0;
+		for (i=0;i<nbe;i++){
+
+			long i0 = GetId(edges[i][0]);
+			long i1 = GetId(edges[i][1]);
+			long j0 = colorV[i0];
+			long j1 = colorV[i1];
+
+			Gh.edges[i].v[0] = Gh.vertices +  j0;
+			Gh.edges[i].v[1] = Gh.vertices +  j1;
+
+			Gh.edges[i].type = 0;
+
+			Gh.edges[i].tg[0]=R2();
+			Gh.edges[i].tg[1]=R2();
+
+			bool required= edges[i].GeomEdgeHook; 
+			if(required) kreq++;
+			edges[i].GeomEdgeHook =  Gh.edges + i;
+			if(required){
+				Gh.edges[i].v[0]->SetRequired();
+				Gh.edges[i].v[1]->SetRequired();
+				Gh.edges[i].SetRequired();
+			}
+
+			R2 x12 = Gh.vertices[j0].r-Gh.vertices[j1].r;
+			double l12=Norme2(x12);        
+			hmin = Min(hmin,l12);
+
+			Gh.vertices[j1].color++;
+			Gh.vertices[j0].color++;
+
+			len[j0]+= l12;
+			len[j1] += l12;
+			hmin = Min(hmin,l12);
+			Gh.edges[i].ReferenceNumber  = edges[i].ReferenceNumber;
+
+			k = edge4->SortAndAdd(i0,i1);
+			if (k != i){
+				delete [] len;
+				delete [] colorV;
+				_error_("problem in Edge4 construction: k != i");
+			}
+		}
+
+		//Build metric for all vertices of Gh
+		for (i=0;i<Gh.nbv;i++){
+		 if (Gh.vertices[i].color > 0) 
+		  Gh.vertices[i].m=  Metric(len[i] /(double) Gh.vertices[i].color);
+		 else 
+		  Gh.vertices[i].m=  Metric(hmin);
+		}
+		//delete len
+		delete [] len;
+
+		//Build Gh.subdomains
+		for (i=0;i<nbsubdomains;i++){
+			it = GetId(subdomains[i].head);
+			j = subdomains[i].direction;
+			long i0 = GetId(triangles[it][VerticesOfTriangularEdge[j][0]]);
+			long i1 = GetId(triangles[it][VerticesOfTriangularEdge[j][1]]);
+			k = edge4->SortAndFind(i0,i1);
+			if(k>=0){
+				subdomains[i].direction = (vertices + i0 == edges[k].v[0]) ? 1 : -1;
+				subdomains[i].edge = edges+k;
+				Gh.subdomains[i].edge = Gh.edges + k;
+				Gh.subdomains[i].direction  =  subdomains[i].direction;
+				Gh.subdomains[i].ReferenceNumber =  subdomains[i].ReferenceNumber;
+			}
+			else
+			 _error_("%i should be >=0");
+		  }
+
+		delete edge4;
+		delete [] colorV;
+
+		//unset adj
+		for (i=0;i<nbt;i++){
+			for ( j=0;j<3;j++){
+				triangles[i].SetAdj2(j,0,triangles[i].GetAllflag(j));
+			}
+		}
+
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::BuildMetric0 (double P2 projection){{{1*/
+	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 %i rows",nbv);
+
+		//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: %i (nbt=%i, nbv=%i)\n",nbsol,nbt,nbv);
+		}
+
+		//first, build the chains that will be used for the Hessian computation, as weel as the area of each element
+		int* head_s=NULL;
+		head_s=(int*)xmalloc(nbv*sizeof(int));
+		int* next_p=NULL;
+		next_p=(int*)xmalloc(3*nbt*sizeof(int));
+		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 %i, Min = %g, Max = %g, Delta = %g\n",nusol,smin,smax,sdelta);
+
+			//skip constant field
+			if (sdelta < 1.0e-10*Max(absmax,1e-20)){
+				printf("      Solution %i is constant, skipping...\n",nusol);
+				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
+		xfree((void**)&head_s);
+		xfree((void**)&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;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::BuildMetric1 (Green formula){{{1*/
+	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 %i rows",nbv);
+
+		//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: %i (nbt=%i, nbv=%i)\n",nbsol,nbt,nbv);
+		}
+
+		//initialize Mmass, OnBoundary and Massxx by zero
+		for (iv=0;iv<nbv;iv++){
+			Mmass[iv]=0;
+			OnBoundary[iv]=0;
+			Mmassxx[iv]=0;
+		}
+
+		//Build detT Mmas Mmassxx workT and OnBoundary
+		for (i=0;i<nbt;i++){ 
+
+			//lopp over the real triangles (no boundary elements)
+			if(triangles[i].link){ 
+
+				//get current triangle t
+				const Triangle &t=triangles[i];
+
+				// coor of 3 vertices 
+				R2 A=t[0];
+				R2 B=t[1];
+				R2 C=t[2];
+
+				// number of the 3 vertices
+				iA = GetId(t[0]);
+				iB = GetId(t[1]);
+				iC = GetId(t[2]);
+
+				//compute triangle determinant (2*Area)
+				double dett = bamg::Area2(A,B,C);
+				detT[i]=dett;
+				dett /= 6;
+
+				// construction of OnBoundary (flag=1 if on boundary, else 0)
+				int nbb=0;
+				for(int j=0;j<3;j++){
+					//get adjacent triangle
+					Triangle *ta=t.Adj(j);
+					//if there is no adjacent triangle, the edge of the triangle t is on boundary
+					if ( !ta || !ta->link){
+						//mark the two vertices of the edge as OnBoundary
+						OnBoundary[GetId(t[VerticesOfTriangularEdge[j][0]])]=1;
+						OnBoundary[GetId(t[VerticesOfTriangularEdge[j][1]])]=1;
+						nbb++;
+					}
+				}
+
+				//number of vertices on boundary for current triangle t
+				workT[i] = nbb;
+
+				//Build Mmass Mmass[i] = Mmass[i] + Area/3
+				Mmass[iA] += dett;
+				Mmass[iB] += dett;
+				Mmass[iC] += dett;
+
+				//Build Massxx = Mmass
+				Mmassxx[iA] += dett;
+				Mmassxx[iB] += dett;
+				Mmassxx[iC] += dett;
+			}
+
+			//else: the triangle is a boundary triangle -> workT=-1
+			else workT[i]=-1;
+		}
+
+		//for all Solution  
+		for (int nusol=0;nusol<nbsol;nusol++) {
+
+			double smin=ss[nusol],smax=ss[nusol];
+			double h1=1.e30,h2=1e-30,rx=0;
+			double hn1=1.e30,hn2=1e-30,rnx =1.e-30;  
+
+			//get min(s), max(s) and initialize Hessian (dxdx,dxdy,dydy)
+			for ( iv=0,k=0; iv<nbv; iv++ ){
+				dxdx[iv]=dxdy[iv]=dydy[iv]=0;
+				smin=Min(smin,ss[iv*nbsol+nusol]);
+				smax=Max(smax,ss[iv*nbsol+nusol]);
+			}
+			double sdelta=smax-smin;
+			double absmax=Max(Abs(smin),Abs(smax));
+
+			//display info
+			if(verbose>2) printf("      Solution %i, Min = %g, Max = %g, Delta = %g, number of fields = %i\n",nusol,smin,smax,sdelta,nbsol);
+
+			//skip constant field
+			if (sdelta < 1.0e-10*Max(absmax,1e-20) ){
+				if (verbose>2) printf("      Solution %i is constant, skipping...\n",nusol);
+				continue;
+			}
+
+			//pointer toward ss that is also a pointer toward s (solutions)
+			double* sf=ss; 
+
+				//initialize the hessian matrix
+				for ( iv=0,k=0; iv<nbv; iv++) dxdx[iv]=dxdy[iv]=dydy[iv]=0;
+
+				//loop over the triangles
+				for (i=0;i<nbt;i++){
+
+					//for real all triangles 
+					if(triangles[i].link){
+
+						// coor of 3 vertices 
+						R2 A=triangles[i][0];
+						R2 B=triangles[i][1];
+						R2 C=triangles[i][2];
+
+						//warning: the normal is internal and the size is the length of the edge
+						R2 nAB = Orthogonal(B-A);
+						R2 nBC = Orthogonal(C-B);
+						R2 nCA = Orthogonal(A-C);
+						//note that :  nAB + nBC + nCA == 0 
+
+						// number of the 3 vertices
+						iA = GetId(triangles[i][0]);
+						iB = GetId(triangles[i][1]);
+						iC = GetId(triangles[i][2]);
+
+						// for the test of  boundary edge
+						// the 3 adj triangles 
+						Triangle *tBC = triangles[i].TriangleAdj(OppositeEdge[0]);
+						Triangle *tCA = triangles[i].TriangleAdj(OppositeEdge[1]);
+						Triangle *tAB = triangles[i].TriangleAdj(OppositeEdge[2]);
+
+						// value of the P1 fonction on 3 vertices 
+						sA = ss[iA*nbsol+nusol];
+						sB = ss[iB*nbsol+nusol];
+						sC = ss[iC*nbsol+nusol];
+
+						/*The nodal functions are such that for a vertex A:
+						  N_A(x,y)=alphaA x + beta_A y +gamma_A
+						  N_A(A) = 1,   N_A(B) = 0,   N_A(C) = 0
+						  solving this system of equation (determinant = 2Area(T) != 0 if A,B and C are not inlined)
+						  leads to:
+						  N_A = (xB yC - xC yB + x(yB-yC) +y(xC-xB))/(2*Area(T))
+						  and this gives:
+						  alpha_A = (yB-yC)/(2*Area(T))
+						  beta_A = (xC-xB)/(2*Area(T))
+						  and therefore:
+						  grad N_A = nA / detT
+						  for an interpolation of a solution s:
+						  grad(s) = s * sum_{i=A,B,C} grad(N_i) */
+
+						R2 Grads=(nAB*sC+nBC*sA+nCA*sB)/detT[i];
+
+						//Use Green to compute Hessian Matrix
+
+						// if edge on boundary no contribution  => normal = 0
+						if ( !tBC || !tBC->link ) nBC=O;
+						if ( !tCA || !tCA->link ) nCA=O;
+						if ( !tAB || !tAB->link ) nAB=O;
+
+						// remark we forgot a 1/2 because
+						//       int_{edge} w_i = 1/2 if i is in edge 
+						//                         0  if not
+						// if we don't take the  boundary 
+						dxdx[iA] += ( nCA.x + nAB.x ) *Grads.x;
+						dxdx[iB] += ( nAB.x + nBC.x ) *Grads.x;
+						dxdx[iC] += ( nBC.x + nCA.x ) *Grads.x;
+
+						//warning optimization (1) the division by 2 is done on the metric construction
+						dxdy[iA] += (( nCA.y + nAB.y ) *Grads.x + ( nCA.x + nAB.x ) *Grads.y) ;
+						dxdy[iB] += (( nAB.y + nBC.y ) *Grads.x + ( nAB.x + nBC.x ) *Grads.y) ;
+						dxdy[iC] += (( nBC.y + nCA.y ) *Grads.x + ( nBC.x + nCA.x ) *Grads.y) ; 
+
+						dydy[iA] += ( nCA.y + nAB.y ) *Grads.y;
+						dydy[iB] += ( nAB.y + nBC.y ) *Grads.y;
+						dydy[iC] += ( nBC.y + nCA.y ) *Grads.y;
+
+					} // for real all triangles 
+				}
+
+				long kk=0;
+				for ( iv=0,k=0 ; iv<nbv; iv++){
+					if(Mmassxx[iv]>0){
+						dxdx[iv] /= 2*Mmassxx[iv];
+						// warning optimization (1) on term dxdy[iv]*ci/2 
+						dxdy[iv] /= 4*Mmassxx[iv];
+						dydy[iv] /= 2*Mmassxx[iv];
+						// Compute the matrix with abs(eigen value)
+						Metric M(dxdx[iv], dxdy[iv], dydy[iv]);
+						EigenMetric Vp(M);
+						Vp.Abs();
+						M = Vp;
+						dxdx[iv] = M.a11;
+						dxdy[iv] = M.a21;
+						dydy[iv] = M.a22;
+					}
+					else kk++;
+				}
+
+				// correction of second derivative
+				// by a laplacien
+				double* d2[3] = {dxdx, dxdy, dydy};
+				double* dd;
+				for (int xy = 0;xy<3;xy++) {
+					dd = d2[xy];
+					// do leat 2 iteration for boundary problem
+					for (int ijacobi=0;ijacobi<Max(NbJacobi,2);ijacobi++){
+						for (i=0;i<nbt;i++) 
+						 if(triangles[i].link){// the real triangles 
+							 // number of the 3 vertices
+							 iA = GetId(triangles[i][0]);
+							 iB = GetId(triangles[i][1]);
+							 iC = GetId(triangles[i][2]);
+							 double cc=3;
+							 if(ijacobi==0)
+							  cc = Max((double) ((Mmassxx[iA]>0)+(Mmassxx[iB]>0)+(Mmassxx[iC]>0)),1.);
+							 workT[i] = (dd[iA]+dd[iB]+dd[iC])/cc;
+						 }
+						for (iv=0;iv<nbv;iv++) workV[iv]=0;
+
+						for (i=0;i<nbt;i++){ 
+							if(triangles[i].link){ // the real triangles 
+								// number of the 3 vertices
+								iA = GetId(triangles[i][0]);
+								iB = GetId(triangles[i][1]);
+								iC = GetId(triangles[i][2]);
+								double cc =  workT[i]*detT[i];
+								workV[iA] += cc;
+								workV[iB] += cc;
+								workV[iC] += cc;
+							}
+						}
+
+						for (iv=0;iv<nbv;iv++){
+							if( ijacobi<NbJacobi || OnBoundary[iv]){
+								dd[iv] = workV[iv]/(Mmass[iv]*6);
+							}
+						}
+					}
+				}
+
+				/*Compute Metric from Hessian*/
+				for ( iv=0;iv<nbv;iv++){
+					vertices[iv].MetricFromHessian(dxdx[iv],dxdy[iv],dydy[iv],smin,smax,ss[iv*nbsol+nusol],bamgopts->err[nusol],bamgopts);
+				}
+
+		}// end for all solution 
+
+		delete [] detT;
+		delete [] Mmass;
+		delete [] dxdx;
+		delete [] dxdy;
+		delete [] dydy;
+		delete []  workT;
+		delete [] workV;
+		delete [] Mmassxx;
+		delete []  OnBoundary;
+
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::CrackMesh{{{1*/
+	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 = %i\n",k);
+
+		//Initialize Cracked edge
+		NbCrackedEdges=k;
+		CrackedEdges=new CrackedEdge[k];
+
+		//Compute number of Cracked Vertices
+		k=0;
+		NbCrackedVertices=0;
+
+		int* splitvertex=new int[nbv];
+		for (i=0;i<nbv;i++) splitvertex[i]=0;
+
+		for (i=0;i<nbe;i++){
+			if(edges[i].GeomEdgeHook->Cracked()){
+
+				//Fill edges fields of CrackedEdges
+				CrackedEdges[k  ].E =edges[i].GeomEdgeHook;
+				CrackedEdges[k++].e1=&edges[i];
+
+				//Get number of the two vertices on the edge
+				i1=GetId(edges[i][0]);
+				i2=GetId(edges[i][1]);
+				_assert_(i1>=0 && i1<nbv && i2>=0 && i2<nbv);
+				splitvertex[i1]++;
+				splitvertex[i2]++;
+
+				//If the vertex has already been flagged once, it is a cracked vertex (tip otherwise)
+				if (splitvertex[i1]==2) NbCrackedVertices++;
+				if (splitvertex[i2]==2) NbCrackedVertices++;
+
+				//The vertex cannot be marked more than twice
+				if (splitvertex[i1]==3 || splitvertex[i2]==3){
+					delete [] splitvertex;
+					_error_("Crossing rifts not supported yet");
+				}
+			}
+		}
+		_assert_(k==NbCrackedEdges);
+
+		//Add new vertices
+		if (verbose>4) printf("      number of Cracked Vertices = %i\n",NbCrackedVertices);
+		if (NbCrackedVertices){
+			CrackedVertices=(long*)xmalloc(2*NbCrackedVertices*sizeof(double));
+			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("%i -> %i %i %i, edge [%i->%i %i->%i]\n",element_renu[GetId(ta.t)],GetId((*ta.t)[0])+1,GetId((*ta.t)[1])+1,GetId((*ta.t)[2])+1,i1,j1,i2,j2);
+				ta = Next(ta).Adj(); 
+				if (count++>50) _error_("Maximum number of iteration exceeded");
+			}while ((tbegin != ta)); 
+		}
+
+		//Check EdgeFlag
+		for(i=0;i<NbCrackedEdges;i++){
+			if (Edgeflags[i]!=2){
+				_error_("A problem occured: at least one crack edge (number %i) does not belong to 2 elements",i+1);
+			}
+		}
+		delete [] Edgeflags;
+
+		//Reset BamgVertex to On
+		SetVertexFieldOn();
+
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::Echo{{{1*/
+	void Mesh::Echo(void) {
+
+		int i;
+
+		printf("Mesh Echo:\n");
+		printf("   nbv = %i\n",nbv);
+		printf("   nbt = %i\n",nbt);
+		printf("   nbe = %i\n",nbe);
+		printf("   nbq = %i\n",nbq);
+		printf("   index:\n");
+		for (i=0;i<nbt;i++){
+			printf("   %4i: [%4i %4i %4i]\n",i+1,
+						((BamgVertex *)triangles[i](0))?GetId(triangles[i][0])+1:0,
+						((BamgVertex *)triangles[i](1))?GetId(triangles[i][1])+1:0,
+						((BamgVertex *)triangles[i](2))?GetId(triangles[i][2])+1:0);
+		}
+		printf("   coordinates:\n");
+		for (i=0;i<nbv;i++){
+			printf("   %4i: [%g %g]\n",i+1,vertices[i].r.x,vertices[i].r.y);
+		}
+
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::ForceBoundary{{{1*/
+		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: %i\n",nbe);
+
+			//check that there is no triangle with 0 determinant
+			for (int t = 0; t < nbt; t++){
+				if (!triangles[t].det) k++;
+			}
+			if (k!=0) {
+				_error_("there is %i triangles of mes = 0",k);
+			}
+
+			//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=%i,v1=%i",i,GetId(edges[i][0]),GetId(edges[i][1]));
+				}
+			}
+
+			if (k!=0) {
+				_error_("There are %i lost edges, the boundary might be crossing",k);
+			}
+			for (int j=0;j<nbv;j++){
+				Nbswap +=  vertices[j].Optim(1,0);
+			}
+			if (verbose > 3) printf("      number of inforced edge = %i, number of swap= %i\n",nbfe,Nbswap); 
+		}
+	/*}}}1*/
+	/*FUNCTION Mesh::FindSubDomain{{{1*/
+	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) = %i\n",nbsubdomains-j);
+							nbsubdomains=j;
+						  }
+
+						delete []  mark; 
+
+			  }
+			else
+			  { // find the head for all sub domaine
+				if (Gh.nbsubdomains != nbsubdomains && subdomains)
+				 delete [] subdomains, subdomains=0;
+				if (! subdomains  ) 
+				 subdomains = new SubDomain[ Gh.nbsubdomains];
+				nbsubdomains =Gh.nbsubdomains;
+				long err=0;
+				CreateSingleVertexToTriangleConnectivity();
+				long * mark = new long[nbt];
+				Edge **GeomEdgetoEdge = MakeGeomEdgeToEdge();
+
+				for (it=0;it<nbt;it++)
+				 mark[it]=triangles[it].link ? -1 : -2;
+				long inew =0;
+				for (int i=0;i<nbsubdomains;i++) {
+					GeomEdge &eg = *Gh.subdomains[i].edge;
+					subdomains[i].ReferenceNumber = Gh.subdomains[i].ReferenceNumber;
+					int ssdlab = subdomains[i].ReferenceNumber;
+					// by carefull is not easy to find a edge create from a GeomEdge 
+					// see routine MakeGeomEdgeToEdge
+					Edge &e = *GeomEdgetoEdge[Gh.GetId(eg)];
+					_assert_(&e);
+					BamgVertex * v0 =  e(0),*v1 = e(1);
+					Triangle *t  = v0->t;
+					int direction = Gh.subdomains[i].direction;
+					// test if ge and e is in the same direction 
+					if (((eg[0].r-eg[1].r),(e[0].r-e[1].r))<0) direction = -direction ;
+					subdomains[i].direction = direction;
+					subdomains[i].edge = &e;
+					_assert_(t && direction);
+
+					AdjacentTriangle  ta(t,EdgesVertexTriangle[v0->IndexInTriangle][0]);// previous edges
+
+					while (1) {
+						_assert_(v0==ta.EdgeVertex(1));
+						if (ta.EdgeVertex(0) == v1) { // ok we find the edge
+							if (direction>0)  
+							 subdomains[i].head=t=Adj(ta);
+							else 
+							 subdomains[i].head=t=ta;
+							if(t<triangles || t >= triangles+nbt || t->det < 0 || t->link == 0) {
+								_error_("bad definition of SubSomain %i",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",i);
+						}
+					}
+				}
+
+				if (inew < nbsubdomains) {
+					if (verbose>5) printf("WARNING: %i SubDomains are being removed\n",nbsubdomains-inew);
+					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++;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::GetId(const Triangle & t) const{{{1*/
+	long Mesh::GetId(const Triangle & t) const  { 
+		return &t - triangles;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::GetId(const Triangle * t) const{{{1*/
+	long Mesh::GetId(const Triangle * t) const  { 
+		return t - triangles;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::GetId(const BamgVertex & t) const{{{1*/
+	long Mesh::GetId(const BamgVertex & t) const  { 
+		return &t - vertices;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::GetId(const BamgVertex * t) const{{{1*/
+	long Mesh::GetId(const BamgVertex * t) const  { 
+		return t - vertices;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::GetId(const Edge & t) const{{{1*/
+	long Mesh::GetId(const Edge & t) const  { 
+		return &t - edges;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::GetId(const Edge * t) const{{{1*/
+	long Mesh::GetId(const Edge * t) const  { 
+		return t - edges;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::Init{{{1*/
+	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;
+		} 
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::Insert{{{1*/
+	void Mesh::Insert() {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Insert)*/
+
+		/*Insert points in the existing Geometry*/
+
+		//Intermediary
+		int i;
+
+		/*Get options*/
+		long int verbose=2;
+
+		//Display info
+		if (verbose>2) printf("   Insert initial %i vertices\n",nbv);
+
+		//Compute integer coordinates for the existing vertices
+		SetIntCoor();
+
+		/*Now we want to build a list (orderedvertices) of the vertices in a random
+		 * order. To do so, we use the following method:
+		 *
+		 * From an initial k0 in [0 nbv[ random (vertex number)
+		 * the next k (vertex number) is computed using a big
+		 * prime number (PN>>nbv) following:
+		 *
+		 * k_{i+1} = k_i + PN  [nbv]
+		 *
+		 * let's show that:
+		 *
+		 *   for all j in [0 nbv[, ∃! i in [0 nbv[ such that k_i=j
+		 *
+		 * Let's assume that there are 2 distinct j1 and j2 such that
+		 * k_j1 = k_j2
+		 *
+		 * This means that
+		 *  
+		 *  k0+j1*PN = k0+j2*PN [nbv]
+		 *  (j1-j2)*PN =0       [nbv]
+		 * since PN is a prime number larger than nbv, and nbv!=1
+		 *  j1-j2=0             [nbv]
+		 * BUT
+		 *  j1 and j2 are in [0 nbv[ which is impossible.
+		 *
+		 *  We hence have built a random list of nbv elements of
+		 *  [0 nbv[ all distincts*/
+
+		//Get Prime number
+		const long PrimeNumber= BigPrimeNumber(nbv);
+		int   k0=rand()%nbv; 
+
+		//Build orderedvertices
+		for (i=0; i<nbv; i++){
+			orderedvertices[i]=&vertices[k0=(k0+PrimeNumber)%nbv];
+		}
+
+		/*Modify orderedvertices such that the first 3 vertices form a triangle*/
+
+		//get first vertex i such that [0,1,i] are not aligned
+		for (i=2; det(orderedvertices[0]->i,orderedvertices[1]->i,orderedvertices[i]->i)==0;){
+			//if i is higher than nbv, it means that all the determinants are 0,
+			//all vertices are aligned!
+			if  (++i>=nbv) _error_("all the vertices are aligned");
+		}
+		// exchange i et 2 in "orderedvertices" so that
+		// the first 3 vertices are not aligned (real triangle)
+		Exchange(orderedvertices[2], orderedvertices[i]);
+
+		/*Take the first edge formed by the first two vertices and build
+		 * the initial simple mesh from this edge and 2 boundary triangles*/
+
+		BamgVertex *v0=orderedvertices[0], *v1=orderedvertices[1];
+
+		nbt = 2;
+		triangles[0](0) = NULL;//infinite vertex
+		triangles[0](1) = v0;
+		triangles[0](2) = v1;
+		triangles[1](0) = NULL;//infinite vertex
+		triangles[1](2) = v0;
+		triangles[1](1) = v1;
+
+		//Build adjacence
+		const int e0 = OppositeEdge[0];
+		const int e1 = NextEdge[e0];
+		const int e2 = PreviousEdge[e0];
+		triangles[0].SetAdj2(e0, &triangles[1] ,e0);
+		triangles[0].SetAdj2(e1, &triangles[1] ,e2);
+		triangles[0].SetAdj2(e2, &triangles[1] ,e1);
+
+		triangles[0].det = -1;  //boundary triangle: det = -1
+		triangles[1].det = -1;  //boundary triangle: det = -1
+
+		triangles[0].SetSingleVertexToTriangleConnectivity();
+		triangles[1].SetSingleVertexToTriangleConnectivity();
+
+		triangles[0].link=&triangles[1];
+		triangles[1].link=&triangles[0];
+
+		//build quadtree
+		if (!quadtree)  quadtree = new QuadTree(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: %i\n",NbSwap);
+			printf("      NbSwap/nbv:          %i\n",NbSwap/nbv);
+		}
+
+#ifdef NBLOOPOPTIM
+
+		k0 = rand()%nbv ; 
+		for (int is4=0; is4<nbv; is4++) 
+		 orderedvertices[is4]= &vertices[k0 = (k0 + PrimeNumber)% nbv];
+
+		for(int Nbloop=0;Nbloop<NBLOOPOPTIM;Nbloop++){
+			long  NbSwap = 0;
+			for (int is1=0; is1<nbv; is1++) 
+			 NbSwap += orderedvertices[is1]->Optim(0,0);
+			if (verbose>3) {
+				printf("      Optim Loop: %i\n",Nbloop);
+				printf("      NbSwap/nbv:          %i\n",NbSwap/nbv);
+			}
+			if(!NbSwap) break;
+		}
+		CreateSingleVertexToTriangleConnectivity(); 
+		// because we break the TriangleContainingTheVertex
+#endif
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::InsertNewPoints{{{1*/
+	long Mesh::InsertNewPoints(long nbvold,long & NbTSwap) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/InsertNewPoints)*/
+
+		long int verbose=0;
+		double seuil= 1.414/2 ;// for two close point 
+		long i;
+		long NbSwap=0;
+		Icoor2 det3[3];
+
+		//number of new points
+		const long nbvnew=nbv-nbvold;
+
+		//display info if required
+		if (verbose>5) printf("      Try to Insert %i new points\n",nbvnew);
+
+		//return if no new points
+		if (!nbvnew) return 0; 
+
+		/*construction of a random order*/
+		const long PrimeNumber= BigPrimeNumber(nbv)  ;
+		//remainder of the division of rand() by nbvnew
+		long k3 = rand()%nbvnew;
+		//loop over the new points
+		for (int is3=0; is3<nbvnew; is3++){
+			register long j=nbvold +(k3 = (k3+PrimeNumber)%nbvnew);
+			register long i=nbvold+is3; 
+			orderedvertices[i]= vertices + j;
+			orderedvertices[i]->ReferenceNumber=i;
+		}
+
+		// for all the new point
+		long iv=nbvold;
+		for (i=nbvold;i<nbv;i++){
+			BamgVertex &vi=*orderedvertices[i];
+			vi.i=R2ToI2(vi.r);
+			vi.r=I2ToR2(vi.i);
+			double hx,hy;
+			vi.m.Box(hx,hy);
+			Icoor1 hi=(Icoor1) (hx*coefIcoor),hj=(Icoor1) (hy*coefIcoor);
+			if (!quadtree->ToClose(vi,seuil,hi,hj)){
+				// a good new point 
+				BamgVertex &vj = vertices[iv];
+				long  j=vj.ReferenceNumber; 
+				if (&vj!=orderedvertices[j]){
+					_error_("&vj!= orderedvertices[j]");
+				}
+				if(i!=j){ 
+					Exchange(vi,vj);
+					Exchange(orderedvertices[j],orderedvertices[i]);
+				}
+				vj.ReferenceNumber=0; 
+				Triangle *tcvj=TriangleFindFromCoord(vj.i,det3);
+				if (tcvj && !tcvj->link){
+					tcvj->Echo();
+					_error_("problem inserting point in InsertNewPoints (tcvj=%p and tcvj->link=%i)",tcvj,tcvj->link);
+				}
+				quadtree->Add(vj);
+				AddVertex(vj,tcvj,det3);
+				NbSwap += vj.Optim(1);          
+				iv++;
+			}
+		} 
+		if (verbose>3) {
+			printf("         number of new points: %i\n",iv);
+			printf("         number of to close (?) points: %i\n",nbv-iv);
+			printf("         number of swap after: %i\n",NbSwap);
+		}
+		nbv = iv;
+
+		for (i=nbvold;i<nbv;i++) NbSwap += vertices[i].Optim(1);  
+		if (verbose>3) printf("   NbSwap=%i\n",NbSwap);
+
+		NbTSwap +=  NbSwap ;
+		return nbv-nbvold;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::isCracked{{{1*/
+	int Mesh::isCracked() const {
+		return NbCrackedVertices != 0;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::MakeGeomEdgeToEdge{{{1*/
+	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",i);
+			}
+		}
+		if(kk) _error_("See above");
+
+		return e;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::MakeQuadrangles{{{1*/
+	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 = %g\n",costheta);
+
+		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    = %i\n",nbq);
+				printf("   number of triangles         = %i\n",nbt-nbtout- nbq*2);
+				printf("   number of outside triangles = %i\n",nbtout);
+			}
+			delete [] qq;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::MakeQuadTree{{{1*/
+	void Mesh::MakeQuadTree() {  
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MakeQuadTree)*/
+
+		long int verbose=0;
+		if (  !quadtree )  quadtree = new QuadTree(this);
+
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::MaxinalHmax{{{1*/
+	double Mesh::MaximalHmax() {
+		return Max(pmax.x-pmin.x,pmax.y-pmin.y);
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::MaxSubDivision{{{1*/
+	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 %g\n",maxsubdiv);
+		// for all the edges 
+		// if the len of the edge is to long 
+		long it,nbchange=0;    
+		double lmax=0;
+		for (it=0;it<nbt;it++){
+			Triangle &t=triangles[it];
+			for (int j=0;j<3;j++){
+				Triangle &tt = *t.TriangleAdj(j);
+				if ( ! &tt ||  it < GetId(tt) && ( tt.link || t.link)){
+					BamgVertex &v0 = t[VerticesOfTriangularEdge[j][0]];
+					BamgVertex &v1 = t[VerticesOfTriangularEdge[j][1]];
+					R2 AB= (R2) v1-(R2) v0;
+					Metric M = v0;
+					double l = M(AB,AB);
+					lmax = Max(lmax,l);
+					if(l> maxsubdiv2){
+					  R2 AC = M.Orthogonal(AB);// the ortogonal vector of AB in M
+						double lc = M(AC,AC);
+						D2xD2 Rt(AB,AC);// Rt.x = AB , Rt.y = AC;
+						D2xD2 Rt1(Rt.inv());
+						D2xD2 D(maxsubdiv2,0,0,lc);
+						D2xD2 MM = Rt1*D*Rt1.t();
+						v0.m =  M = Metric(MM.x.x,MM.y.x,MM.y.y);
+						nbchange++;
+					}
+					M = v1;
+					l = M(AB,AB);
+					lmax = Max(lmax,l);
+					if(l> maxsubdiv2){
+					  R2 AC = M.Orthogonal(AB);// the ortogonal vector of AB in M
+						double lc = M(AC,AC);
+						D2xD2 Rt(AB,AC);// Rt.x = AB , Rt.y = AC;
+						D2xD2 Rt1(Rt.inv());
+						D2xD2 D(maxsubdiv2,0,0,lc);
+						D2xD2  MM = Rt1*D*Rt1.t();
+						v1.m =  M = Metric(MM.x.x,MM.y.x,MM.y.y);
+						nbchange++;
+					}
+				}
+			}
+		}
+		if(verbose>3){
+			printf("      number of metric changes = %i, maximum number of subdivision of a edges before change = %g\n",nbchange,pow(lmax,0.5));
+		}
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::MetricAt{{{1*/
+	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]);
+		}
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::MininalHmin{{{1*/
+	double Mesh::MinimalHmin() {
+		return 2.0/coefIcoor;
+	}
+	/*}}}1*/
+/*FUNCTION Mesh::NearestVertex{{{1*/
+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); 
+} 
+/*}}}1*/
+	/*FUNCTION Mesh::NewPoints{{{1*/
+	void  Mesh::NewPoints(Mesh & Bh,BamgOpts* bamgopts,int KeepVertices){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewPoints)*/
+
+		int i,j,k;
+		long NbTSwap=0;
+		long nbtold=nbt;
+		long nbvold=nbv;
+		long Headt=0;
+		long next_t;
+		long* first_np_or_next_t=new long[maxnbt];
+		Triangle* t=NULL;
+
+		/*Recover options*/
+		int verbose=bamgopts->verbose;
+
+		/*First, insert old points if requested*/
+		if (KeepVertices && (&Bh != this) && (nbv+Bh.nbv< maxnbv)){
+			if (verbose>5) printf("         Inserting initial mesh points\n");
+			for (i=0;i<Bh.nbv;i++){ 
+				BamgVertex &bv=Bh[i];
+				if (!bv.GeomEdgeHook){
+					vertices[nbv].r   = bv.r;
+					vertices[nbv++].m = bv.m;
+				}
+			}
+			Bh.CreateSingleVertexToTriangleConnectivity();     
+			InsertNewPoints(nbvold,NbTSwap)   ;            
+		}  
+		else Bh.CreateSingleVertexToTriangleConnectivity();     
+
+		// generation of the list of next Triangle 
+		for(i=0;i<nbt;i++) first_np_or_next_t[i]=-(i+1);
+		// the next traingle of i is -first_np_or_next_t[i]
+
+		// Big loop (most time consuming)
+		int iter=0;
+		if (verbose>5) printf("         Big loop\n");
+		do {
+			/*Update variables*/
+			iter++;
+			nbtold=nbt;
+			nbvold=nbv;
+
+			/*We test all triangles*/
+			i=Headt;
+			next_t=-first_np_or_next_t[i];
+			for(t=&triangles[i];i<nbt;t=&triangles[i=next_t],next_t=-first_np_or_next_t[i]){
+
+				//check i
+				if (i<0 || i>=nbt ){
+					_error_("Index problem in NewPoints (i=%i not in [0 %i])",i,nbt-1);
+				}
+				//change first_np_or_next_t[i]
+				first_np_or_next_t[i] = iter; 
+
+				//Loop over the edges of t
+				for(j=0;j<3;j++){
+					AdjacentTriangle tj(t,j);
+					BamgVertex &vA = *tj.EdgeVertex(0);
+					BamgVertex &vB = *tj.EdgeVertex(1);
+
+					//if t is a boundary triangle, or tj locked, continue
+					if (!t->link)     continue;
+					if (t->det <0)    continue;
+					if (t->Locked(j)) continue;
+
+					AdjacentTriangle tadjj = t->Adj(j);	  
+					Triangle* ta=tadjj;
+
+					//if the adjacent triangle is a boundary triangle, continur
+					if (ta->det<0) continue;	  
+
+					R2 A=vA;
+					R2 B=vB;
+					k=GetId(ta);
+
+					//if this edge has already been done, go to next edge of triangle
+					if(first_np_or_next_t[k]==iter) continue;
+
+					lIntTria.SplitEdge(Bh,A,B);
+					lIntTria.NewPoints(vertices,nbv,maxnbv);
+				  } // end loop for each edge 
+			  }// for triangle   
+
+			if (!InsertNewPoints(nbvold,NbTSwap)) break;
+			for (i=nbtold;i<nbt;i++) first_np_or_next_t[i]=iter;
+			Headt = nbt; // empty list 
+
+			// for all the triangle containing the vertex i
+			for (i=nbvold;i<nbv;i++){ 
+				BamgVertex*          s  = vertices + i;
+				AdjacentTriangle ta(s->t, EdgesVertexTriangle[s->IndexInTriangle][1]);
+				Triangle*        tbegin= (Triangle*) ta;
+				long kt;
+				do { 
+					kt = GetId((Triangle*) ta);
+					if (first_np_or_next_t[kt]>0){
+						first_np_or_next_t[kt]=-Headt;
+						Headt=kt;
+					}
+					if (ta.EdgeVertex(0)!=s){
+						_error_("ta.EdgeVertex(0)!=s");
+					}
+					ta = Next(Adj(ta));
+				} while ( (tbegin != (Triangle*) ta)); 
+			}
+
+		} while (nbv!=nbvold);
+
+		delete []  first_np_or_next_t;
+
+		long NbSwapf =0,NbSwp;
+
+		NbSwp = NbSwapf;
+		for (i=0;i<nbv;i++)
+		 NbSwapf += vertices[i].Optim(0);
+		NbTSwap +=  NbSwapf ;
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::ProjectOnCurve{{{1*/
+	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 %i forget call to SetVertexFieldOnBTh",BTh.GetId(vA));
+		} 
+
+		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 %i forget call to SetVertexFieldOnBTh",BTh.GetId(vB));
+		} 
+		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 
+	}                  
+	/*}}}1*/
+/*FUNCTION Mesh::ReconstructExistingMesh{{{1*/
+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 %i vertices\n",nbv); 
+
+	//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 %i double edges in the mesh",kk-nbe);
+	}
+
+	//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 (%i , %i) belongs to more than 2 triangles",GetId(triangles[i][VerticesOfTriangularEdge[j][0]]),GetId(triangles[i][VerticesOfTriangularEdge[j][1]]));
+			}
+		}
+	}
+
+	//Display info if required
+	if(verbose>5) {
+		printf("         info of Mesh:\n");
+		printf("            - number of vertices    = %i \n",nbv); 
+		printf("            - number of triangles   = %i \n",nbt); 
+		printf("            - number of given edges = %i \n",nbe); 
+		printf("            - number of all edges   = %i \n"  ,edge4->nb()); 
+		printf("            - Euler number 1 - nb of holes = %i \n"  ,nbt-edge4->nb()+nbv); 
+	}
+
+	//check the consistency of edge[].adj and the geometrical required vertex
+	long k=0;
+	for (i=0;i<edge4->nb();i++){
+		if (st[i]>=0){ // edge alone 
+			if (i<nbe){
+				long i0=edge4->i(i);
+				orderedvertices[i0] = vertices+i0;
+				long i1=edge4->j(i);
+				orderedvertices[i1] = vertices+i1;
+			}
+			else {
+				k=k+1;
+				if (k<10) {
+					//print only 10 edges
+					printf("Lost boundary edges %i : %i %i\n",i,edge4->i(i),edge4->j(i));
+				}
+				else if (k==10){
+					printf("Other lost boundary edges not shown...\n");
+				}
+			}
+		}
+	}
+	if(k) {
+		_error_("%i boundary edges (from the geometry) are not defined as mesh edges",k);
+	}
+
+	/* 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 QuadTree(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 %i existing edges other %i",nbloss,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 = %i",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: [%i %i]\n",i+1,GetId(edges[i][0])+1,GetId(edges[i][1])+1);
+						printf("This edge is on geometrical edge number %i\n",Gh.GetId(edges[i].GeomEdgeHook)+1);
+						if (edges[i][j].GeomEdgeHook->OnGeomVertex())
+						 printf("the vertex number %i of this edge is a geometric BamgVertex number %i\n",GetId(edges[i][j])+1,Gh.GetId(edges[i][j].GeomEdgeHook->gv)+1);
+						else if (edges[i][j].GeomEdgeHook->OnGeomEdge())
+						 printf("the vertex number %i of this edge is a geometric Edge number %i\n",GetId(edges[i][j])+1,Gh.GetId(edges[i][j].GeomEdgeHook->ge)+1);
+						else
+						 printf("Its pointer is %p\n",edges[i][j].GeomEdgeHook);
+
+						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...)");
+					}
+				}
+			}
+		}
+	}
+}
+/*}}}1*/
+	/*FUNCTION Mesh::TrianglesRenumberBySubDomain{{{1*/
+	void Mesh::TrianglesRenumberBySubDomain(bool justcompress){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ReNumberingTheTriangleBySubDomain)*/
+
+		long int verbose=0;
+		long *renu= new long[nbt];
+		register Triangle *t0,*t,*te=triangles+nbt;
+		register long k=0,it,i,j;
+
+		for ( it=0;it<nbt;it++) 
+		 renu[it]=-1; // outside triangle 
+		for ( i=0;i<nbsubdomains;i++)
+		  { 
+			t=t0=subdomains[i].head;
+			if (!t0){ // not empty sub domain
+				_error_("!t0");
+			}
+			do { 
+				long kt = GetId(t);
+				if (kt<0 || kt >= nbt ){
+					_error_("kt<0 || kt >= nbt");
+				}
+				if (renu[kt]!=-1){
+					_error_("renu[kt]!=-1");
+				}
+				renu[kt]=k++;
+			}
+			while (t0 != (t=t->link));
+		  }
+		// take is same numbering if possible    
+		if(justcompress)
+		 for ( k=0,it=0;it<nbt;it++) 
+		  if(renu[it] >=0 ) 
+			renu[it]=k++;
+
+		// put the outside triangles at the end
+		for ( it=0;it<nbt;it++){
+			if (renu[it]==-1) renu[it]=k++;
+		}
+		if (k != nbt){
+			_error_("k != nbt");
+		}
+		// do the change on all the pointeur 
+		for ( it=0;it<nbt;it++)
+		 triangles[it].Renumbering(triangles,te,renu);
+
+		for ( i=0;i<nbsubdomains;i++)
+		 subdomains[i].head=triangles+renu[GetId(subdomains[i].head)];
+
+		// move the Triangles  without a copy of the array 
+		// be carefull not trivial code 
+		for ( it=0;it<nbt;it++) // for all sub cycles of the permutation renu
+		 if (renu[it] >= 0) // a new sub cycle
+			{ 
+			 i=it;
+			 Triangle ti=triangles[i],tj;
+			 while ( (j=renu[i]) >= 0) 
+				{ // i is old, and j is new 
+				 renu[i] = -1; // mark 
+				 tj = triangles[j]; // save new
+				 triangles[j]= ti; // new <- old
+				 i=j;     // next 
+				 ti = tj;
+				}  
+			}
+		delete [] renu;
+
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::VerticesRenumber{{{1*/
+	void Mesh::VerticesRenumber(long * renu) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ReNumberingVertex)*/
+
+		// warning be carfull because pointer
+		// from on mesh to over mesh 
+		//  --  so do ReNumbering at the beginning
+		BamgVertex * ve = vertices+nbv;
+		long it,ie,i;
+
+		printf("renumbering triangles\n");
+		for ( it=0;it<nbt;it++) 
+		 triangles[it].Renumbering(vertices,ve,renu);
+
+		printf("renumbering edges\n");
+		for ( ie=0;ie<nbe;ie++) 
+		 edges[ie].Renumbering(vertices,ve,renu);
+
+		printf("renumbering vertices on geom\n");
+		for (i=0;i< NbVerticesOnGeomVertex;i++)
+		  {
+			BamgVertex *v = VerticesOnGeomVertex[i].meshvertex;
+			if (v>=vertices && v < ve)
+			 VerticesOnGeomVertex[i].meshvertex=vertices+renu[GetId(v)];
+		  }
+
+		printf("renumbering vertices on edge\n");
+		for (i=0;i< NbVerticesOnGeomEdge;i++)
+		  {
+			BamgVertex *v =VerticesOnGeomEdge[i].meshvertex;
+			if (v>=vertices && v < ve)
+			 VerticesOnGeomEdge[i].meshvertex=vertices+renu[GetId(v)];
+		  }
+
+		printf("renumbering vertices on Bth vertex\n");
+		for (i=0;i< NbVertexOnBThVertex;i++)
+		  {
+			BamgVertex *v=VertexOnBThVertex[i].v;
+			if (v>=vertices && v < ve)
+			 VertexOnBThVertex[i].v=vertices+renu[GetId(v)];
+		  }
+
+		for (i=0;i< NbVertexOnBThEdge;i++)
+		  {
+			BamgVertex *v=VertexOnBThEdge[i].v;
+			if (v>=vertices && v < ve)
+			 VertexOnBThEdge[i].v=vertices+renu[GetId(v)];
+		  }
+
+		// move the Vertices without a copy of the array 
+		// be carefull not trivial code 
+		long j;
+		for ( it=0;it<nbv;it++) // for all sub cycles of the permutation renu
+		 if (renu[it] >= 0) // a new sub cycle
+			{ 
+			 i=it;
+			 BamgVertex ti=vertices[i],tj;
+			 while ( (j=renu[i]) >= 0){
+				 // i is old, and j is new 
+				 renu[i] = -1-renu[i]; // mark 
+				 tj = vertices[j];     // save new
+				 vertices[j]= ti;      // new <- old
+				 i=j;     // next 
+				 ti = tj;
+				}  
+			}
+		if (quadtree){
+			delete quadtree;
+			quadtree = new QuadTree(this);
+		}
+
+		for ( it=0;it<nbv;it++) renu[i]= -renu[i]-1;
+	}
+	/*}}}1*/
+/*FUNCTION Mesh::SetIntCoor{{{1*/
+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 < 0 (det=%i)\n",i+1,triangles[i].det);
+				}
+			}
+		}
+
+		//else, set as -1
+		else triangles[i].det=-1;
+	}
+
+	if (number_of_errors) _error_("Fatal error: some triangles have negative areas, see above");
+}
+/*}}}1*/
+/*FUNCTION Mesh::ShowRegulaty{{{1*/
+void  Mesh::ShowRegulaty() const {
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr>*/
+
+	const  double  sqrt32=sqrt(3.)*0.5; 
+	const double  aireKh=sqrt32*0.5;
+	D2  Beq(1,0),Heq(0.5,sqrt32);
+	D2xD2 Br(D2xD2(Beq,Heq).t());
+	D2xD2 B1r(Br.inv());
+	double gammamn=1e100,hmin=1e100;
+	double gammamx=0,hmax=0;
+	double beta=1e100;
+	double beta0=0;
+	double  alpha2=0;
+	double area=0,Marea=0;
+	// double cf= double(coefIcoor);
+	// double cf2= 6.*cf*cf;
+	int nt=0;
+	for (int it=0;it<nbt;it++)
+	 if ( triangles[it].link){
+		 Triangle &K=triangles[it];
+		 double  area3= Area2((R2) K[0],(R2) K[1],(R2) K[2])/6.;
+		 area+= area3;
+		 D2xD2 B_Kt(K[0],K[1],K[2]);
+		 D2xD2 B_K(B_Kt.t());
+		 D2xD2 B1K = Br*B_K.inv();
+		 D2xD2 BK =  B_K*B1r;
+		 D2xD2 B1B1 = B1K.t()*B1K;
+		 Metric MK(B1B1.x.x,B1B1.x.y,B1B1.y.y);
+		 EigenMetric VMK(MK);
+		 alpha2 = Max(alpha2,Max(VMK.lambda1/VMK.lambda2,VMK.lambda2/VMK.lambda1));
+		 double betaK=0;
+
+		 for (int j=0;j<3;j++)
+			{
+			 double he= Norme2(R2(K[j],K[(j+1)%3]));
+			 hmin=Min(hmin,he);
+			 hmax=Max(hmax,he);
+			 BamgVertex & v=K[j];
+			 D2xD2 M((Metric)v);
+			 betaK += sqrt(M.det());
+
+			 D2xD2 BMB = BK.t()*M*BK;
+			 Metric M1(BMB.x.x,BMB.x.y,BMB.y.y);
+			 EigenMetric VM1(M1);
+			 gammamn=Min3(gammamn,VM1.lambda1,VM1.lambda2);
+			 gammamx=Max3(gammamx,VM1.lambda1,VM1.lambda2);		
+			}
+		 betaK *= area3;//  1/2 (somme sqrt(det))* area(K)
+		 Marea+= betaK;
+		 beta=min(beta,betaK);
+		 beta0=max(beta0,betaK);
+		}   
+	area*=3; 
+	gammamn=sqrt(gammamn);
+	gammamx=sqrt(gammamx);    
+	printf("   Adaptmesh info:\n");
+	printf("      number of triangles = %i\n",nt);
+	printf("      hmin = %g, hmax=%g\n",hmin,hmax);
+	printf("      area = %g, M area = %g, M area/( |Khat| nt) = %g\n",area,Marea, Marea/(aireKh*nt));
+	printf("      infinite-regularity(?): min = %g, max = %g\n",gammamn,gammamx);
+	printf("      anisomax = %g, beta max = %g, min = %g\n",pow(alpha2,0.5),1./pow(beta/aireKh,0.5), 1./pow(beta0/aireKh,0.5));
+}
+/*}}}1*/
+/*FUNCTION Mesh::ShowHistogram{{{1*/
+void  Mesh::ShowHistogram() const {
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ShowHistogram)*/
+
+	const long kmax=10;
+	const double llmin = 0.5,llmax=2;
+	const double lmin=log(llmin),lmax=log(llmax),delta= kmax/(lmax-lmin);
+	long histo[kmax+1];
+	long i,it,k, nbedges =0;
+	for (i=0;i<=kmax;i++) histo[i]=0;
+	for (it=0;it<nbt;it++)
+	 if ( triangles[it].link) 
+		{
+
+		 for (int j=0;j<3;j++)
+			{
+			 Triangle *ta = triangles[it].TriangleAdj(j);
+			 if ( !ta || !ta->link || GetId(ta) >= it) 
+				{ 
+				 BamgVertex & vP = triangles[it][VerticesOfTriangularEdge[j][0]];
+				 BamgVertex & vQ = triangles[it][VerticesOfTriangularEdge[j][1]];
+				 if ( !& vP || !&vQ) continue;
+				 R2 PQ = vQ.r - vP.r;
+				 double l = log(LengthInterpole(vP,vQ,PQ));
+				 nbedges++;
+				 k = (int) ((l - lmin)*delta);
+				 k = Min(Max(k,0L),kmax);
+				 histo[k]++;
+				}
+			}
+		}  
+	printf(" --- Histogram of the unit mesh,  nb of edges = %i\n",nbedges);
+	printf("      length of edge in   | %% of edge  | Nb of edges \n"); 
+	printf("      --------------------+-------------+-------------\n"); 
+	for   (i=0;i<=kmax;i++){ 
+		if (i==0) printf("      %10i",0);
+		else      printf("      %10g",exp(lmin+i/delta));
+		if (i==kmax) printf("          +inf   ");
+		else printf("      %10g",exp(lmin+(i+1)/delta));
+		printf("|  %10g |\n",((long)  ((10000.0 * histo[i])/ nbedges))/100.0);
+		printf("  %i\n",histo[i]);
+	}
+	printf("      --------------------+-------------+-------------\n"); 
+}
+/*}}}1*/
+/*FUNCTION Mesh::SmoothingVertex{{{1*/
+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 = %i, Omega=%g\n",nbiter,omega);
+	for (k=0;k<nbiter;k++)
+	  {
+		long i,NbSwap =0;
+		double delta =0;
+		for ( i=0;i<nbv;i++)
+		 if (tstart[i] != &vide) // not a boundary vertex 
+		  delta=Max(delta,vertices[i].Smoothing(*this,BTh,tstart[i],omega));
+		if (!nbq)
+		 for ( i=0;i<nbv;i++)
+		  if (tstart[i] != &vide) // not a boundary vertex 
+			NbSwap += vertices[i].Optim(1);
+		if (verbose>3) printf("      move max = %g, iteration = %i, nb of swap = %i\n",pow(delta,0.5),k,NbSwap);
+	  }
+
+	delete [] tstart;
+	if (quadtree) quadtree= new QuadTree(this);
+}
+/*}}}1*/
+/*FUNCTION Mesh::SmoothMetric{{{1*/
+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 = %g\n",raisonmax);
+	CreateSingleVertexToTriangleConnectivity();
+	long i,j,kch,kk,ip;
+	long *first_np_or_next_t0 = new long[nbv];
+	long *first_np_or_next_t1 = new long[nbv];
+	long Head0 =0,Head1=-1;
+	double logseuil= log(raisonmax);
+
+	for(i=0;i<nbv-1;i++)
+	 first_np_or_next_t0[i]=i+1; 
+	first_np_or_next_t0[nbv-1]=-1;// end;
+	for(i=0;i<nbv;i++)
+	 first_np_or_next_t1[i]=-1;
+	kk=0;
+	while (Head0>=0&& kk++<100) {
+		kch=0;
+		for (i=Head0;i>=0;i=first_np_or_next_t0[ip=i],first_np_or_next_t0[ip]=-1) {
+			//  pour tous les triangles autour du sommet s
+			register Triangle* t= vertices[i].t;
+			if (!t){
+				_error_("!t");
+			}
+			BamgVertex & vi = vertices[i];
+			AdjacentTriangle ta(t,EdgesVertexTriangle[vertices[i].IndexInTriangle][0]);
+			BamgVertex *pvj0 = ta.EdgeVertex(0);
+			while (1) {
+				ta=Previous(Adj(ta));
+				if (vertices+i != ta.EdgeVertex(1)){
+					_error_("vertices+i != ta.EdgeVertex(1)");
+				}
+				BamgVertex & vj = *(ta.EdgeVertex(0));
+				if ( &vj ) {
+					j= &vj-vertices;
+					if (j<0 || j >= nbv){
+						_error_("j<0 || j >= nbv");
+					}
+					R2 Aij = (R2) vj - (R2) vi;
+					double ll =  Norme2(Aij);
+					if (0) {  
+						double hi = ll/vi.m(Aij);
+						double hj = ll/vj.m(Aij);
+						if(hi < hj)
+						  {
+							double dh=(hj-hi)/ll;
+							if (dh>logseuil) {
+								vj.m.IntersectWith(vi.m/(1 +logseuil*ll/hi));
+								if(first_np_or_next_t1[j]<0)
+								 kch++,first_np_or_next_t1[j]=Head1,Head1=j;
+							}
+						  }
+					} 
+					else
+					  {
+						double li = vi.m(Aij);
+						if( vj.m.IntersectWith(vi.m/(1 +logseuil*li)) )
+						 if(first_np_or_next_t1[j]<0) // if the metrix change 
+						  kch++,first_np_or_next_t1[j]=Head1,Head1=j;
+					  }
+				}
+				if  ( &vj ==  pvj0 ) break;
+			}
+		}
+		Head0 = Head1;
+		Head1 = -1;
+		Exchange(first_np_or_next_t0,first_np_or_next_t1);
+	}
+	if(verbose>2) printf("      number of iterations = %i\n",kch); 
+	delete [] first_np_or_next_t0;
+	delete [] first_np_or_next_t1;
+}
+/*}}}1*/
+	/*FUNCTION Mesh::SplitElement{{{1*/
+	int  Mesh::SplitElement(int choice){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshQuad.cpp/SplitElement)*/
+
+		long int verbose=0;
+
+		Direction NoDirOfSearch;
+		const  int withBackground = &BTh != this && &BTh;
+
+		TrianglesRenumberBySubDomain();
+		//int nswap =0;
+		const long nfortria( choice ? 4 : 6);
+		if(withBackground) 
+		  {
+			BTh.SetVertexFieldOn();
+			SetVertexFieldOnBTh();
+		  }
+		else
+		 BTh.SetVertexFieldOn();
+
+		long newnbt=0,newnbv=0;
+		long * kedge = 0;
+		long newnbq=nbq;
+		long * ksplit= 0, * ksplitarray=0;
+		long kkk=0;
+		int ret =0;
+		if (maxnbv<nbv+nbe) return 1;//   
+		// 1) create  the new points by spliting the internal edges 
+		// set the 
+		long nbvold = nbv;
+		long nbtold = nbt;
+		long nbtoutold  = nbtout;
+		long  NbEdgeOnGeom=0;
+		long i;
+
+		nbt = nbt - nbtout; // remove all the  the ouside triangles 
+		long nbtsave = nbt;
+		Triangle * lastT = triangles + nbt;
+		for (i=0;i<nbe;i++)
+		 if(edges[i].GeomEdgeHook) NbEdgeOnGeom++;
+		long newnbe=nbe+nbe;
+		//  long newNbVerticesOnGeomVertex=NbVerticesOnGeomVertex;
+		long newNbVerticesOnGeomEdge=NbVerticesOnGeomEdge+NbEdgeOnGeom;
+		// long newNbVertexOnBThVertex=NbVertexOnBThVertex;
+		long newNbVertexOnBThEdge=withBackground ? NbVertexOnBThEdge+NbEdgeOnGeom:0;
+
+		// do allocation for pointeur to the geometry and background
+		VertexOnGeom * newVerticesOnGeomEdge = new VertexOnGeom[newNbVerticesOnGeomEdge];
+		VertexOnEdge *newVertexOnBThEdge = newNbVertexOnBThEdge ?  new VertexOnEdge[newNbVertexOnBThEdge]:0;
+		if (NbVerticesOnGeomEdge)
+		 memcpy(newVerticesOnGeomEdge,VerticesOnGeomEdge,sizeof(VertexOnGeom)*NbVerticesOnGeomEdge);
+		if (NbVertexOnBThEdge)
+		 memcpy(newVertexOnBThEdge,VertexOnBThEdge,sizeof(VertexOnEdge)*NbVertexOnBThEdge);
+		Edge *newedges = new Edge [newnbe];
+		//  memcpy(newedges,edges,sizeof(Edge)*nbe);
+		SetOfEdges4 * edge4= new SetOfEdges4(nbe,nbv);
+		long k=nbv;
+		long kk=0;
+		long kvb = NbVertexOnBThEdge;
+		long kvg = NbVerticesOnGeomEdge;
+		long ie =0;
+		Edge ** edgesGtoB=0;
+		if (withBackground)
+		 edgesGtoB= BTh.MakeGeomEdgeToEdge();
+		long ferr=0;
+		for (i=0;i<nbe;i++)
+		 newedges[ie].GeomEdgeHook=0;
+
+		for (i=0;i<nbe;i++)
+		  {
+			GeomEdge *ong =  edges[i].GeomEdgeHook;
+
+			newedges[ie]=edges[i];
+			newedges[ie].adj[0]=newedges+(edges[i].adj[0]-edges) ;
+			newedges[ie].adj[1]=newedges + ie +1;
+			R2 A = edges[i][0],B = edges[i][1];
+
+
+			kk += (i == edge4->SortAndAdd(GetId(edges[i][0]),GetId(edges[i][1])));
+			if (ong) // a geometrical edges 
+			  { 
+				if (withBackground){
+					// walk on back ground mesh 
+					//  newVertexOnBThEdge[ibe++] = VertexOnEdge(vertices[k],bedge,absicsseonBedge); 
+					// a faire -- difficile 
+					// the first PB is to now a background edge between the 2 vertices
+					if (!edgesGtoB){
+						_error_("!edgesGtoB");
+					}
+					ong= ProjectOnCurve(*edgesGtoB[Gh.GetId(edges[i].GeomEdgeHook)],
+								edges[i][0],edges[i][1],0.5,vertices[k],
+								newVertexOnBThEdge[kvb],
+								newVerticesOnGeomEdge[kvg++]);
+					vertices[k].ReferenceNumber= edges[i].ReferenceNumber;
+					vertices[k].DirOfSearch =   NoDirOfSearch;        
+					;
+					// get the Info on background mesh 
+					double s =        newVertexOnBThEdge[kvb];
+					BamgVertex &  bv0  = newVertexOnBThEdge[kvb][0];
+					BamgVertex &  bv1  = newVertexOnBThEdge[kvb][1];
+					// compute the metrix of the new points 
+					vertices[k].m =  Metric(1-s,bv0,s,bv1); 
+					kvb++;
+				  }
+				else 
+				  {
+					ong=Gh.ProjectOnCurve(edges[i],
+								0.5,vertices[k],newVerticesOnGeomEdge[kvg++]);
+					// vertices[k].i = R2ToI2( vertices[k].r);
+					vertices[k].ReferenceNumber = edges[i].ReferenceNumber;
+					vertices[k].DirOfSearch = NoDirOfSearch;
+					vertices[k].m =  Metric(0.5,edges[i][0],0.5,edges[i][1]);	      
+				  }  
+			  }
+			else // straigth line edge ---
+			  { 
+				vertices[k].r = ((R2) edges[i][0] + (R2)  edges[i][1] )*0.5;
+				vertices[k].m =  Metric(0.5,edges[i][0],0.5,edges[i][1]);
+				vertices[k].GeomEdgeHook = 0;
+			  }
+			//vertices[k].i = R2ToI2( vertices[k].r);
+			R2 AB =  vertices[k].r;
+			R2 AA = (A+AB)*0.5;
+			R2 BB = (AB+B)*0.5;
+			vertices[k].ReferenceNumber = edges[i].ReferenceNumber;
+			vertices[k].DirOfSearch = NoDirOfSearch;
+
+			newedges[ie].GeomEdgeHook = Gh.Containing(AA,ong);
+			newedges[ie++].v[1]=vertices+k;
+
+			newedges[ie]=edges[i];
+			newedges[ie].adj[0]=newedges + ie -1;
+			newedges[ie].adj[1]=newedges+(edges[i].adj[1]-edges) ;
+			newedges[ie].GeomEdgeHook =  Gh.Containing(BB,ong);
+			newedges[ie++].v[0]=vertices+k;
+			k++;
+		  }
+		if (edgesGtoB) delete [] edgesGtoB;
+		edgesGtoB=0;
+
+		newnbv=k;
+		newNbVerticesOnGeomEdge=kvg;
+		if (newnbv> maxnbv) goto Error;// bug 
+
+		nbv = k;
+
+
+		kedge = new long[3*nbt+1];
+		ksplitarray = new long[nbt+1];
+		ksplit = ksplitarray +1; // because ksplit[-1] == ksplitarray[0]
+
+		for (i=0;i<3*nbt;i++)
+		 kedge[i]=-1;
+
+		//  
+
+		for (i=0;i<nbt;i++) {
+			Triangle & t = triangles[i];
+			if (!t.link){
+				_error_("!t.link");
+			}
+			for(int j=0;j<3;j++)
+			  {
+				const AdjacentTriangle ta = t.Adj(j);
+				const Triangle & tt = ta;
+				if (&tt >= lastT)
+				 t.SetAdj2(j,0,0);// unset adj
+				const BamgVertex & v0 = t[VerticesOfTriangularEdge[j][0]];
+				const BamgVertex & v1 = t[VerticesOfTriangularEdge[j][1]];
+				long  ke =edge4->SortAndFind(GetId(v0),GetId(v1));
+				if (ke>0) 
+				  {
+					long ii = GetId(tt);
+					int  jj = ta;
+					long ks = ke + nbvold;
+					kedge[3*i+j] = ks;
+					if (ii<nbt) // good triangle
+					 kedge[3*ii+jj] = ks;
+					BamgVertex &A=vertices[ks];
+					double aa,bb,cc,dd;
+					if ((dd=Area2(v0.r,v1.r,A.r)) >=0){
+						// warning PB roundoff error 
+						if (t.link && ( (aa=Area2( A.r    , t[1].r , t[2].r )) < 0.0 
+										||   (bb=Area2( t[0].r , A.r    , t[2].r )) < 0.0  
+										||   (cc=Area2( t[0].r , t[1].r , A.r    )) < 0.0)){
+							printf("%i not in triangle %i In= %i %g %g %g %g\n",ke + nbvold,i,!!t.link,aa,bb,cc,dd);
+							_error_("Number of triangles with P2 interpolation Problem");
+						}
+					}
+					else {
+						if (tt.link && ( (aa=Area2( A.r     , tt[1].r , tt[2].r )) < 0 
+										||   (bb=Area2( tt[0].r , A.r     , tt[2].r )) < 0 
+										||   (cc=Area2( tt[0].r , tt[1].r , A.r     )) < 0)){
+							printf("%i not in triangle %i In= %i %g %g %g %g\n",ke + nbvold,ii,!!tt.link,aa,bb,cc,dd);
+							_error_("Number of triangles with P2 interpolation Problem");
+						}
+					} 
+				  }
+			  }
+		}
+
+		for (i=0;i<nbt;i++){
+			ksplit[i]=1; // no split by default
+			const Triangle & t = triangles[ i];
+			int nbsplitedge =0;
+			int nbinvisible =0;
+			int invisibleedge=0;
+			int kkk[3];      
+			for (int j=0;j<3;j++)
+			  {
+				if (t.Hidden(j)) invisibleedge=j,nbinvisible++;
+
+				const AdjacentTriangle ta = t.Adj(j);
+				const Triangle & tt = ta;
+
+
+				const BamgVertex & v0 = t[VerticesOfTriangularEdge[j][0]];
+				const BamgVertex & v1 = t[VerticesOfTriangularEdge[j][1]];
+				if ( kedge[3*i+j] < 0) 
+				  {
+					long  ke =edge4->SortAndFind(GetId(v0),GetId(v1));
+					if (ke<0) // new 
+					  {
+						if (&tt) // internal triangles all the boundary 
+						  { // new internal edges 
+							long ii = GetId(tt);
+							int  jj = ta;
+
+							kedge[3*i+j]=k;// save the vertex number 
+							kedge[3*ii+jj]=k;
+							if (k<maxnbv) 
+							  {
+								vertices[k].r = ((R2) v0+(R2) v1 )/2;
+								//vertices[k].i = R2ToI2( vertices[k].r);
+								vertices[k].ReferenceNumber=0;
+								vertices[k].DirOfSearch =NoDirOfSearch;
+								vertices[k].m =  Metric(0.5,v0,0.5,v1);
+							  }
+							k++;
+							kkk[nbsplitedge++]=j;		      
+						  } // tt 
+						else
+						 _error_("Bug...");
+					  } // ke<0	       
+					else
+					  { // ke >=0
+						kedge[3*i+j]=nbvold+ke;
+						kkk[nbsplitedge++]=j;// previously splited
+					  }
+				  }
+				else 
+				 kkk[nbsplitedge++]=j;// previously splited
+
+			  } 
+			if (nbinvisible>=2){
+				_error_("nbinvisible>=2");
+			}
+			switch (nbsplitedge) {
+				case 0: ksplit[i]=10; newnbt++; break;   // nosplit
+				case 1: ksplit[i]=20+kkk[0];newnbt += 2; break; // split in 2 
+				case 2: ksplit[i]=30+3-kkk[0]-kkk[1];newnbt += 3; break; // split in 3 
+				case 3:
+						  if (nbinvisible) ksplit[i]=40+invisibleedge,newnbt += 4;
+						  else   ksplit[i]=10*nfortria,newnbt+=nfortria;
+						  break;
+			} 
+			if (ksplit[i]<40){
+				_error_("ksplit[i]<40");
+			}
+		  }
+		//  now do the element split
+		newnbq = 4*nbq;
+		nbv = k;
+		kkk = nbt;
+		ksplit[-1] = nbt;
+		// look on  old true  triangles 
+
+		for (i=0;i<nbtsave;i++){
+			int  nbmkadj=0;
+			long mkadj [100];
+			mkadj[0]=i;
+			long kk=ksplit[i]/10;
+			int  ke=(int) (ksplit[i]%10);
+			if (kk>=7 || kk<=0){
+				_error_("kk>=7 || kk<=0");
+			}
+
+			// def the numbering   k (edge) i vertex 
+			int k0 = ke;
+			int k1 = NextEdge[k0];
+			int k2 = PreviousEdge[k0];
+			int i0 = OppositeVertex[k0];
+			int i1 = OppositeVertex[k1];
+			int i2 = OppositeVertex[k2];
+
+			Triangle &t0=triangles[i];
+			BamgVertex * v0=t0(i0);           
+			BamgVertex * v1=t0(i1);           
+			BamgVertex * v2=t0(i2);
+
+			if (nbmkadj>=10){
+				_error_("nbmkadj>=10");
+			}
+			// --------------------------
+			AdjacentTriangle ta0(t0.Adj(i0)),ta1(t0.Adj(i1)),ta2(t0.Adj(i2));
+			// save the flag Hidden
+			int hid[]={t0.Hidden(0),t0.Hidden(1),t0.Hidden(2)};
+			// un set all adj -- save Hidden flag --
+			t0.SetAdj2(0,0,hid[0]);
+			t0.SetAdj2(1,0,hid[1]);
+			t0.SetAdj2(2,0,hid[2]);
+			// --  remake 
+			switch  (kk) {
+				case 1: break;// nothing 
+				case 2: // 
+						  {
+							Triangle &t1=triangles[kkk++];
+							t1=t0;
+							if (kedge[3*i+i0]<0){
+								_error_("kedge[3*i+i0]<0");
+							}
+							BamgVertex * v3 = vertices + kedge[3*i+k0];
+
+							t0(i2) = v3;
+							t1(i1) = v3;
+							t0.SetAllFlag(k2,0);
+							t1.SetAllFlag(k1,0);
+						  } 
+						break; 
+				case 3: //
+						  {
+							Triangle &t1=triangles[kkk++];
+							Triangle &t2=triangles[kkk++];
+							t2=t1=t0;
+							if (kedge[3*i+k1]<0){
+								_error_("kedge[3*i+k1]<0");
+							}
+							if (kedge[3*i+k2]<0){
+								_error_("kedge[3*i+k2]<0");
+							}
+
+							BamgVertex * v01 = vertices + kedge[3*i+k2];
+							BamgVertex * v02 = vertices + kedge[3*i+k1]; 
+							t0(i1) = v01; 
+							t0(i2) = v02; 
+							t1(i2) = v02;
+							t1(i0) = v01; 
+							t2(i0) = v02; 
+							t0.SetAllFlag(k0,0);
+							t1.SetAllFlag(k1,0);
+							t1.SetAllFlag(k0,0);
+							t2.SetAllFlag(k2,0);
+						  } 
+						break;
+				case 4: // 
+				case 6: // split in 4 
+						  {
+							Triangle &t1=triangles[kkk++];
+							Triangle &t2=triangles[kkk++];
+							Triangle &t3=triangles[kkk++];
+							t3=t2=t1=t0;
+							if (kedge[3*i+k0] <0 || kedge[3*i+k1]<0 || kedge[3*i+k2]<0){
+								_error_("kedge[3*i+k0] <0 || kedge[3*i+k1]<0 || kedge[3*i+k2]<0");
+							}
+							BamgVertex * v12 = vertices + kedge[3*i+k0];
+							BamgVertex * v02 = vertices + kedge[3*i+k1]; 
+							BamgVertex * v01 = vertices + kedge[3*i+k2];
+							t0(i1) = v01;
+							t0(i2) = v02;
+							t0.SetAllFlag(k0,hid[k0]);
+
+							t1(i0) = v01;
+							t1(i2) = v12;
+							t0.SetAllFlag(k1,hid[k1]);
+
+							t2(i0) = v02;
+							t2(i1) = v12;
+							t2.SetAllFlag(k2,hid[k2]);
+
+							t3(i0) = v12;
+							t3(i1) = v02;
+							t3(i2) = v01;
+
+							t3.SetAllFlag(0,hid[0]);	   
+							t3.SetAllFlag(1,hid[1]);	   
+							t3.SetAllFlag(2,hid[2]);
+
+							if ( kk == 6)
+							  {
+
+								Triangle &t4=triangles[kkk++];
+								Triangle &t5=triangles[kkk++];
+
+								t4 = t3;
+								t5 = t3;
+
+								t0.SetHidden(k0);
+								t1.SetHidden(k1);
+								t2.SetHidden(k2);
+								t3.SetHidden(0);
+								t4.SetHidden(1);
+								t5.SetHidden(2);
+
+								if (nbv < maxnbv ) 
+								  {
+									vertices[nbv].r = ((R2) *v01 + (R2) *v12  + (R2) *v02 ) / 3.0;
+									vertices[nbv].ReferenceNumber =0;
+									vertices[nbv].DirOfSearch =NoDirOfSearch;
+									//vertices[nbv].i = R2ToI2(vertices[nbv].r);
+									double a3[]={1./3.,1./3.,1./3.};
+									vertices[nbv].m = Metric(a3,v0->m,v1->m,v2->m);
+									BamgVertex * vc =  vertices +nbv++;
+									t3(i0) = vc;
+									t4(i1) = vc;
+									t5(i2) = vc;
+
+								  }
+								else
+								 goto Error; 
+							  }
+
+						  } 
+						break;         
+			}
+
+			// save all the new triangles
+			mkadj[nbmkadj++]=i;
+			long jj;
+			if (t0.link) 
+			 for (jj=nbt;jj<kkk;jj++)
+				{
+				 triangles[jj].link=t0.link;
+				 t0.link= triangles+jj;
+				 mkadj[nbmkadj++]=jj;
+				}
+			if (nbmkadj>13){// 13 = 6 + 4 +
+				_error_("nbmkadj>13");
+			}
+
+			if (kk==6)  newnbq+=3;
+			for (jj=ksplit[i-1];jj<kkk;jj++) nbt = kkk;
+			ksplit[i]= nbt; // save last adresse of the new triangles
+			kkk = nbt;
+		  }
+
+		for (i=0;i<nbv;i++) vertices[i].m = vertices[i].m*2.;
+
+		if(withBackground)
+		 for (i=0;i<BTh.nbv;i++)
+		  BTh.vertices[i].m =  BTh.vertices[i].m*2.;
+
+
+		ret = 2;
+		if (nbt>= maxnbt) goto Error; // bug 
+		if (nbv>= maxnbv) goto Error; // bug 
+		// generation of the new triangles 
+
+		SetIntCoor("In SplitElement"); 
+
+		CreateSingleVertexToTriangleConnectivity();
+		if(withBackground)
+		 BTh.CreateSingleVertexToTriangleConnectivity();
+
+		delete [] edges;
+		edges = newedges;
+		nbe = newnbe;
+		nbq = newnbq;
+
+		for (i=0;i<nbsubdomains;i++)
+		  { 
+			long k = subdomains[i].edge- edges;
+			subdomains[i].edge =  edges+2*k; // spilt all edge in 2 
+		  }
+
+		if (ksplitarray) delete [] ksplitarray;
+		if (kedge) delete [] kedge;
+		if (edge4) delete edge4;
+		if (VerticesOnGeomEdge) delete [] VerticesOnGeomEdge;
+		VerticesOnGeomEdge= newVerticesOnGeomEdge;
+		if(VertexOnBThEdge) delete []  VertexOnBThEdge;
+		VertexOnBThEdge = newVertexOnBThEdge;
+		NbVerticesOnGeomEdge = newNbVerticesOnGeomEdge;
+		NbVertexOnBThEdge=newNbVertexOnBThEdge;
+		//  CreateSingleVertexToTriangleConnectivity();
+
+		ReconstructExistingMesh();
+
+		if (verbose>2){
+			printf("   number of quadrilaterals    = %i\n",nbq);
+			printf("   number of triangles         = %i\n",nbt-nbtout- nbq*2);
+			printf("   number of outside triangles = %i\n",nbtout);
+		}
+
+		return 0; //ok
+
+Error:
+		nbv = nbvold;
+		nbt = nbtold;
+		nbtout = nbtoutold;
+		// cleaning memory ---
+		delete [] newedges;
+		if (ksplitarray) delete [] ksplitarray;
+		if (kedge) delete [] kedge;
+		if (newVerticesOnGeomEdge) delete [] newVerticesOnGeomEdge;
+		if (edge4) delete edge4;
+		if(newVertexOnBThEdge) delete []  newVertexOnBThEdge;
+
+		return ret; // ok 
+	}
+	/*}}}1*/
+/*FUNCTION Mesh::SplitInternalEdgeWithBorderVertices{{{1*/
+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: %i\n",iv);
+		printf("   number of swap to  split internal edges with border vertices: %i\n",NbSwap);
+		nbv = iv;
+	}
+}
+if (NbSplitEdge>nbv-nbvold) printf("WARNING: not enough vertices  to split all internal edges, we lost %i edges...\n",NbSplitEdge - ( nbv-nbvold));
+if (verbose>2) printf("SplitInternalEdgeWithBorderVertices: Number of splited edge %i\n",NbSplitEdge);
+
+return  NbSplitEdge;
+}
+/*}}}1*/
+/*FUNCTION Mesh::ToI2{{{1*/
+I2 Mesh::R2ToI2(const R2 & P) const {
+	return  I2( (Icoor1) (coefIcoor*(P.x-pmin.x)),(Icoor1) (coefIcoor*(P.y-pmin.y)) );
+}
+/*}}}1*/
+/*FUNCTION Mesh::ToR2{{{1*/
+R2 Mesh::I2ToR2(const I2 & P) const {
+	return  R2( (double) P.x/coefIcoor+pmin.x, (double) P.y/coefIcoor+pmin.y);
+}
+/*}}}1*/
+/*FUNCTION Mesh::TriangleFindFromCoord{{{1*/
+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 %i (orphan?)",GetId(a)+1);
+		_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 = %i).",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;
+}
+/*}}}1*/
+/*FUNCTION Mesh::TriangleIntNumbering{{{1*/
+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;   
+}
+/*}}}1*/
+/*FUNCTION Mesh::TriangleReferenceList{{{1*/
+long  Mesh::TriangleReferenceList(long* reft) const {
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ConsRefTriangle)*/
+
+	long int verbose=0;
+	register Triangle *t0,*t;
+	register long k=0, num;   
+
+	//initialize all triangles as -1 (outside)
+	for (int it=0;it<nbt;it++) reft[it]=-1;
+
+	//loop over all subdomains
+	for (int i=0;i<nbsubdomains;i++){ 
+
+		//first triangle of the subdomain i
+		t=t0=subdomains[i].head;
+
+		//check that the subdomain is not empty
+		if (!t0){ _error_("At least one subdomain is empty");}
+
+		//loop
+		do{
+			k++;
+
+			//get current triangle number
+			num = GetId(t);
+
+			//check that num is in [0 nbt[
+			_assert_(num>=0 && num<nbt);
+
+			//reft of this triangle is the subdomain number
+			reft[num]=i;
+
+		} while (t0 != (t=t->link));
+		//stop when all triangles of subdomains have been tagged
+
+	}
+	return k;   
+}
+/*}}}1*/
+/*FUNCTION Mesh::Triangulate{{{1*/
+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 (%i)\n",nbv);
+	for (i=0;i<nbv;i++){
+		vertices[i].r.x=x[i];
+		vertices[i].r.y=y[i];
+		vertices[i].ReferenceNumber=1;
+		vertices[i].DirOfSearch =NoDirOfSearch;
+		vertices[i].m=M1;
+		vertices[i].color=0;
+	}
+	maxnbt=2*maxnbv-2; // for filling The Holes and quadrilaterals 
+
+	/*Insert Vertices*/
+	Insert();
+}
+/*}}}1*/
+	/*FUNCTION Mesh::TriangulateFromGeom0{{{1*/
+	void Mesh::TriangulateFromGeom0(BamgOpts* bamgopts){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/GeomToTriangles0)*/
+		/*Generate mesh from geometry*/
+
+		/*Intermediaries*/
+		int                i,j,k;
+		int                nbcurves    = 0;
+		int                NbNewPoints,NbEdgeCurve;
+		double             lcurve,lstep,s;
+		const int          MaxSubEdge  = 10;
+
+		R2          AB;
+		GeomVertex *a, *b;
+		BamgVertex *va,*vb;
+		GeomEdge   *e;
+
+		// add a ref to GH to make sure that it is not destroyed by mistake
+		Gh.NbRef++;
+
+		/*Get options*/
+		int verbose=bamgopts->verbose;
+
+		//build background mesh flag (1 if background, else 0)
+		bool background=(&BTh != this);
+
+		/*Build VerticesOnGeomVertex*/
+
+		//Compute the number of geometrical vertices that we are going to use to mesh
+		for (i=0;i<Gh.nbv;i++){
+			if (Gh[i].Required()) NbVerticesOnGeomVertex++;
+		}
+		//allocate
+		VerticesOnGeomVertex = new VertexOnGeom[NbVerticesOnGeomVertex];  
+		if(NbVerticesOnGeomVertex >= maxnbv) _error_("too many vertices on geometry: %i >= %i",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 = %i\n",nbv);
+		if (verbose>3) printf("      Creating initial Constrained Delaunay Triangulation...\n");
+		if (verbose>3) printf("         Inserting boundary points\n");
+		Insert();
+
+		//Force the boundary
+		if (verbose>3) printf("         Forcing boundaries\n");
+		ForceBoundary();
+
+		//Extract SubDomains
+		if (verbose>3) printf("         Extracting subdomains\n");
+		FindSubDomain();
+
+		if (verbose>3) printf("      Inserting internal points\n");
+		NewPoints(*this,bamgopts,0) ;
+		if (verbose>4) printf("      -- current number of vertices = %i\n",nbv);
+	}
+	/*}}}1*/
+	/*FUNCTION Mesh::TriangulateFromGeom1{{{1*/
+	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++;
+		if(NbVerticesOnGeomVertex >= maxnbv){
+			delete [] bcurve;
+			_error_("too many vertices on geometry: %i >= %i",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 metrix of the background mesh
+			}
+		}
+		_assert_(NbVertexOnBThVertex==NbVerticesOnGeomVertex);
+
+		/*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 %i\n",nc);
+					//printf("edge on geometry is same as GhCurve? %s\n",(ei.GeomEdgeHook==Gh.curves[nc].FirstEdge || ei.GeomEdgeHook==Gh.curves[nc].LastEdge)?"yes":"no");
+					//if(ei.GeomEdgeHook==Gh.curves[nc].FirstEdge || ei.GeomEdgeHook==Gh.curves[nc].LastEdge){
+					//	printf("Do we have the right extremity? curve first vertex -> %s\n",((GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].FirstEdge)[Gh.curves[nc].FirstVertexIndex])?"yes":"no");
+					//	printf("Do we have the right extremity? curve last  vertex -> %s\n",((GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].LastEdge)[Gh.curves[nc].LastVertexIndex])?"yes":"no");
+					//}
+					//BUG FIX from original bamg
+					/*Check that we are on the same edge and right vertex (0 or 1) */
+					if(ei.GeomEdgeHook==Gh.curves[nc].FirstEdge  && (GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].FirstEdge)[Gh.curves[nc].FirstVertexIndex]){
+						bcurve[nc]=iedge*2+je;
+						bfind++;	
+					}
+					else if ((ei.GeomEdgeHook==Gh.curves[nc].LastEdge  && (GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].LastEdge)[Gh.curves[nc].LastVertexIndex]) && bcurve[nc]==-1){
+						bcurve[nc]=iedge*2+je;
+						bfind++;	
+					}
+				}
+			}
+		} 
+		if (bfind!=Gh.nbcurves){
+			delete [] bcurve;
+			_error_("problem generating number of curves (%i found in the geometry but %i curve found in the mesh)",Gh.nbcurves,bfind);
+		}
+
+		// method in 2 + 1 step 
+		//  0.0) compute the length and the number of vertex to do allocation
+		//  1.0) recompute the length
+		//  1.1) compute the  vertex 
+
+		long nbex=0,NbVerticesOnGeomEdgex=0;
+		for (int step=0; step <2;step++){
+
+			long NbOfNewPoints=0;
+			long NbOfNewEdge=0;
+			long iedge;
+			Gh.UnMarkEdges();	
+			double L=0;
+
+			/*Go through all geometrical curve*/
+			for (int icurve=0;icurve<Gh.nbcurves;icurve++){ 
+
+				/*Get edge and vertex (index) of background mesh on this curve*/
+				iedge=bcurve[icurve]/2;
+				int jedge=bcurve[icurve]%2;
+
+				/*Get edge of Bth with index iedge*/
+				Edge &ei = BTh.edges[iedge];
+			
+				/*Initialize variables*/
+				double Lstep=0,Lcurve=0;    // step between two points   (phase==1) 
+				long NbCreatePointOnCurve=0;// Nb of new points on curve (phase==1) 
+
+				/*Do phase 0 to step*/
+				for(int phase=0;phase<=step;phase++){
+
+					/*Current curve pointer*/
+					Curve *curve= Gh.curves+icurve;
+
+					/*Get index of current curve*/
+					int icurveequi= Gh.GetId(curve);
+
+					/*For phase 0, check that we are at the begining of the curve only*/
+					if(phase==0 &&  icurveequi!=icurve)  continue;
+
+					int   k0=jedge,k1;
+					Edge* pe=  BTh.edges+iedge;
+					int   iedgeequi=bcurve[icurveequi]/2;
+					int   jedgeequi=bcurve[icurveequi]%2;
+
+					int k0equi=jedgeequi,k1equi;		  
+					Edge * peequi= BTh.edges+iedgeequi;
+					GeomEdge *ongequi = peequi->GeomEdgeHook;
+
+					double sNew=Lstep;// abscisse of the new points (phase==1) 
+					L=0;// length of the curve
+					long i=0;// index of new points on the curve
+					register GeomVertex * GA0 = *(*peequi)[k0equi].GeomEdgeHook;
+					BamgVertex *A0;
+					A0 = GA0->MeshVertexHook;  // the vertex in new mesh
+					BamgVertex *A1;
+					VertexOnGeom *GA1;
+					Edge* PreviousNewEdge = 0;
+
+					// New Curve phase 
+					_assert_(A0-vertices>=0 && A0-vertices<nbv);
+					if(ongequi->Required()){
+						GeomVertex *GA1 = *(*peequi)[1-k0equi].GeomEdgeHook;
+						A1 = GA1->MeshVertexHook;  //
+					}       
+					else {
+						for(;;){
+							Edge &ee=*pe; 
+							Edge &eeequi=*peequi; 
+							k1 = 1-k0; // next vertex of the edge 
+							k1equi= 1 - k0equi;
+							_assert_(pe && ee.GeomEdgeHook);
+							ee.GeomEdgeHook->SetMark();
+							BamgVertex & v0=ee[0], & v1=ee[1];
+							R2 AB=(R2)v1-(R2)v0;
+							double L0=L,LAB;
+							LAB=LengthInterpole(v0.m,v1.m,AB);
+							L+= LAB;
+
+							if (phase){
+								// computation of the new points for the given curve
+								while ((i!=NbCreatePointOnCurve) && sNew<=L) { 
+
+									//some checks
+									_assert_(sNew>=L0);
+									_assert_(LAB);
+									_assert_(vertices && nbv<maxnbv);
+									_assert_(edges && nbe<nbex);
+									_assert_(VerticesOnGeomEdge && NbVerticesOnGeomEdge<NbVerticesOnGeomEdgex);
+
+									// new vertex on edge
+									A1=vertices+nbv++;
+									GA1=VerticesOnGeomEdge+NbVerticesOnGeomEdge;
+									Edge* e = edges + nbe++;
+									double se= (sNew-L0)/LAB;
+									if (se<0 || se>=1.000000001){
+										_error_("Problem creating point on a boundary: se=%g should be in [0 1]",se);
+									}
+									se = abscisseInterpole(v0.m,v1.m,AB,se,1);
+									if (se<0 || se>1){
+										_error_("Problem creating point on a boundary: se=%g should be in [0 1]",se);
+									}
+									se = k1         ? se : 1. - se;
+									se = k1==k1equi ? se : 1. - se;
+									VertexOnBThEdge[NbVerticesOnGeomEdge++] = VertexOnEdge(A1,&eeequi,se); // save 
+									ongequi=Gh.ProjectOnCurve(eeequi,se,*A1,*GA1); 
+									A1->ReferenceNumber = eeequi.ReferenceNumber;
+									A1->DirOfSearch =NoDirOfSearch;
+									e->GeomEdgeHook = ongequi;
+									e->v[0]=A0;
+									e->v[1]=A1;
+									e->ReferenceNumber = eeequi.ReferenceNumber;
+									e->adj[0]=PreviousNewEdge;
+
+									if (PreviousNewEdge) PreviousNewEdge->adj[1]=e;
+									PreviousNewEdge=e;
+									A0=A1;
+									sNew += Lstep;
+									if (++i== NbCreatePointOnCurve) break;
+								}
+							}
+
+							//some checks
+							_assert_(ee.GeomEdgeHook->CurveNumber==ei.GeomEdgeHook->CurveNumber);
+							if (ee[k1].GeomEdgeHook->IsRequiredVertex()) {
+								_assert_(eeequi[k1equi].GeomEdgeHook->IsRequiredVertex());
+								register GeomVertex * GA1 = *eeequi[k1equi].GeomEdgeHook;
+								A1=GA1->MeshVertexHook;// the vertex in new mesh
+								_assert_(A1-vertices>=0 && A1-vertices<nbv);
+								break;
+							}
+							if (!ee.adj[k1]) {
+								_error_(" adj edge %i, nbe=%i, Gh.vertices=%i",BTh.GetId(ee),nbe,Gh.vertices);
+							}
+							pe = ee.adj[k1]; // next edge
+							k0 = pe->Intersection(ee); 
+							peequi= eeequi.adj[k1equi];  // next edge
+							k0equi=peequi->Intersection(eeequi);            
+						}// for(;;) end of the curve
+					}
+
+
+					if (phase){ // construction of the last edge
+						Edge* e=edges + nbe++;
+						e->GeomEdgeHook  = ongequi;
+						e->v[0]=A0;
+						e->v[1]=A1;
+						e->ReferenceNumber = peequi->ReferenceNumber;
+						e->adj[0]=PreviousNewEdge;
+						e->adj[1]=0;
+						if (PreviousNewEdge) PreviousNewEdge->adj[1]=e;
+						PreviousNewEdge = e;
+
+						_assert_(i==NbCreatePointOnCurve);
+					}
+
+					if (!phase)  { // 
+						long NbSegOnCurve = Max((long)(L+0.5),(long) 1);// nb of seg
+						Lstep = L/NbSegOnCurve; 
+						Lcurve = L;
+						NbCreatePointOnCurve = NbSegOnCurve-1;
+						NbOfNewEdge += NbSegOnCurve;
+						NbOfNewPoints += NbCreatePointOnCurve;
+					}
+				}
+			}//  end of curve loop 
+
+			//Allocate memory
+			if(step==0){
+				if(nbv+NbOfNewPoints > maxnbv) {
+					_error_("too many vertices on geometry: %i >= %i",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 = %i\n",nbv);
+		if (verbose>3) printf("      Creating initial Constrained Delaunay Triangulation...\n");
+		if (verbose>3) printf("         Inserting boundary points\n");
+		Insert();
+
+		//Force the boundary
+		if (verbose>3) printf("         Forcing boundaries\n");
+		ForceBoundary();
+
+		//Extract SubDomains
+		if (verbose>3) printf("         Extracting subdomains\n");
+		FindSubDomain();
+
+		if (verbose>3) printf("      Inserting internal points\n");
+		NewPoints(BTh,bamgopts,KeepVertices) ;
+		if (verbose>4) printf("      -- current number of vertices = %i\n",nbv);
+	}
+	/*}}}1*/
+
+	/*Intermediary*/
+	/*FUNCTION CloseBoundaryEdge{{{1*/
+	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;
+		  } 
+	}
+	/*}}}1*/
+	/*FUNCTION CloseBoundaryEdgeV2{{{1*/
+	AdjacentTriangle CloseBoundaryEdgeV2(I2 C,Triangle *t, double &a,double &b) { 
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/CloseBoundaryEdgeV2)*/
+		// walk around the vertex 
+		// version 2 for remove the probleme if we fill the hole
+		//int bug=1;
+		//  Triangle *torigine = t;
+		// restart:
+		//   int dir=0;
+		if (t->link != 0){
+			_error_("t->link != 0");
+		}
+		// to have a starting edges 
+		// try the 3 edge bourna-- in case of internal hole 
+		// and choice  the best 
+		// 
+		// the probleme is in case of  the fine and long internal hole
+		// for exemple neart the training edge of a wing
+		BamgVertex * s=0,*s1=0, *s0=0;
+		Icoor2 imax = MaxICoor22;
+		Icoor2 l0 = imax,l1 = imax;
+		double dd2 =  imax;// infinity
+		AdjacentTriangle er; 
+		int  cas=-2;
+		for (int j=0;j<3;j++)
+		  { 
+			AdjacentTriangle ta=t->FindBoundaryEdge(j);
+			if  (! (Triangle *) ta) continue;
+			s0 = ta.EdgeVertex(0);
+			s1 = ta.EdgeVertex(1);
+			I2 A = * s0;
+			I2 B = *ta.EdgeVertex(1);
+			I2 AB = B-A,AC=C-A,BC=B-C;
+			Icoor2  ACAC = (AC,AC), BCBC = (BC,BC);
+			Icoor2  AB2  =   Norme2_2(AB); //  ||AB||^2
+			Icoor2  ABAC  =   (AB,AC);         //  AB.AC|
+
+			double d2;
+			if ( ABAC < 0 )   // DIST A
+			  {
+				if ( (d2=(double) ACAC)  <  dd2) 
+				  {
+					er = ta;
+					l0 = ACAC;
+					l1 = BCBC;
+					cas = 0;
+					s = s0;
+				  }
+			  }
+			else if (ABAC > AB2)  // DIST B
+			  {
+				if ( (d2=(double) BCBC)  <  dd2) 
+				  {
+					dd2 = d2;
+					er = Adj(ta); // other direction
+					l0 = BCBC;
+					l1 = ACAC;
+					cas = 1;
+					s = s1;
+				  }
+			  }
+			else  // DIST AB
+			  { 
+
+				double det_2 =  (double) Det(AB,AC); 
+				det_2 *= det_2; // square of area*2 of triangle ABC
+				d2 = det_2/ (double) AB2; // hauteur^2 in C of of triangle ABC      
+
+				if (d2 < dd2) 
+				  {
+					dd2 = d2;
+					er = ta;
+					l0 = (AC,AC);
+					l1 = (BC,BC);
+					s = 0;
+					cas = -1;
+					b = ((double) ABAC/(double) AB2);
+					a = 1 - b;
+				  }
+			  }
+		  }
+		if (cas ==-2){
+			_error_("cas==-2");
+		}
+		// l1 = ||C s1||  , l0 = ||C s0||
+		// where s0,s1 are the vertex of the edge er
+
+		if ( s) 
+		  { 
+			t=er;
+			AdjacentTriangle edge(er); 
+
+			int kkk=0;  
+			int linkp = t->link == 0;
+
+			Triangle * tt=t=edge=Adj(Previous(edge));
+			do  {  // loop over vertex s
+				kkk++;
+				if (edge.EdgeVertex(0)!=s && kkk>=10000){
+					_error_("edge.EdgeVertex(0)!=s && kkk>=10000");
+				}
+
+				int link = tt->link == 0;
+				if ((link + linkp) == 1) 
+				  { // a boundary edge 
+					BamgVertex * st = edge.EdgeVertex(1);
+					I2 I=*st;
+					Icoor2  ll = Norme2_2 (C-I);
+					if (ll < l1) {  // the other vertex is neart 
+						s1=st;
+						l1=ll;
+						er = edge;
+						if(ll<l0) { // change of direction --
+							s1=s;
+							l1=l0;
+							s=st;
+							l0=ll;
+							t=tt;
+							edge=Adj(edge);
+							link=linkp;
+							er = edge;
+						}
+					}
+				  }
+
+				linkp=link;
+				edge=Adj(Previous(edge));
+				tt = edge;
+			} while (t!=tt);
+
+			if (!(Triangle *) er){
+				_error_("!(Triangle *) er");
+			}
+			I2 A((I2)*er.EdgeVertex(0));
+			I2 B((I2)*er.EdgeVertex(1));
+			I2 AB=B-A,AC=C-A,CB=B-C;
+			double aa =  (double) (AB,AC);
+			double bb =  (double) (AB,CB);
+			if (aa<0)       a=1,b=0;
+			else if(bb<0)   a=0,b=1;
+			else  
+			  {
+				a  = bb/(aa+bb);
+				b  = aa/(aa+bb);
+			  }
+		  }
+		return er;
+	} 
+	/*}}}1*/
+/*FUNCTION ForceEdge{{{1*/
+int ForceEdge(BamgVertex &a, BamgVertex & b,AdjacentTriangle & taret)  { 
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ForceEdge)*/
+
+	int NbSwap =0;
+	if (!a.t || !b.t){ // the 2 vertex is in a mesh
+		_error_("!a.t || !b.t");
+	}
+	int k=0;
+	taret=AdjacentTriangle(0,0); // erreur 
+
+	AdjacentTriangle tta(a.t,EdgesVertexTriangle[a.IndexInTriangle][0]);
+	BamgVertex   *v1, *v2 = tta.EdgeVertex(0),*vbegin =v2;
+	// we turn around a in the  direct direction  
+
+	Icoor2 det2 = v2 ? det(*v2,a,b): -1 , det1;
+	if(v2) // normal case 
+	 det2 = det(*v2,a,b);
+	else { // no chance infini vertex try the next
+		tta= Previous(Adj(tta));
+		v2 = tta.EdgeVertex(0);
+		vbegin =v2;
+		if (!v2){
+			_error_("!v2");
+		}
+		det2 = det(*v2,a,b);
+	}
+
+	while (v2 != &b) {
+		AdjacentTriangle tc = Previous(Adj(tta));    
+		v1 = v2; 
+		v2 = tc.EdgeVertex(0);
+		det1 = det2;
+		det2 =  v2 ? det(*v2,a,b): det2; 
+
+		if((det1 < 0) && (det2 >0)) { 
+			// try to force the edge 
+			BamgVertex * va = &a, *vb = &b;
+			tc = Previous(tc);
+			if (!v1 || !v2){
+				_error_("!v1 || !v2");
+			}
+			Icoor2 detss = 0,l=0,ks;
+			while ((ks=SwapForForcingEdge(  va,  vb, tc, detss, det1,det2,NbSwap)))
+			 if(l++ > 10000000) {
+				 _error_("Loop in forcing Egde, nb de swap=%i, nb of try swap (%i) too big",NbSwap,l);
+			 }
+			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; 
+}
+/*}}}1*/
+/*FUNCTION swap{{{1*/
+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 
+/*}}}1*/
+	/*FUNCTION SwapForForcingEdge{{{1*/
+	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;
+	}
+	/*}}}1*/
+
+}
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Mesh.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Mesh.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Mesh.h	(revision 11330)
@@ -0,0 +1,194 @@
+#ifndef _MESH_H_
+#define _MESH_H_
+
+#include "./include.h"
+#include "./BamgOpts.h"
+#include "./BamgMesh.h"
+#include "./BamgGeom.h"
+#include "./Triangle.h"
+#include "./VertexOnGeom.h"
+#include "./VertexOnVertex.h"
+#include "./VertexOnEdge.h"
+#include "./ListofIntersectionTriangles.h"
+
+namespace bamg {
+
+	//classes
+	class Geometry;
+	class CrackedEdge;
+	class QuadTree;
+	class SubDomain;
+
+	class Mesh {
+
+		public:
+
+			Geometry                    & Gh;                    // Geometry
+			Mesh                        & BTh;                   // Background Mesh Bth== *this =>no background
+			BamgVertex                   *vertices;
+			Triangle                     *triangles;
+			Edge                         *edges;
+			QuadTree                     *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(double* index,double* x,double* y,int nods,int nels);/*MeshConvert*/
+			Mesh(double* x,double* y,int nods); /*BamgTriangulate*/
+			Mesh(Mesh &,Geometry * pGh=0,Mesh* pBTh=0,long maxnbv_in=0 ); //copy operator
+			Mesh(const Mesh &,const int *flag,const int *bb,BamgOpts* bamgopts); // truncature
+			Mesh(long maxnbv,Mesh & BT,BamgOpts* bamgopts,int keepBackVertices=1);
+			Mesh(long maxnbv,Geometry & G,BamgOpts* bamgopts);
+			~Mesh(); 
+
+			//Operators
+			const BamgVertex &operator[](long i) const { return vertices[i];  };
+			BamgVertex       &operator[](long i) { return vertices[i];        };
+			const Triangle   &operator()(long i) const { return triangles[i]; };
+			Triangle         &operator()(long  i) { return triangles[i];             };
+
+			//Methods
+			void SetIntCoor(const char * from =0);
+			double MinimalHmin();
+			double MaximalHmax();
+			I2 R2ToI2(const R2 & P) const;
+			R2 I2ToR2(const I2 & P) const;
+			void AddVertex(BamgVertex & s,Triangle * t,Icoor2 *  =0) ;
+			void Insert();
+			void Echo(void);
+			void ForceBoundary();
+			void FindSubDomain(int OutSide=0);
+			long TriangleReferenceList(long*) const;
+			void TriangleIntNumbering(long* renumbering);
+			void ShowHistogram() const;
+			void CrackMesh(BamgOpts* bamgopts);
+			void ShowRegulaty() const;
+			void SmoothMetric(double raisonmax) ;
+			void BoundAnisotropy(double anisomax,double hminaniso= 1e-100) ;
+			void MaxSubDivision(double maxsubdiv);
+			Edge** MakeGeomEdgeToEdge();
+			long SplitInternalEdgeWithBorderVertices();
+			void MakeQuadrangles(double costheta);
+			int  SplitElement(int choice);
+			void MakeQuadTree();
+			void NewPoints(Mesh &,BamgOpts* bamgopts,int KeepVertices=1);
+			long InsertNewPoints(long nbvold,long & NbTSwap) ; 
+			void TrianglesRenumberBySubDomain(bool justcompress=false);
+			void VerticesRenumber(long * renu);
+			void SmoothingVertex(int =3,double=0.3);
+			Metric MetricAt (const R2 &) const;
+			GeomEdge* ProjectOnCurve( Edge & AB, BamgVertex &  A, BamgVertex & B,double theta, BamgVertex & R,VertexOnEdge & BR,VertexOnGeom & GR);
+			long GetId(const Triangle & t) const;
+			long GetId(const Triangle * t) const;
+			long GetId(const BamgVertex & t) const;
+			long GetId(const BamgVertex * t) const;
+			long GetId(const Edge & t) const;
+			long GetId(const Edge * t) const;
+			BamgVertex* NearestVertex(Icoor1 i,Icoor1 j) ;
+			Triangle* TriangleFindFromCoord(const I2 & ,Icoor2 [3],Triangle *tstart=0) const;
+			void ReadMesh(double* index,double* x,double* y,int nods,int nels);
+			void ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts);
+			void WriteMesh(BamgMesh* bamgmesh,BamgOpts* bamgopts);
+			void ReadMetric(const BamgOpts* bamgopts);
+			void WriteMetric(BamgOpts* bamgopts);
+			void WriteIndex(int** pindex,int* pnels);
+			void AddMetric(BamgOpts* bamgopts);
+			void BuildMetric0(BamgOpts* bamgopts);
+			void BuildMetric1(BamgOpts* bamgopts);
+			void AddGeometryMetric(BamgOpts* bamgopts);
+			int  isCracked() const;
+			void BuildGeometryFromMesh(BamgOpts* bamgopts=NULL);
+			void ReconstructExistingMesh();
+
+			//Inline methods
+			inline  void CreateSingleVertexToTriangleConnectivity(){
+				for (int i=0;i<nbv;i++) vertices[i].IndexInTriangle=0, vertices[i].t=NULL;
+				for (int i=0;i<nbt;i++) triangles[i].SetSingleVertexToTriangleConnectivity();
+			}
+			inline  void  UnMarkUnSwapTriangle(){
+				for (int i=0;i<nbt;i++)
+				 for(int j=0;j<3;j++)
+				  triangles[i].SetUnMarkUnSwap(j);
+			  }
+			inline  void  SetVertexFieldOn(){
+				for (int i=0;i<nbv;i++)                    vertices[i].GeomEdgeHook=NULL;
+				for (int j=0;j<NbVerticesOnGeomVertex;j++) VerticesOnGeomVertex[j].SetOn();
+				for (int k=0;k<NbVerticesOnGeomEdge;k++ )  VerticesOnGeomEdge[k].SetOn();
+			}	       
+			inline  void   SetVertexFieldOnBTh(){
+				for (int i=0;i<nbv;i++)                 vertices[i].GeomEdgeHook=NULL;
+				for (int j=0;j<NbVertexOnBThVertex;j++) VertexOnBThVertex[j].SetOnBTh();
+				for (int k=0;k<NbVertexOnBThEdge;k++ )  VertexOnBThEdge[k].SetOnBTh();
+			}
+
+		private:
+			void TriangulateFromGeom1(BamgOpts* bamgopts,int KeepVertices=1);// the real constructor mesh adaption
+			void TriangulateFromGeom0(BamgOpts* bamgopts);// the real constructor mesh generator
+			void Triangulate(double* x,double* y,int nods);
+			void Init(long);
+	};
+
+	/*Intermediary*/
+	AdjacentTriangle CloseBoundaryEdge(I2 ,Triangle *, double &,double &) ;
+	AdjacentTriangle CloseBoundaryEdgeV2(I2 A,Triangle *t, double &a,double &b);
+	void  swap(Triangle *t1,short a1,
+				Triangle *t2,short a2,
+				BamgVertex *s1,BamgVertex *s2,Icoor2 det1,Icoor2 det2);
+	int SwapForForcingEdge(BamgVertex   *  & pva ,BamgVertex  * &   pvb ,
+				AdjacentTriangle & tt1,Icoor2 & dets1,
+				Icoor2 & detsa,Icoor2 & detsb, int & nbswap);
+	int ForceEdge(BamgVertex &a, BamgVertex & b,AdjacentTriangle & taret) ;
+	inline AdjacentTriangle Previous(const AdjacentTriangle & ta){
+		return AdjacentTriangle(ta.t,PreviousEdge[ta.a]);
+	}
+	inline AdjacentTriangle Next(const AdjacentTriangle & ta){
+		return AdjacentTriangle(ta.t,NextEdge[ta.a]);
+	}
+	inline  AdjacentTriangle Adj(const AdjacentTriangle & a){
+		return  a.Adj();
+	}
+	inline void Adj(GeomEdge * & on,int &i){
+		int j=i;i=on->AdjVertexIndex[i];on=on->Adj[j];
+	}
+	inline double qualite(const BamgVertex &va,const BamgVertex &vb,const BamgVertex &vc){
+		double ret; 
+		I2 ia=va,ib=vb,ic=vc;
+		I2 ab=ib-ia,bc=ic-ib,ac=ic-ia;
+		Icoor2 deta=Det(ab,ac);
+		if (deta <=0) ret = -1;
+		else {
+			double a = sqrt((double) (ac,ac)),
+					 b = sqrt((double) (bc,bc)),
+					 c = sqrt((double) (ab,ab)),
+					 p = a+b+c;
+			double h= Max(Max(a,b),c),ro=deta/p;
+			ret = ro/h;
+		}
+		return ret;
+	}
+
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Metric.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Metric.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Metric.cpp	(revision 11330)
@@ -0,0 +1,354 @@
+#include <cstdio>
+#include <string.h>
+#include <cmath>
+
+#include "Metric.h"
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+
+using namespace std;
+
+namespace bamg {
+
+	SaveMetricInterpole  LastMetricInterpole;
+
+	/*Constructor/Destructor*/
+	/*FUNCTION Metric::Metric(){{{1*/
+	/*FUNCTION Metric::Metric(double a){{{1*/
+	Metric::Metric(double a): a11(1/(a*a)),a21(0),a22(1/(a*a)){
+	
+	}/*}}}*/
+	/*FUNCTION Metric::Metric(double a,double b,double c){{{1*/
+	Metric::Metric(double a,double b,double c) :a11(a),a21(b),a22(c){
+	
+	}/*}}}*/
+	/*FUNCTION Metric::Metric(const double  a[3],const  Metric& m0, const  Metric& m1,const  Metric&  m2 ){{{1*/ 
+	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;
+	}
+	/*}}}1*/
+	/*FUNCTION Metric::Metric(double  a,const  Metric& ma, double  b,const  Metric& mb){{{1*/
+	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;
+	}
+	/*}}}1*/
+
+	/*Methods*/
+	/*FUNCTION Metric::det{{{1*/
+	double Metric::det() const {
+		return a11*a22-a21*a21;
+	}  /*}}}*/
+	/*FUNCTION Metric::Echo {{{1*/
+	void Metric::Echo(void){
+
+		printf("Metric:\n");
+		printf("   [a11 a21 a22]: [%g %g %g]\n",a11,a21,a22);
+
+		return;
+	}
+	/*}}}*/
+	/*FUNCTION Metric::IntersectWith{{{1*/
+	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;
+	}
+	/*}}}1*/
+	/*FUNCTION Metric::mul{{{1*/
+	R2     Metric::mul(const R2 x)const {
+		return R2(a11*x.x+a21*x.y,a21*x.x+a22*x.y);
+	}/*}}}*/
+
+	/*Intermediary*/
+	/*FUNCTION LengthInterpole{{{1*/
+	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=%i sss=%g ) %g\n",i,l,sss,sstop); 
+		return l;
+	}
+	/*}}}1*/
+	/*FUNCTION SimultaneousMatrixReduction{{{1*/
+	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]);
+		}
+	}
+	/*}}}1*/
+	/*FUNCTION abscisseInterpole{{{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 ;
+	}
+	/*}}}1*/
+
+}
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Metric.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Metric.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Metric.h	(revision 11330)
@@ -0,0 +1,137 @@
+#ifndef _METRIC_H
+#define _METRIC_H
+
+#include "./include.h"
+#include "../../shared/Bamg/shared.h"
+#include "R2.h"
+
+namespace bamg {
+
+	typedef P2<double,double>    D2;
+	typedef P2xP2<double,double> D2xD2;
+
+	class Metric;
+	class EigenMetric;
+
+	class Metric{
+
+		public:
+
+			//fields
+			double a11,a21,a22;
+
+			//friends
+			friend class EigenMetric;
+
+			//functions
+			Metric():a11(0),a21(0),a22(0){};
+			Metric(const EigenMetric&);
+			Metric(double a);
+			Metric(double a,double b,double c);
+			Metric( double  a,const  Metric& ma, double  b,const  Metric& mb);
+			Metric(const double  a[3],const  Metric& m0,const  Metric& m1,const  Metric& m2 );
+			void        Echo();
+			R2          mul(const R2 x)const;
+			double      det() const;
+			int         IntersectWith(const  Metric& M2);
+			inline void Box(double &hx,double &hy) const;
+
+			/*The following functions must remain the the header file because it is called before Metric
+			 * is compiled by other classes*/
+			R2 Orthogonal(const R2 x){ return R2(-(a21*x.x+a22*x.y),a11*x.x+a21*x.y); }
+			R2 Orthogonal(const I2 x){ return R2(-(a21*x.x+a22*x.y),a11*x.x+a21*x.y); }
+
+			//operators
+			Metric operator*(double c) const {double c2=c*c;return  Metric(a11*c2,a21*c2,a22*c2);} 
+			Metric operator/(double c) const {double c2=1/(c*c);return  Metric(a11*c2,a21*c2,a22*c2);} 
+			operator D2xD2(){ return D2xD2(a11,a21,a21,a22);}
+			double  operator()(R2 x) const { return sqrt(x.x*x.x*a11+2*x.x*x.y*a21+x.y*x.y*a22);};        // length of x in metric sqrt(<Mx,x>)
+			double  operator()(R2 x,R2 y) const { return x.x*y.x*a11+(x.x*x.y+x.y*y.x)*a21+x.y*y.y*a22;};
+
+	};
+
+	class EigenMetric{
+		public:
+
+			//fields
+			double lambda1,lambda2;
+			D2     v;
+
+			//friends
+			friend  class Metric;
+
+			//functions
+			EigenMetric(const Metric& );
+			EigenMetric(double r1,double r2,const D2& vp1);
+			void   Echo();
+			void   Abs();
+			void   pow(double  p);
+			void   Min(double  a);
+			void   Max(double  a);
+			void   Minh(double h);
+			void   Maxh(double h);
+			void   Isotrope();
+			double hmin()   const;
+			double hmax()   const;
+			double lmax()   const;
+			double lmin()   const;
+			double Aniso2() const;
+			double Aniso()  const;
+			void   BoundAniso(const  double c);
+			inline void BoundAniso2(const double coef);
+
+			//operators
+			void operator *=(double coef){ lambda1*=coef;lambda2*=coef;}
+	};
+
+	class SaveMetricInterpole {
+		friend double LengthInterpole(const Metric& Ma,const  Metric& Mb, R2 AB);
+		friend double abscisseInterpole(const Metric& Ma ,const  Metric& Mb, R2 ,double s,int optim);
+		public:
+		int opt;
+		double lab;
+		double L[1024],S[1024];
+	};
+
+	extern SaveMetricInterpole  LastMetricInterpole; // for optimization 
+	//Functions
+	void  SimultaneousMatrixReduction( Metric M1,  Metric M2,D2xD2 &V);
+	double LengthInterpole(const Metric& Ma,const  Metric& Mb, R2 AB);
+	double abscisseInterpole(const Metric& Ma,const  Metric& Mb, R2 AB,double s,int optim=0);
+
+	//inlines
+	inline void  EigenMetric::BoundAniso2(const double coef){
+		if (coef<=1.00000000001){
+			if (lambda1 < lambda2)
+			 lambda1 = bamg::Max(lambda1,lambda2*coef);
+			else
+			 lambda2 = bamg::Max(lambda2,lambda1*coef);
+		}
+		else{  //TO BE CHECKED
+			if (lambda1 > lambda2)
+			 lambda1 = bamg::Min(lambda1,lambda2*coef);
+			else
+			 lambda2 = bamg::Min(lambda2,lambda1*coef);
+		}
+	}
+	inline Metric::Metric(const EigenMetric& M) {
+		double v00=M.v.x*M.v.x;
+		double v11=M.v.y*M.v.y;
+		double v01=M.v.x*M.v.y;
+		a11=v00*M.lambda1+v11*M.lambda2;
+		a21=v01*(M.lambda1-M.lambda2);
+		a22=v00*M.lambda2+v11*M.lambda1;
+	}
+	inline   void  Metric::Box(double &hx,double &hy) const {
+		double d=  a11*a22-a21*a21;
+		hx = sqrt(a22/d);
+		hy = sqrt(a11/d);
+	}
+	inline double LengthInterpole(double la,double lb) {
+		return ( Abs(la - lb) < 1.0e-6*Max3(la,lb,1.0e-20) ) ?  (la+lb)/2  : la*lb*log(la/lb)/(la-lb);
+	}
+	inline double abscisseInterpole(double la,double lb,double lab,double s){
+		return ( Abs(la - lb) <1.0e-6*Max3(la,lb,1.0e-20))  ? s : (exp(s*lab*(la-lb)/(la*lb))-1)*lb/(la-lb);
+	}
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/QuadTree.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/QuadTree.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/QuadTree.cpp	(revision 11330)
@@ -0,0 +1,598 @@
+#include <limits.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "../objects.h"
+
+namespace bamg {
+
+	/*MACROS {{{1*/
+	/* 
+	 * 
+	 *    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 QuadTree? {{{1
+	 * 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)
+	 }}}1*/
+
+	/*Constructors/Destructors*/
+	/*FUNCTION QuadTree::QuadTree(){{{1*/
+	QuadTree::QuadTree(){
+
+		/*Number of boxes and vertices*/
+		NbQuadTreeBox=0;
+		NbVertices=0;
+
+		/*Create container*/
+		boxcontainer=new DataSet();
+
+		/*Create Root, pointer toward the main box*/
+		root=NewQuadTreeBox();
+
+		}
+	/*}}}1*/
+	/*FUNCTION QuadTree::QuadTree(Mesh * t,long nbv){{{1*/
+	QuadTree::QuadTree(Mesh * t,long nbv){ 
+
+		/*Number of boxes and vertices*/
+		NbQuadTreeBox=0;
+		NbVertices=0;
+
+		/*Create container*/
+		boxcontainer=new DataSet();
+
+		/*Create Root, pointer toward the main box*/
+		root=NewQuadTreeBox();
+
+		/*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]);
+
+	}
+	/*}}}1*/
+	/*FUNCTION QuadTree::~QuadTree(){{{1*/
+	QuadTree::~QuadTree() {
+		delete boxcontainer;
+		root=NULL;
+	}
+	/*}}}1*/
+
+	/*Methods*/
+	/*FUNCTION QuadTree::Add{{{1*/
+	void  QuadTree::Add(BamgVertex &w){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, QuadTree.cpp/Add)*/
+		QuadTreeBox** pb=NULL;
+		QuadTreeBox*  b=NULL;
+
+		/*Get integer coodinate of current point w*/
+		register long i=w.i.x, j=w.i.y;
+
+		/*Initialize level*/
+		register long level=MaxISize;
+
+		/*Get inital box (the largest)*/
+		pb = &root;
+
+		/*Find the smallest box where w is located*/
+		while((b=*pb) && (b->nbitems<0)){ 
+
+			//shift b->nbitems by -1
+			b->nbitems--;
+
+			//shifted righ by one bit: level=00000010 -> 00000001
+			level >>= 1;
+
+			//Get next subbox according to the bit value (level)
+			pb = &b->b[IJ(i,j,level)];
+		}
+
+		/*OK, we have found b, a Subbox holding vertices (might be full)
+		  check that the vertex is not already in the box*/
+		if (b){      
+			if (b->nbitems > 3 &&  b->v[3] == &w) return;
+			if (b->nbitems > 2 &&  b->v[2] == &w) return;
+			if (b->nbitems > 1 &&  b->v[1] == &w) return;
+			if (b->nbitems > 0 &&  b->v[0] == &w) return;
+		}
+
+		/*check that l is not 0 (this should not happen as MaxDeep = 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 QuadTreeBox is full
+
+			/*Copy the 4 vertices in the current QuadTreebox*/
+			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*/
+				QuadTreeBox *bb = b->b[ij=IJ(v4[k]->i.x,v4[k]->i.y,level)];
+
+				// alloc the QuadTreeBox
+				if (!bb) bb=b->b[ij]=NewQuadTreeBox(); 
+
+				/*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 QuadTreeBox if necessary*/
+		if (!(b=*pb)) b=*pb= NewQuadTreeBox();
+
+		/*Add w*/
+		b->v[b->nbitems++]=&w;
+
+		//Increase NbVertices by one (we have one new vertex)
+		NbVertices++;
+	}
+	/*}}}1*/
+	/*FUNCTION QuadTree::NearestVertex{{{1*/
+	BamgVertex*  QuadTree::NearestVertex(Icoor1 i,Icoor1 j) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, QuadTree.cpp/NearestVertex)*/
+
+		/*Intermediaries*/
+		QuadTreeBox *pb[MaxDeep];
+		int          pi[MaxDeep];
+		Icoor1       ii[MaxDeep];
+		Icoor1       jj[MaxDeep];
+		int          level;
+		long         n0;
+		QuadTreeBox *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 QuadTreeBox 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)
+			QuadTreeBox *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 QuadTreeBox (macro)
+			j0 += J_IJ(k,hb2); // j orign of QuadTreeBox 
+			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{
+					QuadTreeBox* 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;
+
+	}
+	/*}}}1*/
+	/*FUNCTION QuadTree::NearestVertexWithNormal{{{1*/
+	BamgVertex*  QuadTree::NearestVertexWithNormal(Icoor1 i,Icoor1 j) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, QuadTree.cpp/NearestVertexWithNormal)*/
+
+		QuadTreeBox * pb[ MaxDeep ];
+		int  pi[ MaxDeep  ];
+		Icoor1 ii[  MaxDeep ], jj [ MaxDeep];
+		int l; // level
+		QuadTreeBox * b;
+		long     h =MaxISize,h0;
+		long     hb=MaxISize;
+		Icoor1  i0=0,j0=0;
+		Icoor1  iplus( i<MaxISize?(i<0?0:i):MaxISize-1);
+		Icoor1  jplus( j<MaxISize?(j<0?0:j):MaxISize-1);
+
+		BamgVertex *vn=0;
+
+		// init for optimisation ---
+		b = root;
+		register long  n0;
+		if (!root->nbitems)
+		 return vn; // empty tree 
+
+		while( (n0 = b->nbitems) < 0) 
+		  {
+			// search the non empty 
+			// QuadTreeBox containing  the point (i,j)
+			register Icoor1 hb2 = hb >> 1 ;
+			register  int k = IJ(iplus,jplus,hb2);// QuadTreeBox number of size hb2 contening i;j
+			register QuadTreeBox * b0= b->b[k];
+			if ( ( b0 == 0) || (b0->nbitems == 0) ) 
+			 break; // null box or empty   => break 	    
+			b=b0;	
+			i0 += I_IJ(k,hb2); // i orign of QuadTreeBox
+			j0 += J_IJ(k,hb2); // j orign of QuadTreeBox 
+			hb = hb2; 
+		  }
+
+
+		if ( n0 > 0) 
+		  {  
+			for(register int k=0;k<n0;k++)
+			  {
+				I2 i2 =  b->v[k]->i;
+				//   try if is in the right direction -- 
+				h0 = NORM(iplus,i2.x,jplus,i2.y);
+				if (h0 <h) {
+					h = h0;
+					vn = b->v[k];}
+			  }
+			if (vn) return vn; 
+		  }
+		// general case -----
+		// INITIALISATION OF THE HEAP 
+		l =0; // level 
+		pb[0]= b;
+		pi[0]=b->nbitems>0 ?(int)  b->nbitems : 4  ;
+		ii[0]=i0;
+		jj[0]=j0;
+		h=hb;
+		do {   // walk on the tree  
+			b= pb[l];
+			while (pi[l]--) // loop on 4 element of the box
+			  { 	      
+				int k = pi[l];
+
+				if (b->nbitems>0) // BamgVertex QuadTreeBox none empty
+				  { 
+					I2 i2 =  b->v[k]->i;
+					// if good direction when try -- 
+
+					h0 = NORM(iplus,i2.x,jplus,i2.y);
+					if (h0 <h) 
+					  {
+						h = h0;
+						vn = b->v[k];
+					  }
+				  }
+				else // Pointer QuadTreeBox 
+				  { 
+					register QuadTreeBox *b0=b;
+					if ((b=b->b[k])) 
+					  {
+						hb >>=1 ; // div by 2
+						register Icoor1 iii = ii[l]+I_IJ(k,hb);
+						register Icoor1 jjj = jj[l]+J_IJ(k,hb);
+
+						if  (INTER_SEG(iii,iii+hb,iplus-h,iplus+h) && INTER_SEG(jjj,jjj+hb,jplus-h,jplus+h)) 
+						  {
+							pb[++l]=  b;
+							pi[l]= b->nbitems>0 ?(int)  b->nbitems : 4  ;
+							ii[l]= iii;
+							jj[l]= jjj;
+
+						  }
+						else
+						 b=b0, hb <<=1 ;
+					  }
+					else
+					 b=b0;
+				  }
+			  }
+			hb <<= 1; // mul by 2 
+		} while (l--);
+
+		return vn;
+	}
+	/*}}}1*/
+	/*FUNCTION QuadTree::NewQuadTreeBox {{{1*/
+	QuadTree::QuadTreeBox* QuadTree::NewQuadTreeBox(void){
+
+		/*Output*/
+		QuadTreeBox* newbox=NULL;
+
+		/*Create and initialize a new box*/
+		newbox=new QuadTreeBox;
+		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*/
+		NbQuadTreeBox++;
+
+		/*currentbox now points toward next quadtree box*/
+		return newbox;
+	}/*}}}*/
+	/*FUNCTION QuadTree::ToClose {{{1*/
+	BamgVertex*   QuadTree::ToClose(BamgVertex & v,double seuil,Icoor1 hx,Icoor1 hy){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, QuadTree.cpp/ToClose)*/
+
+		const Icoor1 i=v.i.x;
+		const Icoor1 j=v.i.y;
+		const R2 X(v.r);
+		const Metric  Mx(v.m);
+
+		QuadTreeBox * pb[ MaxDeep ];
+		int  pi[ MaxDeep  ];
+		Icoor1 ii[  MaxDeep ], jj [ MaxDeep];
+		register int l=0; // level
+		register QuadTreeBox * b;
+		Icoor1 h=MaxISize;
+		Icoor1 hb =  MaxISize;
+		Icoor1 i0=0,j0=0;
+
+		//  BamgVertex *vn=0;
+
+		if (!root->nbitems)
+		 return 0; // empty tree 
+
+		// general case -----
+		pb[0]=root;
+		pi[0]=root->nbitems>0 ?(int)  root->nbitems : 4  ;
+		ii[0]=i0;
+		jj[0]=j0;
+		h=hb;
+		do {    
+			b= pb[l];
+			while (pi[l]--){ 	      
+				register int k = pi[l];
+
+				if (b->nbitems>0){ // BamgVertex QuadTreeBox none empty
+					I2 i2 =  b->v[k]->i;
+					if ( ABS(i-i2.x) <hx && ABS(j-i2.y) <hy )
+					  {
+						R2 XY(X,b->v[k]->r);
+						double dd;
+						if( (dd= LengthInterpole(Mx(XY), b->v[k]->m(XY)))  < seuil ){
+							return b->v[k]; 
+						}
+					  }
+				}
+				else{ // Pointer QuadTreeBox 
+					register QuadTreeBox *b0=b;
+					if ((b=b->b[k])){
+						hb >>=1 ; // div by 2
+						register long iii = ii[l]+I_IJ(k,hb);
+						register long jjj = jj[l]+J_IJ(k,hb);
+
+						if  (INTER_SEG(iii,iii+hb,i-hx,i+hx) && INTER_SEG(jjj,jjj+hb,j-hy,j+hy)){
+							pb[++l]=  b;
+							pi[l]= b->nbitems>0 ?(int)  b->nbitems : 4  ;
+							ii[l]= iii;
+							jj[l]= jjj;
+
+						}
+						else{
+							b=b0;
+							hb <<=1 ;
+						}
+					}
+					else{
+						b=b0;
+					}
+				}
+			}
+			hb <<= 1; // mul by 2 
+		} while (l--);
+
+		return 0;
+	}
+	/*}}}1*/
+}
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/QuadTree.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/QuadTree.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/QuadTree.h	(revision 11330)
@@ -0,0 +1,66 @@
+/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, QuadTree.h)*/
+#ifndef _QUADTREE_H
+#define _QUADTREE_H
+
+#include "./include.h"
+
+namespace bamg {
+
+	const int  MaxDeep  = 30;
+	const long MaxISize = ( 1L << MaxDeep);  // = 2^30 : 010000000000..000 (bitwise operation)
+
+	class BamgVertex;
+
+	class QuadTree{
+
+		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 QuadTreeBox: public Object{ 
+				public:
+					int nbitems; // number of current vertices in the box
+					union{
+						QuadTreeBox* b[4];
+						BamgVertex*  v[4];
+					};
+					/*Object functions*/
+					void  Echo(){_error_("not implemented yet");};
+					void  DeepEcho(){_error_("not implemented yet");};
+					int   Id(){_error_("not implemented yet");};
+					int   MyRank(){_error_("not implemented yet");};
+					#ifdef _SERIAL_
+					void  Marshall(char** pmarshalled_dataset){_error_("not implemented yet");};
+					int   MarshallSize(){_error_("not implemented yet");};
+					void  Demarshall(char** pmarshalled_dataset){_error_("not implemented yet");};
+					#endif
+					int   ObjectEnum(){_error_("not implemented yet");};
+					Object* copy(){_error_("not implemented yet");};
+			};
+
+			/*QuadTree private Fields*/
+			DataSet* boxcontainer;
+
+		public:
+
+			/*QuadTree public Fields*/
+			QuadTreeBox* root;
+			long         NbQuadTreeBox;
+			long         NbVertices;
+
+			QuadTree();
+			QuadTree(Mesh *t,long nbv=-1);
+			~QuadTree();
+
+			BamgVertex*  NearestVertex(Icoor1 i,Icoor1 j);
+			BamgVertex*  NearestVertexWithNormal(Icoor1 i,Icoor1 j);
+			QuadTreeBox* NewQuadTreeBox(void);
+			BamgVertex*  ToClose(BamgVertex & ,double ,Icoor1,Icoor1);
+			void         Add( BamgVertex & w);
+
+	};
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/R2.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/R2.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/R2.h	(revision 11330)
@@ -0,0 +1,105 @@
+/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, R2.h)*/
+#ifndef _R2_H
+#define _R2_H
+
+#include <cstdio>
+
+namespace bamg {
+
+	template <class R,class RR> class P2{
+
+		  public:  
+
+			  //fields
+			  R x,y;
+
+			  //functions
+			  P2 () :x(0),y(0) {};
+			  P2 (R a,R b)  :x(a),y(b)  {}
+			  P2 (P2 A,P2 B) : x(B.x-A.x),y(B.y-A.y) {}
+			  void Echo(){
+				  printf("Member of P2:\n");
+				  printf("   x: %g or %i\n",x,x);
+				  printf("   y: %g or %i\n",y,y);
+			  }
+			  //operators
+			  RR       operator,(const P2<R,RR> & cc) const {return  (RR) x* (RR) cc.x+(RR) y* (RR) cc.y;} //scalar product
+			  P2<R,RR> operator+(const P2<R,RR> & cc) const {return P2<R,RR>(x+cc.x,y+cc.y);}
+			  P2<R,RR> operator-(const P2<R,RR> & cc) const {return P2<R,RR>(x-cc.x,y-cc.y);}
+			  P2<R,RR> operator-()  const{return P2<R,RR>(-x,-y);}
+			  P2<R,RR> operator*(R  cc) const {return P2<R,RR>(x*cc,y*cc);}
+			  P2<R,RR> operator/(R  cc) const {return P2<R,RR>(x/cc,y/cc);}
+			  P2<R,RR> operator+=(const  P2<R,RR> & cc) {x += cc.x;y += cc.y;return *this;}
+			  P2<R,RR> operator/=(const  R r) {x /= r;y /= r;return *this;}
+			  P2<R,RR> operator*=(const  R r) {x *= r;y *= r;return *this;}
+			  P2<R,RR> operator-=(const  P2<R,RR> & cc) {x -= cc.x;y -= cc.y;return *this;}
+
+	  };
+
+	template <class R,class RR> class P2xP2{
+
+		  private:
+
+			  friend P2<R,RR> operator*(P2<R,RR> c,P2xP2<R,RR> cc){
+				  return P2<R,RR>(c.x*cc.x.x + c.y*cc.y.x, c.x*cc.x.y + c.y*cc.y.y);
+			  } 
+		  public:
+
+			  //fields
+			  P2<R,RR> x,y; 
+
+			  //functions
+			  P2xP2 (): x(),y()  {}
+			  P2xP2 (P2<R,RR> a,P2<R,RR> b): x(a),y(b) {}
+			  P2xP2 (P2<R,RR> a,P2<R,RR> b,P2<R,RR> c ): x(b-a),y(c-a) {}
+			  P2xP2 (R xx,R xy,R yx,R yy) :x(xx,xy),y(yx,yy) {}
+			  void Echo(){
+				  printf("Member of P2xP2:\n");
+				  printf("   x.x: %g   x.y: %g\n",x.x,x.y);
+				  printf("   y.x: %g   y.x: %g\n",y.x,y.y);
+			  }
+			  RR          det() const {return (RR) x.x* (RR) y.y - (RR) x.y * (RR) y.x;}
+			  P2xP2<R,RR> inv()  const{
+				  RR d = (*this).det(); 
+				  return P2xP2<R,RR>((R)( y.y /d) ,(R)(-x.y/d),(R)( -y.x/d) ,(R)( x.x/d) );
+			  };
+			  P2xP2<R,RR> t()  {return P2xP2<R,RR>(x.x,y.x,x.y,y.y);} //transposer 
+			  P2<R,RR>    tx() {return P2<R,RR>(x.x,y.x);} 
+			  P2<R,RR>    ty() {return P2<R,RR>(x.y,y.y);} 
+			  //Operators
+			  P2<R,RR>     operator*(const P2<R,RR>& c) const {return P2<R,RR>(x.x*c.x + x.y*c.y, y.x*c.x + y.y*c.y);}
+			  P2xP2<R,RR>  operator*(P2xP2<R,RR> c) const{
+				  return  P2xP2<R,RR>(x.x*c.x.x + x.y*c.y.x,
+							  x.x*c.x.y + x.y*c.y.y,
+							  y.x*c.x.x + y.y*c.y.x,
+							  y.x*c.x.y + y.y*c.y.y);
+			  }
+	  };  
+
+	//inline functions
+	template  <class R,class RR>  
+	  inline RR Det(const P2<R,RR> x,const P2<R,RR> y) {
+		  return (RR) x.x * (RR) y.y - (RR) x.y * (RR) y.x ;
+	  } 
+	template  <class R,class RR>  
+	  inline RR Area2 (const P2<R,RR> a,const P2<R,RR> b,const P2<R,RR> c) {
+		  return Det(b-a,c-a) ;
+	  }
+	template  <class R,class RR>  
+	  inline R Norme1 (const P2<R,RR> x) {
+		  return (Abs(x.x)+Abs(x.y)) ;
+	  } 
+	template  <class R,class RR>  
+	  inline RR Norme2_2 (const P2<R,RR> x) {
+		  return (RR)x.x*(RR)x.x + (RR)x.y*(RR)x.y ;
+	  } 
+	template  <class R,class RR>  
+	  inline RR Norme2 (const P2<R,RR> x) {
+		  return sqrt((RR)x.x*(RR)x.x + (RR)x.y*(RR)x.y) ;
+	  } 
+	template  <class R,class RR>  
+	  inline P2<R,RR> Orthogonal (const P2<R,RR> x) {
+		  return  P2<R,RR>(-x.y,x.x);
+	  } 
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/SetOfE4.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/SetOfE4.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/SetOfE4.cpp	(revision 11330)
@@ -0,0 +1,120 @@
+#include "../objects.h"
+
+using namespace std;
+namespace bamg {
+
+	/*Constructor*/
+	/*FUNCTION  SetOfEdges4::SetOfEdges4(long mmx,long nnx){{{1*/
+	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;
+	}
+	/*}}}1*/
+
+	/*Methods*/ 
+	/*FUNCTION  SetOfEdges4::add{{{1*/
+	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=%i > nbax=%i",NbOfEdges,nbax);
+		}
+
+		//update chain
+		Edges[NbOfEdges].i=ii;
+		Edges[NbOfEdges].j=jj;
+		Edges[NbOfEdges].next= head[h];
+		head[h] = NbOfEdges;
+		return NbOfEdges ++;
+	}
+	/*}}}1*/
+	/*FUNCTION  SetOfEdges4::find {{{1*/
+	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;
+	}
+	/*}}}1*/
+	/*FUNCTION  SetOfEdges4::i{{{1*/
+	long SetOfEdges4::i(long k){
+		return Edges[k].i;
+	}
+	/*}}}1*/
+	/*FUNCTION  SetOfEdges4::j{{{1*/
+	long SetOfEdges4::j(long k){
+		return Edges[k].j;
+	}
+	/*}}}1*/
+	/*FUNCTION  SetOfEdges4::nb{{{1*/
+	long SetOfEdges4::nb(){
+		return NbOfEdges;
+	}
+	/*}}}1*/
+	/*FUNCTION  SetOfEdges4::newarete{{{1*/
+	long SetOfEdges4::newarete(long k){
+		return NbOfEdges == k+1;
+	}
+	/*}}}1*/
+	/*FUNCTION  SetOfEdges4::SortAndAdd{{{1*/
+	long SetOfEdges4::SortAndAdd (long ii,long jj) {
+		return ii <=jj ? add (ii,jj)  : add (jj,ii) ;
+	}
+	/*}}}1*/
+	/*FUNCTION  SetOfEdges4::SortAndFind{{{1*/
+	long SetOfEdges4::SortAndFind (long ii,long jj) {
+		return ii <=jj ? find (ii,jj)  : find (jj,ii) ;
+	}
+	/*}}}1*/
+}
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/SetOfE4.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/SetOfE4.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/SetOfE4.h	(revision 11330)
@@ -0,0 +1,42 @@
+#ifndef _SetOfEdge4_h
+#define _SetOfEdge4_h
+
+namespace bamg {
+
+	class SetOfEdges4;
+
+	class IntEdge{
+		friend class SetOfEdges4;
+		public:
+		long i,j;
+		long next; 
+	};
+
+	class SetOfEdges4 {
+
+		private:
+			long nx,nbax,NbOfEdges;
+			long* head; 
+			IntEdge* Edges;
+
+		public:
+
+			// Constructors
+			SetOfEdges4(long ,long);// nb Edges mx , nb de sommet 
+			~SetOfEdges4() {delete [] head; delete [] Edges;}
+
+			//operators
+			IntEdge & operator[](long k){return  Edges[k];}
+
+			//Methods
+			long add (long ii,long jj);
+			long SortAndAdd (long ii,long jj);
+			long nb();
+			long find (long ii,long jj);
+			long SortAndFind (long ii,long jj);
+			long i(long k);
+			long j(long k);
+			long newarete(long k);
+	};
+}
+#endif 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/SubDomain.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/SubDomain.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/SubDomain.cpp	(revision 11330)
@@ -0,0 +1,28 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "SubDomain.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+
+	/*Methods*/
+	/*FUNCTION SubDomain::Set {{{1*/
+	void SubDomain::Set(const Mesh & Th ,long i,Mesh & ThNew){
+		*this = Th.subdomains[i];
+		if ( head-Th.triangles<0 || head-Th.triangles>=Th.nbt){
+			_error_("head-Th.triangles<0 || head-Th.triangles>=Th.nbt");
+		}
+		head = ThNew.triangles + Th.GetId(head) ; 
+		if (edge-Th.edges<0 || edge-Th.edges>=Th.nbe);{
+			_error_("edge-Th.edges<0 || edge-Th.edges>=Th.nbe");
+		}
+		edge = ThNew.edges+ Th.GetId(edge);
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/SubDomain.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/SubDomain.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/SubDomain.h	(revision 11330)
@@ -0,0 +1,27 @@
+#ifndef _SUBDOMAIN_H_
+#define _SUBDOMAIN_H_
+
+#include "./include.h"
+#include "./Edge.h"
+
+namespace bamg {
+
+	//classes
+	class Triangle;
+	class Mesh;
+
+	class SubDomain {
+
+		public:
+
+			Triangle *head;
+			long      ReferenceNumber;
+			int       direction;   // -1 or 1
+			Edge     *edge;        // to geometrical
+
+			//Methods
+			void Set(const Mesh &,long,Mesh &);
+	};
+
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Triangle.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Triangle.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Triangle.cpp	(revision 11330)
@@ -0,0 +1,440 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "../objects.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION Triangle(){{{1*/
+	Triangle::Triangle(void){
+
+	}
+	/*}}}*/
+	/*FUNCTION Triangle(Mesh *Th,long i,long j,long k) {{{1*/
+	Triangle::Triangle(Mesh *Th,long i,long j,long k) {
+		BamgVertex *v=Th->vertices;
+		long nbv = Th->nbv;
+		if (i<0 || j<0 || k<0){
+			_error_("i<0 || j<0 || k<0");
+		}
+		if (i>=nbv || j>=nbv || k>=nbv){
+			_error_("i>=nbv || j>=nbv || k>=nbv");
+		}
+		vertices[0]=v+i;
+		vertices[1]=v+j;
+		vertices[2]=v+k;
+		adj[0]=adj[1]=adj[2]=0;
+		AdjEdgeIndex[0]=AdjEdgeIndex[1]=AdjEdgeIndex[2]=0;
+		det=0;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle(BamgVertex *v0,BamgVertex *v1,BamgVertex *v2) {{{1*/
+	Triangle::Triangle(BamgVertex *v0,BamgVertex *v1,BamgVertex *v2){
+		vertices[0]=v0;
+		vertices[1]=v1;
+		vertices[2]=v2;
+		adj[0]=adj[1]=adj[2]=0;
+		AdjEdgeIndex[0]=AdjEdgeIndex[1]=AdjEdgeIndex[2]=0;
+		if (v0) det=0;
+		else {
+			det=-1;
+			link=NULL;};  
+	}
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION Triangle::Adj{{{1*/
+	AdjacentTriangle Triangle::Adj(int i)  const {
+		return AdjacentTriangle(adj[i],AdjEdgeIndex[i]&3);
+	};/*}}}*/
+	/*FUNCTION Triangle::Echo {{{1*/
+	void Triangle::Echo(void){
+
+		int i;
+
+		printf("Triangle:\n");
+		printf("   vertices pointer towards three vertices\n");
+		printf("      vertices[0] vertices[1] vertices[2] = %p %p %p\n",vertices[0],vertices[1],vertices[2]);
+		printf("   adj pointer towards three adjacent triangles\n");
+		printf("      adj[0] adj[1] adj[2] = %p %p %p\n",adj[0],adj[1],adj[2]);
+		printf("   det (integer triangle determinant) = %i\n",det);
+		if (link){
+			printf("   link (pointer toward duplicate triangle)= %p\n",link);
+		}
+		else{
+			printf("   color = %i\n",color);
+		}
+
+		printf("\nThree vertices:\n");
+		for(i=0;i<3;i++){
+			if (vertices[i]){
+				vertices[i]->Echo();
+			}
+			else{
+				printf("   vertex %i does not exist\n",i+1);
+			}
+		}
+
+		return;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::FindBoundaryEdge{{{1*/
+	AdjacentTriangle Triangle::FindBoundaryEdge(int i) const{
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FindBoundaryEdge)*/
+
+		/*Intermediary*/
+		Triangle* ttc=NULL;
+		int k,j,jc;
+
+		// call current triangle t
+		Triangle* t = (Triangle*)this;
+
+		//is the current triangle inside or outside?
+		int outside=!link  ;
+
+		// EdgesVertexTriangle[3][2] = {{1,2},{2,0},{0,1}};
+		// initialize j as the first vertex of the ith edge
+		j=EdgesVertexTriangle[i][0];
+
+		//Loop over the adjacent triangle of t
+		k=0;
+		do{
+			//keep track of outside
+			int outsidep = outside;
+			//increment k
+			k++;
+			//Get ttc, adjacent triangle of t with respect to vertex j
+			ttc =  t->adj[j];
+			//is the current triangle inside or outside?
+			outside = !ttc->link;
+			//if both previous triangle are outside, return
+			if (outside+outsidep == 1) return AdjacentTriangle(t,j);
+
+			//update t and j
+			t = ttc;
+			//NextEdge[3] = {1,2,0};
+			jc = NextEdge[t->AdjEdgeIndex[j]&3];
+			j = NextEdge[jc];
+
+			//check number of iterations
+			if (k>=2000){
+				_error_("too many iteration in Triangle::FindBoundaryEdge (k>=2000)");
+			}
+		} while (this!= t);
+		//not found, return empty triangle
+		return AdjacentTriangle(NULL,0);
+	}
+	/*}}}1*/
+	/*FUNCTION Triangle::GetAllflag{{{1*/
+	int    Triangle::GetAllflag(int a){
+		return AdjEdgeIndex[a] & 1020;
+	}/*}}}*/
+	/*FUNCTION Triangle::Hidden{{{1*/
+	int    Triangle::Hidden(int a)const {
+		return AdjEdgeIndex[a]&16;
+	} /*}}}*/
+	/*FUNCTION Triangle::Locked{{{1*/
+	int    Triangle::Locked(int a)const {
+		return AdjEdgeIndex[a]&4;
+	} /*}}}*/
+	/*FUNCTION Triangle::NuEdgeTriangleAdj{{{1*/
+	short  Triangle::NuEdgeTriangleAdj(int i) const {
+		/*Number of the  adjacent edge in adj tria (make sure it is between 0 and 2*/
+		return AdjEdgeIndex[i&3]&3;
+	}/*}}}*/
+	/*FUNCTION Triangle::Optim{{{1*/
+	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;
+	}
+	/*}}}1*/
+	/*FUNCTION Triangle::Quadrangle {{{1*/
+	Triangle* Triangle::Quadrangle(BamgVertex * & v0,BamgVertex * & v1,BamgVertex * & v2,BamgVertex * & v3) const{
+		// return the other triangle of the quad if a quad or 0 if not a quat
+		Triangle * t =0;
+		if (link) {
+			int a=-1;
+			if (AdjEdgeIndex[0] & 16 ) a=0;
+			if (AdjEdgeIndex[1] & 16 ) a=1;
+			if (AdjEdgeIndex[2] & 16 ) a=2;
+			if (a>=0) {
+				t = adj[a];
+				//  if (t-this<0) return 0;
+				v2 = vertices[VerticesOfTriangularEdge[a][0]];
+				v0 = vertices[VerticesOfTriangularEdge[a][1]];
+				v1 = vertices[OppositeEdge[a]];
+				v3 = t->vertices[OppositeEdge[AdjEdgeIndex[a]&3]];
+			}
+		}
+		return t;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::QualityQuad {{{1*/
+	double   Triangle::QualityQuad(int a,int option) const{
+		double q;
+		if (!link || AdjEdgeIndex[a] &4)
+		 q=  -1;
+		else {
+			Triangle * t = adj[a];
+			if (t-this<0) q=  -1;// because we do 2 times 
+			else if (!t->link ) q=  -1;
+			else if (AdjEdgeIndex[0] & 16 || AdjEdgeIndex[1] & 16  || AdjEdgeIndex[2] & 16 || t->AdjEdgeIndex[0] & 16 || t->AdjEdgeIndex[1] & 16 || t->AdjEdgeIndex[2] & 16 )
+			 q= -1;
+			else if(option){ 
+				const BamgVertex & v2 = *vertices[VerticesOfTriangularEdge[a][0]];
+				const BamgVertex & v0 = *vertices[VerticesOfTriangularEdge[a][1]];
+				const BamgVertex & v1 = *vertices[OppositeEdge[a]];
+				const BamgVertex & v3 = * t->vertices[OppositeEdge[AdjEdgeIndex[a]&3]];
+				q =  QuadQuality(v0,v1,v2,v3); // do the float part
+			}
+			else q= 1;
+		}
+		return  q;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::Renumbering(Triangle *tb,Triangle *te, long *renu){{{1*/
+	void  Triangle::Renumbering(Triangle *tb,Triangle *te, long *renu){
+
+		if (link  >=tb && link  <te) link  = tb + renu[link -tb];
+		if (adj[0] >=tb && adj[0] <te) adj[0] = tb + renu[adj[0]-tb];
+		if (adj[1] >=tb && adj[1] <te) adj[1] = tb + renu[adj[1]-tb];
+		if (adj[2] >=tb && adj[2] <te) adj[2] = tb + renu[adj[2]-tb];    
+	}/*}}}*/
+	/*FUNCTION Triangle::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){{{1*/
+	void Triangle::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){
+		if (vertices[0] >=vb && vertices[0] <ve) vertices[0] = vb + renu[vertices[0]-vb];
+		if (vertices[1] >=vb && vertices[1] <ve) vertices[1] = vb + renu[vertices[1]-vb];
+		if (vertices[2] >=vb && vertices[2] <ve) vertices[2] = vb + renu[vertices[2]-vb];    
+	}/*}}}*/
+	/*FUNCTION Triangle::Set {{{1*/
+	void Triangle::Set(const Triangle & rec,const Mesh & Th ,Mesh & ThNew){ 
+		*this = rec;
+		if ( vertices[0] ) vertices[0] = ThNew.vertices +  Th.GetId(vertices[0]);
+		if ( vertices[1] ) vertices[1] = ThNew.vertices +  Th.GetId(vertices[1]);
+		if ( vertices[2] ) vertices[2] = ThNew.vertices +  Th.GetId(vertices[2]);
+		if(adj[0]) adj[0] =  ThNew.triangles + Th.GetId(adj[0]);
+		if(adj[1]) adj[1] =  ThNew.triangles + Th.GetId(adj[1]);
+		if(adj[2]) adj[2] =  ThNew.triangles + Th.GetId(adj[2]);
+		if (link  >= Th.triangles && link  < Th.triangles + Th.nbt)
+		 link = ThNew.triangles + Th.GetId(link);
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::SetAdjAdj{{{1*/
+	void Triangle::SetAdjAdj(short a){
+		// Copy all the mark 
+		a &= 3;
+		register Triangle *tt=adj[a];
+		AdjEdgeIndex [a] &= 55; // remove MarkUnSwap
+		register short aatt = AdjEdgeIndex[a] & 3;
+		if(tt){ 
+			tt->adj[aatt]=this;
+			tt->AdjEdgeIndex[aatt]=a + (AdjEdgeIndex[a] & 60 ) ;
+		}
+	}/*}}}*/
+	/*FUNCTION Triangle::SetAdj2{{{1*/
+	void Triangle::SetAdj2(short a,Triangle *t,short aat){
+		/*For current triangle:
+		 * - a is the index of the edge were the adjency is set (in [0 2])
+		 * - t is the adjacent triangle
+		 * - aat is the index of the same edge in the adjacent triangle*/
+		adj[a]=t;
+		AdjEdgeIndex[a]=aat;
+		if(t){ //if t!=NULL add adjacent triangle to t (this)
+			t->adj[aat]=this;
+			t->AdjEdgeIndex[aat]=a;
+		}
+	}/*}}}*/
+	/*FUNCTION Triangle::SetAllFlag{{{1*/
+	void   Triangle::SetAllFlag(int a,int f){
+		AdjEdgeIndex[a] = (AdjEdgeIndex[a] &3) + (1020 & f);
+	}/*}}}*/
+	/*FUNCTION Triangle::SetDet{{{1*/
+	void Triangle::SetDet() {
+		if(vertices[0] && vertices[1] && vertices[2])    det = bamg::det(*vertices[0],*vertices[1],*vertices[2]);
+		else det = -1; 
+	}/*}}}*/
+	/*FUNCTION Triangle::SetHidden{{{1*/
+	void Triangle::SetHidden(int a){
+		//Get Adjacent Triangle number a
+		register Triangle* t = adj[a];
+		//if it exist
+		//C|=D -> C=(C|D) bitwise inclusive OR
+		if(t) t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] |=16;
+		AdjEdgeIndex[a] |= 16;
+	}/*}}}*/
+	/*FUNCTION Triangle::SetLocked{{{1*/
+	void Triangle::SetLocked(int a){
+		//mark the edge as on Boundary
+		register Triangle * t = adj[a];
+		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] |=4;
+		AdjEdgeIndex[a] |= 4;
+	}/*}}}*/
+	/*FUNCTION Triangle::SetMarkUnSwap{{{1*/
+	void Triangle::SetMarkUnSwap(int a){
+		register Triangle * t = adj[a];
+		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] |=8;
+		AdjEdgeIndex[a] |=8 ;
+	}/*}}}*/
+	/*FUNCTION Triangle::SetSingleVertexToTriangleConnectivity{{{1*/
+	void Triangle::SetSingleVertexToTriangleConnectivity() { 
+		if (vertices[0]) (vertices[0]->t=this,vertices[0]->IndexInTriangle=0);
+		if (vertices[1]) (vertices[1]->t=this,vertices[1]->IndexInTriangle=1);
+		if (vertices[2]) (vertices[2]->t=this,vertices[2]->IndexInTriangle=2);
+	}/*}}}*/
+	/*FUNCTION Triangle::SetUnMarkUnSwap{{{1*/
+	void Triangle::SetUnMarkUnSwap(int a){ 
+		register Triangle * t = adj[a];
+		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] &=55; // 23 + 32 
+		AdjEdgeIndex[a] &=55 ;
+	}/*}}}*/
+	/*FUNCTION Triangle::swap{{{1*/
+	int Triangle::swap(short a,int koption){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/swap)*/
+
+		if(a/4 !=0) return 0;// arete lock or MarkUnSwap
+
+		register Triangle *t1=this,*t2=adj[a];// les 2 triangles adjacent
+		register short a1=a,a2=AdjEdgeIndex[a];// les 2 numero de l arete dans les 2 triangles
+		if(a2/4 !=0) return 0; // arete lock or MarkUnSwap
+
+		register BamgVertex  *sa=t1->vertices[VerticesOfTriangularEdge[a1][0]];
+		register BamgVertex  *sb=t1->vertices[VerticesOfTriangularEdge[a1][1]];
+		register BamgVertex  *s1=t1->vertices[OppositeVertex[a1]];
+		register BamgVertex  *s2=t2->vertices[OppositeVertex[a2]];
+
+		Icoor2 det1=t1->det , det2=t2->det ;
+		Icoor2 detT = det1+det2;
+		Icoor2 detA = Abs(det1) + Abs(det2);
+		Icoor2 detMin = Min(det1,det2);
+
+		int OnSwap = 0;       
+		// si 2 triangle infini (bord) => detT = -2;
+		if (sa == 0) {// les deux triangles sont frontieres
+			det2=bamg::det(s2->i,sb->i,s1->i);
+			OnSwap = det2 >0;}
+		else if (sb == 0) { // les deux triangles sont frontieres
+			det1=bamg::det(s1->i,sa->i,s2->i);
+			OnSwap = det1 >0;}
+		else if(( s1 != 0) && (s2 != 0) ) {
+			det1 = bamg::det(s1->i,sa->i,s2->i);
+			det2 = detT - det1;
+			OnSwap = (Abs(det1) + Abs(det2)) < detA;
+
+			Icoor2 detMinNew=Min(det1,det2);
+			//     if (detMin<0 && (Abs(det1) + Abs(det2) == detA)) OnSwap=BinaryRand();// just for test   
+			if (! OnSwap &&(detMinNew>0)) {
+				OnSwap = detMin ==0;
+				if (! OnSwap) {
+					int  kopt = koption;
+					while (1)
+					 if(kopt) {
+						 // critere de Delaunay pure isotrope
+						 register Icoor2 xb1 = sb->i.x - s1->i.x,
+									 x21 = s2->i.x - s1->i.x,
+									 yb1 = sb->i.y - s1->i.y,
+									 y21 = s2->i.y - s1->i.y,
+									 xba = sb->i.x - sa->i.x, 
+									 x2a = s2->i.x - sa->i.x,
+									 yba = sb->i.y - sa->i.y,
+									 y2a = s2->i.y - sa->i.y;
+						 register double
+							cosb12 =  double(xb1*x21 + yb1*y21),
+									 cosba2 =  double(xba*x2a + yba*y2a) ,
+									 sinb12 = double(det2),
+									 sinba2 = double(t2->det);
+
+
+						 // angle b12 > angle ba2 => cotg(angle b12) < cotg(angle ba2)
+						 OnSwap =  ((double) cosb12 * (double)  sinba2) <  ((double) cosba2 * (double) sinb12);
+						 break;
+					 }
+					 else {	
+						 // critere de Delaunay anisotrope 
+						 double som;
+						 I2 AB=(I2) *sb - (I2) *sa;
+						 I2 MAB2=((I2) *sb + (I2) *sa);
+						 R2 MAB(MAB2.x*0.5,MAB2.y*0.5);
+						 I2 A1=(I2) *s1 - (I2) *sa;
+						 I2 D = (I2) * s1 - (I2) * sb ;
+						 R2 S2(s2->i.x,s2->i.y);
+						 R2 S1(s1->i.x,s1->i.y);
+							{
+							 Metric M=s1->m;
+							 R2 ABo = M.Orthogonal(AB);
+							 R2 A1o = M.Orthogonal(A1);
+							 // (A+B)+ x ABo = (S1+B)/2+ y A1 
+							 // ABo x - A1o y =  (S1+B)/2-(A+B)/2 = (S1-B)/2 = D/2
+							 double dd = Abs(ABo.x*A1o.y)+Abs(ABo.y*A1o.x);
+							 double d = (ABo.x*A1o.y - ABo.y*A1o.x)*2; // because D/2
+							 if (Abs(d) > dd*1.e-3) {
+								 R2 C(MAB+ABo*((D.x*A1o.y - D.y*A1o.x)/d));
+								 som  = M(C - S2)/M(C - S1);
+							 } else 
+								{kopt=1;continue;}
+
+							}
+							{
+							 Metric M=s2->m;
+							 R2 ABo = M.Orthogonal(AB);
+							 R2 A1o = M.Orthogonal(A1);
+							 // (A+B)+ x ABo = (S1+B)/2+ y A1 
+							 // ABo x - A1o y =  (S1+B)/2-(A+B)/2 = (S1-B)/2 = D/2 
+							 double dd = Abs(ABo.x*A1o.y)+Abs(ABo.y*A1o.x);
+							 double d = (ABo.x*A1o.y - ABo.y*A1o.x)*2; // because D/2
+							 if(Abs(d) > dd*1.e-3) {
+								 R2 C(MAB+ABo*((D.x*A1o.y - D.y*A1o.x)/d));
+								 som  += M(C - S2)/M(C -  S1);
+							 } else 
+								{kopt=1;continue;}
+							}
+						 OnSwap = som < 2;
+						 break;
+					 }
+
+				} // OnSwap 
+			} // (! OnSwap &&(det1 > 0) && (det2 > 0) )
+		}
+		if( OnSwap ) 
+		 bamg::swap(t1,a1,t2,a2,s1,s2,det1,det2);
+		else {
+			t1->SetMarkUnSwap(a1);     
+		}
+		return OnSwap;
+	}
+	/*}}}1*/
+	/*FUNCTION Triangle::TriangleAdj{{{1*/
+	Triangle* Triangle::TriangleAdj(int i) const {
+		return adj[i&3];
+	}/*}}}*/
+
+}
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/Triangle.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/Triangle.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/Triangle.h	(revision 11330)
@@ -0,0 +1,74 @@
+#ifndef _TRIANGLE_H_
+#define _TRIANGLE_H_
+
+#include "./include.h"
+#include "AdjacentTriangle.h"
+
+namespace bamg {
+
+	//classes
+	class Mesh;
+	class BamgVertex;
+	class Triangle;
+
+	class Triangle {
+
+		friend class AdjacentTriangle;
+
+		private:
+			BamgVertex *vertices[3];        // 3 vertices if t is triangle, t[i] allowed by access function, (*t)[i] if pointer
+			Triangle   *adj[3];             // 3 pointers toward the adjacent triangles
+			short       AdjEdgeIndex[3];   // edge id in the adjacent triangles. The edge number 1 is the edge number AdjEdgeIndex[1] in the Adjacent triangle 1
+
+		public: 
+			Icoor2 det; //Integer determinant (twice its area)
+			union { 
+				Triangle *link;
+				long      color;
+			};
+
+			//Constructors/Destructors
+			Triangle();
+			Triangle(Mesh *Th,long i,long j,long k);
+			Triangle(BamgVertex *v0,BamgVertex *v1,BamgVertex *v2);
+
+			//Operators
+			const BamgVertex & operator[](int i) const {return *vertices[i];};
+			BamgVertex & operator[](int i)  {return *vertices[i];};
+			const BamgVertex * operator()(int i) const {return vertices[i];};
+			BamgVertex * & operator()(int i)  {return vertices[i];};
+
+			//Methods
+			void              Echo();
+			int               swap(short a1,int=0);
+			long              Optim(short a,int =0);
+			int               Locked(int a)const;
+			int               Hidden(int a)const;
+			int               GetAllflag(int a);
+			void              SetAllFlag(int a,int f);
+			double            QualityQuad(int a,int option=1) const;
+			short             NuEdgeTriangleAdj(int i) const;
+			AdjacentTriangle  FindBoundaryEdge(int  i) const;
+			AdjacentTriangle  Adj(int i) const;
+			Triangle         *TriangleAdj(int i) const;
+			Triangle         *Quadrangle(BamgVertex  *& v0,BamgVertex *& v1,BamgVertex *& v2,BamgVertex *& v3) const;
+			void              Renumbering(Triangle   *tb,Triangle *te, long *renu);
+			void              Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu);
+			void              SetAdjAdj(short a);
+			void              SetAdj2(short a,Triangle *t,short aat);
+			void              SetSingleVertexToTriangleConnectivity();
+			void              SetHidden(int a);
+			void              SetLocked(int a);
+			void              SetMarkUnSwap(int a);
+			void              SetUnMarkUnSwap(int a);
+			void              SetDet();
+
+			//Inline methods
+			double qualite() ;
+			void  Set(const Triangle &,const Mesh &,Mesh &);
+			int   In(BamgVertex *v) const { return vertices[0]==v || vertices[1]==v || vertices[2]==v ;}
+
+	};
+
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnEdge.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnEdge.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnEdge.cpp	(revision 11330)
@@ -0,0 +1,25 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "VertexOnEdge.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Methods*/
+	/*FUNCTION VertexOnEdge::Set {{{1*/
+	void VertexOnEdge::Set(const Mesh & Th ,long i,Mesh & ThNew){
+		*this = Th.VertexOnBThEdge[i];  
+		v = ThNew.vertices + Th.GetId(v);
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnEdge::SetOnBTh{{{1*/
+	void VertexOnEdge::SetOnBTh(){
+		v->BackgroundEdgeHook=this;
+		v->IndexInTriangle=IsVertexOnEdge;  
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnEdge.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnEdge.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnEdge.h	(revision 11330)
@@ -0,0 +1,36 @@
+#ifndef _VERTEXONEDGE_H_
+#define _VERTEXONEDGE_H_
+
+#include "./include.h"
+#include "./Edge.h"
+
+namespace bamg {
+
+	//classes
+	class Mesh;
+	class BamgVertex;
+
+	class VertexOnEdge {
+
+		public:
+			BamgVertex* v;
+			Edge*   be;
+			double abcisse;
+
+			//Constructors
+			VertexOnEdge(BamgVertex * w, Edge *bw,double s) :v(w),be(bw),abcisse(s) {};
+			VertexOnEdge(){};
+
+			//Operators
+			operator double () const { return abcisse;}
+			operator BamgVertex* () const { return v;}  
+			operator Edge* () const { return be;}  
+			BamgVertex & operator[](int i) const { return (*be)[i];}
+
+			//Methods
+			void SetOnBTh();
+			void Set(const Mesh &,long,Mesh &);  
+	};
+
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnGeom.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnGeom.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnGeom.cpp	(revision 11330)
@@ -0,0 +1,70 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "VertexOnGeom.h"
+#include "Mesh.h"
+#include "Geometry.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION VertexOnGeom::VertexOnGeom(){{{1*/
+	VertexOnGeom::VertexOnGeom(){
+		meshvertex=NULL;
+		curvilincoord=0;
+		gv=0;
+	} 
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomVertex &g){{{1*/
+	VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomVertex &g){
+		meshvertex=&m;
+		curvilincoord=-1;
+		gv=&g;
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomEdge &g,double s){{{1*/
+	VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomEdge &g,double s){
+		meshvertex=&m;
+		curvilincoord=s;
+		ge=&g;
+	}
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION VertexOnGeom::Set {{{1*/
+	void VertexOnGeom::Set(const VertexOnGeom & rec,const Mesh & Th ,Mesh & ThNew){
+		*this = rec;  
+		meshvertex = ThNew.vertices + Th.GetId(meshvertex);
+		if (gv)
+		 if (curvilincoord < 0 )
+		  gv = ThNew.Gh.vertices + Th.Gh.GetId(gv);
+		 else
+		  ge = ThNew.Gh.edges + Th.Gh.GetId(ge);
+
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::OnGeomVertex{{{1*/
+	int VertexOnGeom::OnGeomVertex()const{
+		return this? curvilincoord <0 :0;
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::OnGeomEdge{{{1*/
+	int VertexOnGeom::OnGeomEdge() const{
+		return this? curvilincoord >=0 :0;
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::IsRequiredVertex{{{1*/
+	int VertexOnGeom::IsRequiredVertex() {
+		return this? ((curvilincoord<0 ? (gv?gv->Required():0):0 )) : 0;
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::SetOn{{{1*/
+	void VertexOnGeom::SetOn(){
+		meshvertex->GeomEdgeHook=this;
+		meshvertex->IndexInTriangle=IsVertexOnGeom;
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnGeom.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnGeom.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnGeom.h	(revision 11330)
@@ -0,0 +1,46 @@
+#ifndef _VERTEXONGEOM_H_
+#define _VERTEXONGEOM_H_
+
+#include "./include.h"
+#include "./GeomVertex.h"
+
+namespace bamg {
+
+	//classes
+	class Mesh;
+	class BamgVertex;
+	class GeomEdge;
+
+	class VertexOnGeom{
+
+		public:
+
+			BamgVertex* meshvertex;
+			double curvilincoord;  
+			union{ 
+				GeomVertex* gv; // if curvilincoord <0; 
+				GeomEdge*   ge; // if curvilincoord in [0..1]
+			};
+
+			//Constructors/Destructors
+			VertexOnGeom();
+			VertexOnGeom(BamgVertex & m,GeomVertex &g);
+			VertexOnGeom(BamgVertex & m,GeomEdge &g,double s);
+
+			//Operators
+			operator BamgVertex*() const  {return meshvertex;}
+			operator GeomVertex * () const  {return gv;}
+			operator GeomEdge * () const  {return ge;}
+			operator const double & () const {return curvilincoord;}
+
+			//Methods
+			int  OnGeomVertex()const;
+			int  OnGeomEdge() const;
+			int  IsRequiredVertex();
+			void SetOn();
+
+			//Inline methods
+			void Set(const VertexOnGeom&,const Mesh &,Mesh &);  
+	};
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnVertex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnVertex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnVertex.cpp	(revision 11330)
@@ -0,0 +1,34 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "VertexOnVertex.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION VertexOnVertex::VertexOnVertex(){{{1*/
+	VertexOnVertex::VertexOnVertex() {
+		v=NULL;
+		bv=NULL;
+	};/*}}}*/
+	/*FUNCTION VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw){{{1*/
+	VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw) :v(w),bv(bw){
+	
+	}/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION VertexOnVertex::Set{{{1*/
+	void VertexOnVertex::Set(const Mesh &Th ,long i,Mesh &ThNew) { 
+		*this = Th.VertexOnBThVertex[i];  
+		v     = ThNew.vertices + Th.GetId(v);
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnVertex::SetOnBTh{{{1*/
+	void VertexOnVertex::SetOnBTh(){
+		v->BackgroundVertexHook=bv;v->IndexInTriangle=IsVertexOnVertex;
+	}/*}}}*/
+
+} 
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnVertex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnVertex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/VertexOnVertex.h	(revision 11330)
@@ -0,0 +1,28 @@
+#ifndef _VERTEXONVERTEX_H_
+#define _VERTEXONVERTEX_H_
+
+#include "./include.h"
+#include "./BamgVertex.h"
+
+namespace bamg {
+
+	//classes
+	class Mesh;
+
+	class VertexOnVertex {
+
+		public:
+			BamgVertex* v;
+			BamgVertex* bv;
+
+			//Constructors
+			VertexOnVertex();
+			VertexOnVertex(BamgVertex * w,BamgVertex *bw);
+
+			//Methods
+			void SetOnBTh();
+			void Set(const Mesh &,long,Mesh &);
+	};
+
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/include.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/include.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/include.h	(revision 11330)
@@ -0,0 +1,12 @@
+/*!\file: include.h
+ * \brief prototypes for include.h
+ */ 
+
+#ifndef _INCLUDE2_H_
+#define  _INCLUDE2_H_
+
+#include "../../include/macros.h"
+#include "./macros.h"
+#include "./typedefs.h"
+
+#endif //ifndef _INCLUDE2_H_
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/macros.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/macros.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/macros.h	(revision 11330)
@@ -0,0 +1,29 @@
+#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};
+	#if LONG_BIT > 63
+	const  Icoor1 MaxICoor   = 1073741823; // 2^30-1 =111...111 (29 times)
+	#else
+	const  Icoor1 MaxICoor   = 8388608;    // 2^23
+	#endif
+	const  Icoor2 MaxICoor22 = Icoor2(2)*Icoor2(MaxICoor) * Icoor2(MaxICoor) ;
+}
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Bamg/typedefs.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Bamg/typedefs.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Bamg/typedefs.h	(revision 11330)
@@ -0,0 +1,21 @@
+#ifndef _BAMGTYPEDEFS_H
+#define _BAMGTYPEDEFS_H
+
+#include "./R2.h"
+
+namespace bamg {
+
+	/*Integer coordinates types*/
+	typedef int  Icoor1; 
+	#if LONG_BIT > 63 //64 bits or more
+	typedef long Icoor2;
+	#else //32 bits
+	typedef double Icoor2;
+	#endif
+
+	/*I2 and R2*/
+	typedef P2<Icoor1,Icoor2>  I2;
+	typedef P2<double,double>  R2;
+}
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Constraints/Constraint.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Constraints/Constraint.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Constraints/Constraint.h	(revision 11330)
@@ -0,0 +1,30 @@
+/*!\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:*/
+/*{{{1*/
+#include "../Object.h"
+
+class Nodes;
+
+#include "../../toolkits/toolkits.h"
+/*}}}*/
+
+class Constraint: public Object{
+
+	public: 
+		
+		virtual      ~Constraint(){};
+		virtual void ConstrainNode(Nodes* nodes,Parameters* parameters)=0;
+		virtual bool InAnalysis(int analysis_type)=0;
+
+
+};
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcDynamic.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcDynamic.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcDynamic.cpp	(revision 11330)
@@ -0,0 +1,205 @@
+/*!\file SpcDynamic.c
+ * \brief: implementation of the SpcDynamic object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../Container/Container.h"
+#include "../objects.h"
+
+/*SpcDynamic constructors and destructor*/
+/*FUNCTION SpcDynamic::SpcDynamic(){{{1*/
+SpcDynamic::SpcDynamic(){
+	return;
+}
+/*}}}1*/
+/*FUNCTION SpcDynamic::SpcDynamic(int spc_sid,int spc_nodeid,...){{{1*/
+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;
+}
+/*}}}1*/
+/*FUNCTION SpcDynamic::~SpcDynamic{{{1*/
+SpcDynamic::~SpcDynamic(){
+	return;
+}
+/*}}}1*/
+		
+/*Object virtual functions definitions:*/
+/*FUNCTION SpcDynamic::Echo {{{1*/
+void SpcDynamic::Echo(void){
+
+	printf("SpcDynamic:\n");
+	printf("   sid: %i\n",sid);
+	printf("   nodeid: %i\n",nodeid);
+	printf("   dof: %i\n",dof);
+	printf("   value: %g\n",value);
+	printf("   isset: %s\n",isset?"true":"false");
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	return;
+}
+/*}}}1*/
+/*FUNCTION SpcDynamic::DeepEcho {{{1*/
+void SpcDynamic::DeepEcho(void){
+
+	this->Echo();
+	return;
+}		
+/*}}}1*/
+/*FUNCTION SpcDynamic::Id {{{1*/
+int    SpcDynamic::Id(void){ return sid; }
+/*}}}1*/
+/*FUNCTION SpcDynamic::MyRank {{{1*/
+int    SpcDynamic::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}1*/
+#ifdef _SERIAL_
+/*FUNCTION SpcDynamic::Marshall {{{1*/
+void  SpcDynamic::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of SpcDynamic: */
+	enum_type=SpcDynamicEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*marshall SpcDynamic data: */
+	memcpy(marshalled_dataset,&sid,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(marshalled_dataset,&nodeid,sizeof(nodeid));marshalled_dataset+=sizeof(nodeid);
+	memcpy(marshalled_dataset,&dof,sizeof(dof));marshalled_dataset+=sizeof(dof);
+	memcpy(marshalled_dataset,&value,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(marshalled_dataset,&isset,sizeof(isset));marshalled_dataset+=sizeof(isset);
+	memcpy(marshalled_dataset,&analysis_type,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}1*/
+/*FUNCTION SpcDynamic::MarshallSize {{{1*/
+int   SpcDynamic::MarshallSize(){
+
+	return sizeof(sid)
+		+sizeof(nodeid)
+		+sizeof(dof)
+		+sizeof(value)
+		+sizeof(isset)
+		+sizeof(analysis_type)
+		+sizeof(int); //sizeof(int) for enum type
+}
+/*}}}1*/
+/*FUNCTION SpcDynamic::Demarshall {{{1*/
+void  SpcDynamic::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+
+	memcpy(&sid,marshalled_dataset,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(&nodeid,marshalled_dataset,sizeof(nodeid));marshalled_dataset+=sizeof(nodeid);
+	memcpy(&dof,marshalled_dataset,sizeof(dof));marshalled_dataset+=sizeof(dof);
+	memcpy(&value,marshalled_dataset,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(&isset,marshalled_dataset,sizeof(isset));marshalled_dataset+=sizeof(isset);
+	memcpy(&analysis_type,marshalled_dataset,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}1*/
+#endif
+/*FUNCTION SpcDynamic::ObjectEnum{{{1*/
+int SpcDynamic::ObjectEnum(void){
+
+	return SpcDynamicEnum;
+
+}
+/*}}}1*/
+/*FUNCTION SpcDynamic::copy {{{1*/
+Object* SpcDynamic::copy() {
+	return new SpcDynamic(*this); 
+}
+/*}}}1*/
+
+/*Constraint virtual functions definitions: */
+/*FUNCTION SpcDynamic::InAnalysis{{{1*/
+bool SpcDynamic::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+/*FUNCTION SpcDynamic::ConstrainNode{{{1*/
+void SpcDynamic::ConstrainNode(Nodes* nodes,Parameters* parameters){
+
+	Node* node=NULL;
+
+	/*Chase through nodes and find the node to which this SpcDynamic applys: */
+	node=(Node*)nodes->GetObjectById(NULL,nodeid);
+
+	/*Apply constraint: */
+	if(node){ //in case the spc is dealing with a node on another cpu
+
+		/*We should first check that the value has been set... (test306)*/
+		node->ApplyConstraint(dof,value);
+	}
+}
+/*}}}*/
+
+/*SpcDynamic functions*/
+/*FUNCTION SpcDynamic::GetDof {{{1*/
+int SpcDynamic::GetDof(){
+	return dof;
+}
+/*}}}1*/
+/*FUNCTION SpcDynamic::GetNodeId {{{1*/
+int   SpcDynamic::GetNodeId(){
+	
+	return nodeid;
+}
+/*}}}1*/
+/*FUNCTION SpcDynamic::GetValue {{{1*/
+double SpcDynamic::GetValue(){
+	_assert_(this->isset);
+	_assert_(!isnan(value));
+	return value;
+}
+/*}}}1*/
+/*FUNCTION SpcDynamic::SetDynamicConstraint {{{1*/
+void SpcDynamic::SetDynamicConstraint(Nodes* nodes,double* yg_serial){
+
+	int pos;
+
+	Node* node=(Node*)nodes->GetObjectById(NULL,nodeid);
+	pos=node->GetDof(dof-1,GsetEnum);
+
+	this->value=yg_serial[pos];
+	this->isset=true;
+}
+/*}}}1*/
Index: /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcDynamic.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcDynamic.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcDynamic.h	(revision 11330)
@@ -0,0 +1,57 @@
+/*!\file SpcDynamic.h
+ * \brief: header file for spc object
+ */
+
+#ifndef _SPCDynamic_H_
+#define _SPCDynamic_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../Object.h"
+class DataSet;
+/*}}}*/
+
+class SpcDynamic: public Constraint{
+
+	private: 
+		int	sid; /*! id, to track it*/
+		int	nodeid; /*!node id*/
+		int dof; /*!component*/
+		double value; /*value*/
+		bool isset;
+		int analysis_type;
+
+	public:
+
+		/*SpcDynamic constructors, destructors:{{{1*/
+		SpcDynamic();
+		SpcDynamic(int sid,int nodeid, int dof,int analysis_type);
+		~SpcDynamic();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Constraint virtual functions definitions: {{{1*/
+		void   ConstrainNode(Nodes* nodes,Parameters* parameters);
+		bool   InAnalysis(int analysis_type);
+		/*}}}*/
+		/*SpcDynamic management:{{{1 */
+		int    GetNodeId();
+		int    GetDof();
+		double GetValue();
+		void   SetDynamicConstraint(Nodes* nodes,double *yg_serial);
+		/*}}}*/
+
+};
+
+#endif  /* _SPCStatic_H_*/
Index: /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcStatic.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcStatic.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcStatic.cpp	(revision 11330)
@@ -0,0 +1,190 @@
+/*!\file SpcStatic.c
+ * \brief: implementation of the SpcStatic object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../Container/Container.h"
+#include "../objects.h"
+
+/*SpcStatic constructors and destructor*/
+/*FUNCTION SpcStatic::SpcStatic(){{{1*/
+SpcStatic::SpcStatic(){
+	return;
+}
+/*}}}1*/
+/*FUNCTION SpcStatic::SpcStatic(int spc_sid,int spc_nodeid,...){{{1*/
+SpcStatic::SpcStatic(int spc_sid,int spc_nodeid, int spc_dof,double spc_value,int spc_analysis_type){
+
+	sid=spc_sid;
+	nodeid=spc_nodeid;
+	dof=spc_dof;
+	value=spc_value;
+	analysis_type=spc_analysis_type;
+
+	return;
+}
+/*}}}1*/
+/*FUNCTION SpcStatic::~SpcStatic{{{1*/
+SpcStatic::~SpcStatic(){
+	return;
+}
+/*}}}1*/
+		
+/*Object virtual functions definitions:*/
+/*FUNCTION SpcStatic::Echo {{{1*/
+void SpcStatic::Echo(void){
+
+	printf("SpcStatic:\n");
+	printf("   sid: %i\n",sid);
+	printf("   nodeid: %i\n",nodeid);
+	printf("   dof: %i\n",dof);
+	printf("   value: %g\n",value);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	return;
+}
+/*}}}1*/
+/*FUNCTION SpcStatic::DeepEcho {{{1*/
+void SpcStatic::DeepEcho(void){
+
+	printf("SpcStatic:\n");
+	printf("   sid: %i\n",sid);
+	printf("   nodeid: %i\n",nodeid);
+	printf("   dof: %i\n",dof);
+	printf("   value: %g\n",value);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	return;
+}		
+/*}}}1*/
+/*FUNCTION SpcStatic::Id {{{1*/
+int    SpcStatic::Id(void){ return sid; }
+/*}}}1*/
+/*FUNCTION SpcStatic::MyRank {{{1*/
+int    SpcStatic::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}1*/
+#ifdef _SERIAL_
+/*FUNCTION SpcStatic::Marshall {{{1*/
+void  SpcStatic::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of SpcStatic: */
+	enum_type=SpcStaticEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*marshall SpcStatic data: */
+	memcpy(marshalled_dataset,&sid,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(marshalled_dataset,&nodeid,sizeof(nodeid));marshalled_dataset+=sizeof(nodeid);
+	memcpy(marshalled_dataset,&dof,sizeof(dof));marshalled_dataset+=sizeof(dof);
+	memcpy(marshalled_dataset,&value,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(marshalled_dataset,&analysis_type,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}1*/
+/*FUNCTION SpcStatic::MarshallSize {{{1*/
+int   SpcStatic::MarshallSize(){
+
+	return sizeof(sid)
+		+sizeof(nodeid)
+		+sizeof(dof)
+		+sizeof(value)
+		+sizeof(analysis_type)
+		+sizeof(int); //sizeof(int) for enum type
+}
+/*}}}1*/
+/*FUNCTION SpcStatic::Demarshall {{{1*/
+void  SpcStatic::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+
+	memcpy(&sid,marshalled_dataset,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(&nodeid,marshalled_dataset,sizeof(nodeid));marshalled_dataset+=sizeof(nodeid);
+	memcpy(&dof,marshalled_dataset,sizeof(dof));marshalled_dataset+=sizeof(dof);
+	memcpy(&value,marshalled_dataset,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(&analysis_type,marshalled_dataset,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}1*/
+#endif
+/*FUNCTION SpcStatic::ObjectEnum{{{1*/
+int SpcStatic::ObjectEnum(void){
+
+	return SpcStaticEnum;
+
+}
+/*}}}1*/
+/*FUNCTION SpcStatic::copy {{{1*/
+Object* SpcStatic::copy() {
+	return new SpcStatic(*this); 
+}
+/*}}}1*/
+
+/*Constraint virtual functions definitions: */
+/*FUNCTION SpcStatic::InAnalysis{{{1*/
+bool SpcStatic::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+/*FUNCTION SpcStatic::ConstrainNode{{{1*/
+void SpcStatic::ConstrainNode(Nodes* nodes,Parameters* parameters){
+
+	Node* node=NULL;
+
+	/*Chase through nodes and find the node to which this SpcStatic applys: */
+	node=(Node*)nodes->GetObjectById(NULL,nodeid);
+
+	/*Apply constraint: */
+	if(node){ //in case the spc is dealing with a node on another cpu
+		node->ApplyConstraint(dof,value);
+	}
+}
+/*}}}*/
+
+/*SpcStatic functions*/
+/*FUNCTION SpcStatic::GetDof {{{1*/
+int SpcStatic::GetDof(){
+	return dof;
+}
+/*}}}1*/
+/*FUNCTION SpcStatic::GetNodeId {{{1*/
+int   SpcStatic::GetNodeId(){
+	
+	return nodeid;
+}
+/*}}}1*/
+/*FUNCTION SpcStatic::GetValue {{{1*/
+double SpcStatic::GetValue(){
+	_assert_(!isnan(value));
+	return value;
+}
+/*}}}1*/
Index: /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcStatic.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcStatic.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcStatic.h	(revision 11330)
@@ -0,0 +1,55 @@
+/*!\file SpcStatic.h
+ * \brief: header file for spc object
+ */
+
+#ifndef _SPCStatic_H_
+#define _SPCStatic_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../Object.h"
+class DataSet;
+/*}}}*/
+
+class SpcStatic: public Constraint{
+
+	private: 
+		int	sid; /*! id, to track it*/
+		int	nodeid; /*!node id*/
+		int dof; /*!component*/
+		double value; /*value*/
+		int analysis_type;
+
+	public:
+
+		/*SpcStatic constructors, destructors:{{{1*/
+		SpcStatic();
+		SpcStatic(int sid,int nodeid, int dof,double value,int analysis_type);
+		~SpcStatic();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Constraint virtual functions definitions: {{{1*/
+		void   ConstrainNode(Nodes* nodes,Parameters* parameters);
+		bool   InAnalysis(int analysis_type);
+		/*}}}*/
+		/*SpcStatic management:{{{1 */
+		int    GetNodeId();
+		int    GetDof();
+		double GetValue();
+		/*}}}*/
+
+};
+
+#endif  /* _SPCStatic_H_*/
Index: /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcTransient.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcTransient.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcTransient.cpp	(revision 11330)
@@ -0,0 +1,248 @@
+/*!\file SpcTransient.c
+ * \brief: implementation of the SpcTransient object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../Container/Container.h"
+#include "../objects.h"
+
+/*SpcTransient constructors and destructor*/
+/*FUNCTION SpcTransient::SpcTransient(){{{1*/
+SpcTransient::SpcTransient(){
+	sid=-1;
+	nodeid=-1;
+	dof=-1;
+	values=NULL;
+	times=NULL;
+	nsteps=-1;
+	analysis_type=-1;
+	return;
+}
+/*}}}1*/
+/*FUNCTION SpcTransient::SpcTransient(int spc_sid,int spc_nodeid,...){{{1*/
+SpcTransient::SpcTransient(int spc_sid,int spc_nodeid, int spc_dof,int spc_nsteps, double* spc_times, double* spc_values,int spc_analysis_type){
+
+	sid=spc_sid;
+	nodeid=spc_nodeid;
+	dof=spc_dof;
+	nsteps=spc_nsteps;
+	if(spc_nsteps){
+		values=(double*)xmalloc(spc_nsteps*sizeof(double));
+		times=(double*)xmalloc(spc_nsteps*sizeof(double));
+		memcpy(values,spc_values,nsteps*sizeof(double));
+		memcpy(times,spc_times,nsteps*sizeof(double));
+	}
+	analysis_type=spc_analysis_type;
+	return;
+}
+/*}}}1*/
+/*FUNCTION SpcTransient::~SpcTransient{{{1*/
+SpcTransient::~SpcTransient(){
+	xfree((void**)&times);
+	xfree((void**)&values);
+	return;
+}
+/*}}}1*/
+		
+/*Object virtual functions definitions:*/
+/*FUNCTION SpcTransient::Echo {{{1*/
+void SpcTransient::Echo(void){
+
+	int i;
+	printf("SpcTransient:\n");
+	printf("   sid: %i\n",sid);
+	printf("   nodeid: %i\n",nodeid);
+	printf("   dof: %i\n",dof);
+	printf("   nsteps: %i\n",nsteps);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	printf("   steps|times|values\n");
+	for(i=0;i<nsteps;i++){
+		printf("%i-%g:%g\n",i,times[i],values[i]);
+	}
+	return;
+}
+/*}}}1*/
+/*FUNCTION SpcTransient::DeepEcho {{{1*/
+void SpcTransient::DeepEcho(void){
+	this->Echo();
+}		
+/*}}}1*/
+/*FUNCTION SpcTransient::Id {{{1*/
+int    SpcTransient::Id(void){ return sid; }
+/*}}}1*/
+/*FUNCTION SpcTransient::MyRank {{{1*/
+int    SpcTransient::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}1*/
+#ifdef _SERIAL_
+/*FUNCTION SpcTransient::Marshall {{{1*/
+void  SpcTransient::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of SpcTransient: */
+	enum_type=SpcTransientEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*marshall SpcTransient data: */
+	memcpy(marshalled_dataset,&sid,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(marshalled_dataset,&nodeid,sizeof(nodeid));marshalled_dataset+=sizeof(nodeid);
+	memcpy(marshalled_dataset,&dof,sizeof(dof));marshalled_dataset+=sizeof(dof);
+	memcpy(marshalled_dataset,&nsteps,sizeof(nsteps));marshalled_dataset+=sizeof(nsteps);
+	memcpy(marshalled_dataset,&analysis_type,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+	if(nsteps){
+		memcpy(marshalled_dataset,values,nsteps*sizeof(double));marshalled_dataset+=nsteps*sizeof(double);
+		memcpy(marshalled_dataset,times,nsteps*sizeof(double));marshalled_dataset+=nsteps*sizeof(double);
+	}
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}1*/
+/*FUNCTION SpcTransient::MarshallSize {{{1*/
+int   SpcTransient::MarshallSize(){
+
+	return sizeof(sid)
+		+sizeof(nodeid)
+		+sizeof(dof)
+		+sizeof(nsteps)
+		+nsteps*2*sizeof(double)
+		+sizeof(analysis_type)
+		+sizeof(int); //sizeof(int) for enum type
+}
+/*}}}1*/
+/*FUNCTION SpcTransient::Demarshall {{{1*/
+void  SpcTransient::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+
+	memcpy(&sid,marshalled_dataset,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(&nodeid,marshalled_dataset,sizeof(nodeid));marshalled_dataset+=sizeof(nodeid);
+	memcpy(&dof,marshalled_dataset,sizeof(dof));marshalled_dataset+=sizeof(dof);
+	memcpy(&nsteps,marshalled_dataset,sizeof(nsteps));marshalled_dataset+=sizeof(nsteps);
+	memcpy(&analysis_type,marshalled_dataset,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+	if(nsteps){
+		values=(double*)xmalloc(nsteps*sizeof(double));
+		times=(double*)xmalloc(nsteps*sizeof(double));
+		memcpy(values,marshalled_dataset,nsteps*sizeof(double));marshalled_dataset+=nsteps*sizeof(double);
+		memcpy(times,marshalled_dataset,nsteps*sizeof(double));marshalled_dataset+=nsteps*sizeof(double);
+	}
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}1*/
+#endif
+/*FUNCTION SpcTransient::ObjectEnum{{{1*/
+int SpcTransient::ObjectEnum(void){
+
+	return SpcTransientEnum;
+
+}
+/*}}}1*/
+/*FUNCTION SpcTransient::copy {{{1*/
+Object* SpcTransient::copy() {
+	return new SpcTransient(sid,nodeid,dof,nsteps,times,values,analysis_type);
+}
+/*}}}1*/
+
+/*Constraint virtual functions definitions:*/
+/*FUNCTION SpcTransient::InAnalysis{{{1*/
+bool SpcTransient::InAnalysis(int in_analysis_type){
+	
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+/*FUNCTION SpcTransient::ConstrainNode{{{1*/
+void SpcTransient::ConstrainNode(Nodes* nodes,Parameters* parameters){
+
+	Node* node=NULL;
+	double time=0;
+	int    i;
+	double alpha=-1;
+	double 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(isnan(value)){
+			node->RelaxConstraint(dof);
+		}
+		else node->ApplyConstraint(dof,value);
+	}
+}
+/*}}}*/
+
+/*SpcTransient functions*/
+/*FUNCTION SpcTransient::GetDof {{{1*/
+int SpcTransient::GetDof(){
+	return dof;
+}
+/*}}}1*/
+/*FUNCTION SpcTransient::GetNodeId {{{1*/
+int   SpcTransient::GetNodeId(){
+	
+	return nodeid;
+}
+/*}}}1*/
+/*FUNCTION SpcTransient::GetValue {{{1*/
+double SpcTransient::GetValue(){
+	return values[0];
+}
+/*}}}1*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcTransient.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcTransient.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Constraints/SpcTransient.h	(revision 11330)
@@ -0,0 +1,57 @@
+/*!\file SpcTransient.h
+ * \brief: header file for spc object
+ */
+
+#ifndef _SPCTRANSIENT_H_
+#define _SPCTRANSIENT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../Object.h"
+class DataSet;
+/*}}}*/
+
+class SpcTransient: public Constraint{
+
+	private: 
+		int	sid; /*! id, to track it*/
+		int	nodeid; /*!node id*/
+		int dof; /*!component*/
+		double* values; /*different values in time*/
+		double* times; /*different time steps*/
+		int nsteps; /*number of time steps*/
+		int analysis_type;
+
+	public:
+
+		/*SpcTransient constructors, destructors:{{{1*/
+		SpcTransient();
+		SpcTransient(int sid,int nodeid, int dof,int nsteps, double* times, double* values,int analysis_type);
+		~SpcTransient();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Constraint virtual functions definitions: {{{1*/
+		void   ConstrainNode(Nodes* nodes,Parameters* parameters);
+		bool   InAnalysis(int analysis_type);
+		/*}}}*/
+		/*SpcTransient management:{{{1 */
+		int    GetNodeId();
+		int    GetDof();
+		double GetValue();
+		/*}}}*/
+
+};
+
+#endif  /* _SPCTRANSIENT_H_ */
Index: /issm/trunk-jpl-damage/src/c/objects/Contour.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Contour.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Contour.cpp	(revision 11330)
@@ -0,0 +1,24 @@
+/*! \file Contour.c
+ *  \sa Contour.h
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./objects.h"
+#include "../include/include.h"
+#include "../io/io.h"
+
+void ContourEcho(Contour* contour){
+
+	int i;
+
+	_printf_(true,"Number of nodes in contour: %i\n",contour->nods);
+	_printf_(true,"Node coordinates: \n");
+	for (i=0;i<contour->nods;i++){
+		_printf_(true,"%lf %lf\n",*(contour->x+i),*(contour->y+i));
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/objects/Contour.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Contour.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Contour.h	(revision 11330)
@@ -0,0 +1,19 @@
+/*! \file Contour.h
+ *  \brief structure object to hold contour profiles from an 
+ *  Argus domain outline file, or from any cad system.
+ */
+
+#ifndef _CONTOUR_H_
+#define _CONTOUR_H_
+
+/*!Contour declaration: */
+struct Contour {
+	int	nods;
+	double* x;
+	double* y;
+};
+
+/*!Methods: */
+void ContourEcho(Contour* contour);
+
+#endif  /* CONTOUR_H_ */
Index: /issm/trunk-jpl-damage/src/c/objects/DakotaPlugin.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/DakotaPlugin.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/DakotaPlugin.cpp	(revision 11330)
@@ -0,0 +1,118 @@
+/*!\file:  DakotaPlugin.cpp (see DakotaPlugin.h for explanations)
+ * \brief  header file for derived DirectApplicInterface class. 
+ * \sa SpwanCore.cpp and \sa qmu.cpp
+ *
+ * This class needs to be understood simultaneously with qmu.cpp and SpwanCore.cpp. 
+ * This call is derived from the Dakota DirectApplicInterface class. This is the 
+ * only way to plug ISSM's own routines into the Dakota engine. The derived class 
+ * has one function called derived_map_ac, which is called by Dakota to drive the 
+ * entire snesitivity analysis. 
+ *
+ * We use this routine (which gets variables, variable_descriptors from the Dakota 
+ * engine, and requests responses from the ISSM solution sequences), to call our 
+ * own solutoin cores. This routines calls the SpawnCore routine, which will drive 
+ * the entire computations. 
+ */ 
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*Standard ISSM includes: */
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "../objects/objects.h"
+#include "../modules/Dakotax/Dakotax.h"
+
+/*Standard includes: */
+#include <string>
+
+#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+
+//Dakota headers
+#include "DakotaResponse.H"
+#include "ParamResponsePair.H"
+#include "DakotaPlugin.h"
+#include "system_defs.h"
+#include "ProblemDescDB.H"
+#include "ParallelLibrary.H"
+
+namespace SIM {
+
+//constructor
+DakotaPlugin::DakotaPlugin(const Dakota::ProblemDescDB& problem_db,void* in_femmodel):Dakota::DirectApplicInterface(problem_db){
+
+
+	femmodel=in_femmodel;
+	counter=0;
+}
+
+//destructor
+DakotaPlugin::~DakotaPlugin(){ /* Virtual destructor handles referenceCount at Interface level. */ }
+
+int DakotaPlugin::derived_map_ac(const Dakota::String& driver) {
+
+	int i;
+	double* variables=NULL;
+	char** variable_descriptors=NULL;
+	char*  variable_descriptor=NULL;
+	double* responses=NULL;
+
+	/*increae counter: */
+	counter++;
+
+	/*Before launching analysis, we need to transfer the dakota inputs into Issm 
+	 *readable variables: */
+
+	/*First, the variables: */
+	variables=(double*)xmalloc(numACV*sizeof(double));
+	for(i=0;i<numACV;i++){
+		variables[i]=xC[i];
+	}
+	/*The descriptors: */
+	variable_descriptors=(char**)xmalloc(numACV*sizeof(char*));
+	for(i=0;i<numACV;i++){
+		string label=xCLabels[i];
+		variable_descriptor=(char*)xmalloc((strlen(label.c_str())+1)*sizeof(char));
+		memcpy(variable_descriptor,label.c_str(),(strlen(label.c_str())+1)*sizeof(char));
+
+		
+		variable_descriptors[i]=variable_descriptor;
+	}
+
+	/*Initialize responses: */
+	responses=(double*)xcalloc(numFns,sizeof(double));
+
+	/*run core solution: */
+	SpawnCore(responses,numFns, variables,variable_descriptors,numACV,femmodel,counter);
+
+	/*populate responses: */
+	for(i=0;i<numFns;i++){
+		fnVals[i]=responses[i];
+	}
+
+
+	/*Free ressources:*/
+	xfree((void**)&variables);
+	for(i=0;i<numACV;i++){
+		variable_descriptor=variable_descriptors[i];
+		xfree((void**)&variable_descriptor);
+	}
+	xfree((void**)&variable_descriptors);
+	xfree((void**)&responses);
+
+	return 0;
+}
+  
+
+int DakotaPlugin::GetCounter(){
+	return counter;
+}
+
+} // namespace SIM
+
+
+#endif //only works if dakota library has been compiled in.
Index: /issm/trunk-jpl-damage/src/c/objects/DakotaPlugin.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/DakotaPlugin.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/DakotaPlugin.h	(revision 11330)
@@ -0,0 +1,55 @@
+/*!\file:  DakotaPlugin.h:
+ */ 
+
+#ifndef _DAKOTAPLUGIN_H
+#define _DAKOTAPLUGIN_H
+
+
+#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+
+/*Headers:*/
+/*{{{1*/
+
+
+#include "DirectApplicInterface.H"
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+
+/*}}}*/
+
+namespace SIM {
+
+class DakotaPlugin: public Dakota::DirectApplicInterface
+{
+public:
+
+	DakotaPlugin(const Dakota::ProblemDescDB& problem_db,void* model);
+	~DakotaPlugin();
+
+	/*these fields are used by core solutions: */
+	void* femmodel;
+
+	int counter;
+
+protected:
+
+  // execute the input filter portion of a direct evaluation invocation
+  //int derived_map_if(const Dakota::String& if_name);
+  /// execute an analysis code portion of a direct evaluation invocation
+  int derived_map_ac(const Dakota::String& ac_name);
+  // execute the output filter portion of a direct evaluation invocation
+  //int derived_map_of(const Dakota::String& of_name);
+
+  /*add for issm: */
+  int GetCounter();
+
+private:
+
+};
+
+} // namespace SIM
+
+#endif //only works if dakota library has been compiled in.
+
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/DofIndexing.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/DofIndexing.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/DofIndexing.cpp	(revision 11330)
@@ -0,0 +1,335 @@
+/*!\file DofIndexing.c
+ * \brief: implementation of the DofIndexing object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include "./objects.h"
+#include <string.h>
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../shared/shared.h"
+#include "../Container/Container.h"
+#include "../include/include.h"
+
+/*DofIndexing constructors and destructor*/
+/*FUNCTION DofIndexing::DofIndexing(){{{1*/
+DofIndexing::DofIndexing(){
+
+	this->gsize=UNDEF;
+	this->fsize=UNDEF;
+	this->ssize=UNDEF;
+	this->clone=0;
+	this->f_set=NULL;
+	this->s_set=NULL;
+	this->svalues=NULL;
+	this->doftype=NULL;
+	this->gdoflist=NULL;
+	this->fdoflist=NULL;
+	this->sdoflist=NULL;
+
+}
+/*}}}*/
+/*FUNCTION DofIndexing::DofIndexing(int gsize){{{1*/
+DofIndexing::DofIndexing(int in_gsize){
+	this->Init(in_gsize,NULL);
+}
+/*}}}*/
+/*FUNCTION DofIndexing::DofIndexing(DofIndexing* in)  -> copy{{{1*/
+DofIndexing::DofIndexing(DofIndexing* in){ //copy constructor
+
+	int i;
+	this->gsize=in->gsize;
+	this->fsize=in->fsize;
+	this->ssize=in->ssize;
+	
+	this->clone=in->clone;
+
+	if(this->gsize>0){
+		this->f_set=(bool*)xmalloc(this->gsize*sizeof(bool));
+		this->s_set=(bool*)xmalloc(this->gsize*sizeof(bool));
+		this->svalues=(double*)xmalloc(this->gsize*sizeof(int));
+		if(in->doftype)this->doftype=(int*)xmalloc(this->gsize*sizeof(int)); 
+		this->gdoflist=(int*)xmalloc(this->gsize*sizeof(int)); 
+	}
+	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=(int*)xmalloc(this->fsize*sizeof(int)); else this->fdoflist=NULL;
+	if(this->ssize>0 && this->ssize!=UNDEF)this->sdoflist=(int*)xmalloc(this->ssize*sizeof(int)); 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));
+		memcpy(this->svalues,in->svalues,this->gsize*sizeof(double));
+		if(this->doftype)memcpy(this->doftype,in->doftype,this->gsize*sizeof(int));
+		memcpy(this->gdoflist,in->gdoflist,this->gsize*sizeof(int));
+	}
+	if(this->fsize>0 && this->fsize!=UNDEF)memcpy(this->fdoflist,in->fdoflist,this->fsize*sizeof(int));
+	if(this->ssize>0 && this->ssize!=UNDEF)memcpy(this->sdoflist,in->sdoflist,this->ssize*sizeof(int));
+
+}
+/*}}}*/
+/*FUNCTION DofIndexing::~DofIndexing() {{{1*/
+DofIndexing::~DofIndexing(){ //destructor
+
+	xfree((void**)&f_set); 
+	xfree((void**)&s_set); 
+	xfree((void**)&svalues);
+	xfree((void**)&doftype); 
+	xfree((void**)&gdoflist);
+	xfree((void**)&fdoflist);
+	xfree((void**)&sdoflist);
+
+}
+/*}}}*/
+/*FUNCTION DofIndexing::Init{{{1*/
+void DofIndexing::Init(int in_gsize,int* in_doftype){
+
+	int i;
+	this->gsize=in_gsize;
+	
+	this->clone=0;
+
+	/*allocate: */
+	if(this->gsize>0){
+		this->f_set=(bool*)xmalloc(this->gsize*sizeof(bool));
+		this->s_set=(bool*)xmalloc(this->gsize*sizeof(bool));
+		this->svalues=(double*)xmalloc(this->gsize*sizeof(double));
+		if(in_doftype)this->doftype=(int*)xmalloc(this->gsize*sizeof(int));
+		this->gdoflist=(int*)xmalloc(this->gsize*sizeof(int));
+	}
+
+	for (i=0;i<this->gsize;i++){
+		/*assume dof is free, no constraints, no rigid body constraint: */
+		this->f_set[i]=true;
+		this->s_set[i]=false;
+		if(this->doftype)this->doftype[i]=in_doftype[i];
+		this->svalues[i]=0; //0 constraint is the default value
+		this->gdoflist[i]=UNDEF;
+	}
+}
+/*}}}*/
+/*FUNCTION DofIndexing::InitSet{{{1*/
+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;
+		xfree((void**)&this->fdoflist);
+		if(this->fsize)this->fdoflist=(int*)xmalloc(size*sizeof(int));
+		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;
+		xfree((void**)&this->sdoflist);
+		if(this->ssize)this->sdoflist=(int*)xmalloc(size*sizeof(int));
+		else this->sdoflist=NULL;
+	}
+	else _error_("%s%s%s"," set of enum type ",EnumToStringx(setenum)," not supported yet!");
+}
+/*}}}*/
+
+/*Some of the Object functionality: */
+/*FUNCTION DofIndexing::Echo{{{1*/
+void DofIndexing::Echo(void){
+
+	int i;
+
+	printf("DofIndexing:\n");
+	printf("   gsize: %i\n",gsize);
+	printf("   clone: %i\n",clone);
+}
+/*}}}*/
+/*FUNCTION DofIndexing::DeepEcho{{{1*/
+void DofIndexing::DeepEcho(void){
+
+	int i;
+
+	printf("DofIndexing:\n");
+	printf("   gsize: %i\n",gsize);
+	printf("   fsize: %i\n",fsize);
+	printf("   ssize: %i\n",ssize);
+	printf("   clone: %i\n",clone);
+	
+	printf("   set membership: f,s sets \n");
+	for(i=0;i<gsize;i++){
+		printf("      dof %i: %s %s\n",i,f_set[i]?"true":"false",s_set[i]?"true":"false");
+	}
+
+	printf("   svalues (%i): |",this->ssize);
+	for(i=0;i<this->gsize;i++){
+		if(this->s_set[i])printf(" %g |",svalues[i]);
+	}
+	printf("\n");
+
+	if(doftype){
+		printf("   doftype: |");
+		for(i=0;i<gsize;i++){
+			printf(" %i |",doftype[i]);
+		}
+		printf("\n");
+	}
+	else printf("   doftype: NULL\n");
+
+	printf("   g_doflist (%i): |",this->gsize);
+	for(i=0;i<this->gsize;i++){
+		printf(" %i |",gdoflist[i]);
+	}
+	printf("\n");
+
+	printf("   f_doflist (%i): |",this->fsize);
+	for(i=0;i<this->fsize;i++){
+		printf(" %i |",fdoflist[i]);
+	}
+	printf("\n");
+
+	printf("   s_doflist (%i): |",this->ssize);
+	for(i=0;i<this->ssize;i++){
+		printf(" %i |",sdoflist[i]);
+	}
+	printf("\n");
+}		
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION DofIndexing::Marshall{{{1*/
+void  DofIndexing::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+	bool  flagdoftype; //to indicate if there are some doftype or if NULL
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*preliminary: */
+	if(this->doftype)flagdoftype=true;
+	else             flagdoftype=false;
+
+	/*get enum type of DofIndexing: */
+	enum_type=DofIndexingEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*marshall DofIndexing data: */
+	memcpy(marshalled_dataset,&gsize,sizeof(gsize));marshalled_dataset+=sizeof(gsize);
+	memcpy(marshalled_dataset,&fsize,sizeof(fsize));marshalled_dataset+=sizeof(fsize);
+	memcpy(marshalled_dataset,&ssize,sizeof(ssize));marshalled_dataset+=sizeof(ssize);
+	memcpy(marshalled_dataset,&flagdoftype,sizeof(flagdoftype));marshalled_dataset+=sizeof(flagdoftype);
+	memcpy(marshalled_dataset,&clone,sizeof(clone));marshalled_dataset+=sizeof(clone);
+	
+	if(this->gsize>0){
+		memcpy(marshalled_dataset,f_set,gsize*sizeof(bool));marshalled_dataset+=gsize*sizeof(bool);
+		memcpy(marshalled_dataset,s_set,gsize*sizeof(bool));marshalled_dataset+=gsize*sizeof(bool);
+		memcpy(marshalled_dataset,svalues,gsize*sizeof(double)); marshalled_dataset+=gsize*sizeof(double);
+		if(flagdoftype){ memcpy(marshalled_dataset,doftype,gsize*sizeof(int)); marshalled_dataset+=gsize*sizeof(int); }
+		memcpy(marshalled_dataset,gdoflist,gsize*sizeof(int)); marshalled_dataset+=gsize*sizeof(int);
+	}
+	if(this->fsize>0 && this->fsize!=UNDEF){ memcpy(marshalled_dataset,fdoflist,fsize*sizeof(int)); marshalled_dataset+=fsize*sizeof(int);}
+	if(this->ssize>0 && this->ssize!=UNDEF){ memcpy(marshalled_dataset,sdoflist,ssize*sizeof(int)); marshalled_dataset+=ssize*sizeof(int);}
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+/*FUNCTION DofIndexing::MarshallSize{{{1*/
+int   DofIndexing::MarshallSize(){
+
+	int size=0;
+
+	size+=4*sizeof(int)+sizeof(bool);
+	if(this->gsize>0){
+		size+= 2*this->gsize*sizeof(bool)+
+			   this->gsize*sizeof(double)+
+			   this->gsize*sizeof(int);
+		if(this->doftype)size+=this->gsize*sizeof(int);
+	}
+	if(this->fsize>0 && this->fsize!=UNDEF)size+=this->fsize*sizeof(int);
+	if(this->ssize>0 && this->ssize!=UNDEF)size+=this->ssize*sizeof(int);
+
+	size+=sizeof(int); //sizeof(int) for enum type
+
+	return size;
+}
+/*}}}*/
+/*FUNCTION DofIndexing::Demarshall{{{1*/
+void  DofIndexing::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type;
+	bool  flagdoftype;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of object since DofIndexing is not directly called by DataSet: */
+	memcpy(&enum_type,marshalled_dataset,sizeof(int)); marshalled_dataset+=sizeof(int);
+
+	/*easy part: */
+	memcpy(&gsize,marshalled_dataset,sizeof(gsize));marshalled_dataset+=sizeof(gsize);
+	memcpy(&fsize,marshalled_dataset,sizeof(fsize));marshalled_dataset+=sizeof(fsize);
+	memcpy(&ssize,marshalled_dataset,sizeof(ssize));marshalled_dataset+=sizeof(ssize);
+	memcpy(&flagdoftype,marshalled_dataset,sizeof(flagdoftype));marshalled_dataset+=sizeof(flagdoftype);
+	memcpy(&clone,marshalled_dataset,sizeof(clone));marshalled_dataset+=sizeof(clone);
+	
+	/*Allocate: */
+	if(this->gsize>0){
+		this->f_set=(bool*)xmalloc(this->gsize*sizeof(bool));
+		this->s_set=(bool*)xmalloc(this->gsize*sizeof(bool));
+		this->svalues=(double*)xmalloc(this->gsize*sizeof(double));
+		if(flagdoftype)this->doftype=(int*)xmalloc(this->gsize*sizeof(int));
+		else           this->doftype=NULL;
+		this->gdoflist=(int*)xmalloc(this->gsize*sizeof(int));
+	}
+	else{
+		this->f_set=NULL;
+		this->s_set=NULL;
+		this->svalues=NULL;
+		this->doftype=NULL;
+		this->gdoflist=NULL;
+	}
+	if(this->fsize>0)
+	 this->fdoflist=(int*)xmalloc(this->fsize*sizeof(int));
+	else
+	 this->fdoflist=NULL;
+	if(this->ssize>0)
+	 this->sdoflist=(int*)xmalloc(this->ssize*sizeof(int));
+	else
+	 this->sdoflist=NULL;
+
+	/*Copy arrays: */
+	if(this->gsize>0){
+		memcpy(f_set,marshalled_dataset,gsize*sizeof(bool));marshalled_dataset+=gsize*sizeof(bool);
+		memcpy(s_set,marshalled_dataset,gsize*sizeof(bool));marshalled_dataset+=gsize*sizeof(bool);
+		memcpy(svalues,marshalled_dataset,gsize*sizeof(double));marshalled_dataset+=gsize*sizeof(double);
+		if(flagdoftype){memcpy(doftype,marshalled_dataset,gsize*sizeof(int));marshalled_dataset+=gsize*sizeof(int); }
+		memcpy(gdoflist,marshalled_dataset,gsize*sizeof(int));marshalled_dataset+=gsize*sizeof(int);
+	}
+	
+	if(this->fsize>0 && this->fsize!=UNDEF){ memcpy(this->fdoflist,marshalled_dataset,this->fsize*sizeof(int));marshalled_dataset+=this->fsize*sizeof(int); }
+	if(this->ssize>0 && this->ssize!=UNDEF){ memcpy(this->sdoflist,marshalled_dataset,this->ssize*sizeof(int));marshalled_dataset+=this->ssize*sizeof(int); }
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+
Index: /issm/trunk-jpl-damage/src/c/objects/DofIndexing.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/DofIndexing.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/DofIndexing.h	(revision 11330)
@@ -0,0 +1,57 @@
+/*!\file: DofIndexing.h
+ * \brief prototype for DofIndexing.h
+ */ 
+
+#ifndef _DOFINDEXING_H_
+#define  _DOFINDEXING_H_
+
+class DofIndexing{
+	
+	public:
+
+		/*sizes: */
+		int gsize; //number of dofs for a node
+		int fsize; //number of dofs solver for
+		int ssize; //number of constrained dofs
+
+		/*partitioning: */
+		int     clone;   //this node is replicated from another one 
+
+		/*boundary conditions sets: */
+		bool*     f_set; //is dof on f-set (on which we solve)
+		bool*     s_set; //is dof on s-set (on which boundary conditions -dirichlet- are applied)
+		double*   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 {{{1*/
+		DofIndexing();
+		DofIndexing(int g_size);
+		void Init(int g_size,int* doftype);
+		void InitSet(int setenum);
+		DofIndexing(DofIndexing* properties);
+		~DofIndexing();
+		/*}}}*/
+		/*Object like functionality: {{{1*/
+		void  Echo(void); 
+		void  DeepEcho(void); 
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		void  copy(DofIndexing* properties);
+		/*}}}*/
+		/*DofIndexing management: {{{1*/
+		DofIndexing* Spawn(int* indices, int numindices);
+		/*}}}*/
+
+};
+#endif //ifndef _DOFINDEXING_H_
Index: /issm/trunk-jpl-damage/src/c/objects/ElementResults/BoolElementResult.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ElementResults/BoolElementResult.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ElementResults/BoolElementResult.cpp	(revision 11330)
@@ -0,0 +1,195 @@
+/*!\file BoolElementResult.c
+ * \brief: implementation of the BoolElementResult object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "./ElementResultLocal.h"
+#include "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+/*BoolElementResult constructors and destructor*/
+/*FUNCTION BoolElementResult::BoolElementResult(){{{1*/
+BoolElementResult::BoolElementResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::BoolElementResult(int in_enum_type,IssmDouble in_value,int in_step, double in_time){{{1*/
+BoolElementResult::BoolElementResult(int in_enum_type,bool in_value,int in_step, double in_time){
+
+	enum_type=in_enum_type;
+	value=in_value;
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::~BoolElementResult(){{{1*/
+BoolElementResult::~BoolElementResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION BoolElementResult::Echo {{{1*/
+void BoolElementResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::DeepEcho{{{1*/
+void BoolElementResult::DeepEcho(void){
+
+	printf("BoolElementResult:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %s\n",this->value?"true":"false");
+	printf("   step: %i\n",this->step);
+	printf("   time: %g\n",this->time);
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::Id{{{1*/
+int    BoolElementResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION BoolElementResult::MyRank{{{1*/
+int    BoolElementResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION BoolElementResult::Marshall{{{1*/
+void  BoolElementResult::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of BoolElementResult: */
+	enum_value=BoolElementResultEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall BoolElementResult data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&value,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(marshalled_dataset,&time,sizeof(time));marshalled_dataset+=sizeof(time);
+	memcpy(marshalled_dataset,&step,sizeof(step));marshalled_dataset+=sizeof(step);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::Demarshall{{{1*/
+void  BoolElementResult::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&value,marshalled_dataset,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(&time,marshalled_dataset,sizeof(time));marshalled_dataset+=sizeof(time);
+	memcpy(&step,marshalled_dataset,sizeof(step));marshalled_dataset+=sizeof(step);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::MarshallSize{{{1*/
+int   BoolElementResult::MarshallSize(){
+	
+	return sizeof(value)+
+		+sizeof(enum_type)
+		+sizeof(time)
+		+sizeof(step)
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+#endif
+/*FUNCTION BoolElementResult::ObjectEnum{{{1*/
+int BoolElementResult::ObjectEnum(void){
+
+	return BoolElementResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::copy{{{1*/
+Object* BoolElementResult::copy() {
+
+	return new BoolElementResult(this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*ElementResult management*/
+/*FUNCTION BoolElementResult::InstanceEnum{{{1*/
+int BoolElementResult::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::SpawnTriaElementResult{{{1*/
+ElementResult* BoolElementResult::SpawnTriaElementResult(int* indices){
+
+	/*output*/
+	BoolElementResult* outresult=new BoolElementResult();
+
+	/*copy fields: */
+	outresult->enum_type=this->enum_type;
+	outresult->value=this->value;
+	outresult->time=this->time;
+	outresult->step=this->step;
+
+	/*Assign output*/
+	return outresult;
+
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::ProcessUnits{{{1*/
+void BoolElementResult::ProcessUnits(Parameters* parameters){
+	
+	this->value=UnitConversion(this->value,IuToExtEnum,this->enum_type);
+
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::NumberOfNodalValues{{{1*/
+int BoolElementResult::NumberOfNodalValues(void){
+	return 1;
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::PatchFill{{{1*/
+void BoolElementResult::PatchFill(int row, Patch* patch){
+	
+	 /*Here, we fill the result information into the patch object. First, let's remember what is in a row 
+	  * of the patch object: enum_type step time element_id interpolation vertices_ids nodal_values
+	  * Here, we will supply the enum_type, step, time, interpolation and nodal_values: */
+	double doublevalue=this->value?1:0;
+	patch->fillresultinfo(row,this->enum_type,this->step,this->time,P0Enum,&doublevalue,1);
+
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::GetVectorFromResults{{{1*/
+void BoolElementResult::GetVectorFromResults(Vec vector,int* doflist,int* connectivitylist,int numdofs){
+
+	_error_("cannot return vector on vertices");
+} /*}}}*/
+/*FUNCTION BoolElementResult::GetElementVectorFromResults{{{1*/
+void BoolElementResult::GetElementVectorFromResults(Vec vector,int dof){
+
+	VecSetValue(vector,dof,(double)value,INSERT_VALUES);
+} /*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/ElementResults/BoolElementResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ElementResults/BoolElementResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ElementResults/BoolElementResult.h	(revision 11330)
@@ -0,0 +1,59 @@
+/*! \file BoolElementResult.h 
+ *  \brief: header file for bool result object
+ *  A boll result object is just derived from a BoolInput object, with additional time and step information.
+ */
+
+
+#ifndef _BOOLELEMENTRESULT_H_
+#define _BOOLELEMENTRESULT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../Inputs/Input.h"
+#include "../../include/include.h"
+class Parameters;
+/*}}}*/
+
+class BoolElementResult: public ElementResult{
+
+	private: 
+		int    enum_type;
+		bool   value;
+		int    step;
+		double time;
+
+	public:
+
+		/*BoolElementResult constructors, destructors: {{{1*/
+		BoolElementResult();
+		BoolElementResult(int enum_type,bool value,int step,double time);
+		~BoolElementResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ElementResult virtual functions definitions: {{{1*/
+		ElementResult* SpawnTriaElementResult(int* indices);
+		double  GetTime(void){return time;};
+		int     GetStep(void){return step;};
+		void    ProcessUnits(Parameters* parameters);
+		int     NumberOfNodalValues(void);
+		void    PatchFill(int row, Patch* patch);
+		/*}}}*/
+		/*BoolElementResult management: {{{1*/
+		int   InstanceEnum();
+		void GetVectorFromResults(Vec vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vec vector,int dof);
+		/*}}}*/
+};
+#endif  /* _BOOLELEMENTRESULT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/ElementResults/DoubleElementResult.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ElementResults/DoubleElementResult.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ElementResults/DoubleElementResult.cpp	(revision 11330)
@@ -0,0 +1,184 @@
+/*!\file DoubleElementResult.c
+ * \brief: implementation of the DoubleElementResult object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "./ElementResultLocal.h"
+#include "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+/*DoubleElementResult constructors and destructor*/
+/*FUNCTION DoubleElementResult::DoubleElementResult(){{{1*/
+DoubleElementResult::DoubleElementResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::DoubleElementResult(int in_enum_type,IssmDouble in_value,int in_step, double in_time){{{1*/
+DoubleElementResult::DoubleElementResult(int in_enum_type,IssmDouble in_value,int in_step, double in_time){
+
+	enum_type=in_enum_type;
+	value=in_value;
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::~DoubleElementResult(){{{1*/
+DoubleElementResult::~DoubleElementResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleElementResult::Echo {{{1*/
+void DoubleElementResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::DeepEcho{{{1*/
+void DoubleElementResult::DeepEcho(void){
+
+	printf("DoubleElementResult:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %g\n",this->value);
+	printf("   step: %i\n",this->step);
+	printf("   time: %g\n",this->time);
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::Id{{{1*/
+int    DoubleElementResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleElementResult::MyRank{{{1*/
+int    DoubleElementResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION DoubleElementResult::Marshall{{{1*/
+void  DoubleElementResult::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of DoubleElementResult: */
+	enum_value=DoubleElementResultEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall DoubleElementResult data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&value,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(marshalled_dataset,&time,sizeof(time));marshalled_dataset+=sizeof(time);
+	memcpy(marshalled_dataset,&step,sizeof(step));marshalled_dataset+=sizeof(step);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::Demarshall{{{1*/
+void  DoubleElementResult::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&value,marshalled_dataset,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(&step,marshalled_dataset,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(&time,marshalled_dataset,sizeof(time));marshalled_dataset+=sizeof(time);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::MarshallSize{{{1*/
+int   DoubleElementResult::MarshallSize(){
+	
+	return sizeof(value)+
+		+sizeof(enum_type)
+		+sizeof(time)
+		+sizeof(step)
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+#endif
+/*FUNCTION DoubleElementResult::ObjectEnum{{{1*/
+int DoubleElementResult::ObjectEnum(void){
+
+	return DoubleElementResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::copy{{{1*/
+Object* DoubleElementResult::copy() {
+
+	return new DoubleElementResult(this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*ElementResult management*/
+/*FUNCTION DoubleElementResult::InstanceEnum{{{1*/
+int DoubleElementResult::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::SpawnTriaElementResult{{{1*/
+ElementResult* DoubleElementResult::SpawnTriaElementResult(int* indices){
+
+	/*output*/
+	DoubleElementResult* outresult=new DoubleElementResult();
+
+	/*copy fields: */
+	outresult->enum_type=this->enum_type;
+	outresult->value=this->value;
+	outresult->time=this->time;
+	outresult->step=this->step;
+
+	/*Assign output*/
+	return outresult;
+
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::ProcessUnits{{{1*/
+void DoubleElementResult::ProcessUnits(Parameters* parameters){
+	
+	this->value=UnitConversion(this->value,IuToExtEnum,this->enum_type);
+
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::NumberOfNodalValues{{{1*/
+int DoubleElementResult::NumberOfNodalValues(void){
+	return 1;
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::PatchFill{{{1*/
+void DoubleElementResult::PatchFill(int row, Patch* patch){
+	
+	 /*Here, we fill the result information into the patch object. First, let's remember what is in a row 
+	  * of the patch object: enum_type step time element_id interpolation vertices_ids nodal_values
+	  * Here, we will supply the enum_type, step, time, interpolation and nodal_values: */
+	patch->fillresultinfo(row,this->enum_type,this->step,this->time,P0Enum,&this->value,1);
+
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/ElementResults/DoubleElementResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ElementResults/DoubleElementResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ElementResults/DoubleElementResult.h	(revision 11330)
@@ -0,0 +1,59 @@
+/*! \file DoubleElementResult.h 
+ *  \brief: header file for double result object
+ *  A double result object is just derived from a DoubleInput object, with additional time and step information.
+ */
+
+
+#ifndef _DOUBLEELEMENTRESULT_H_
+#define _DOUBLEELEMENTRESULT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../Inputs/Input.h"
+#include "../../include/include.h"
+class Parameters;
+/*}}}*/
+
+class DoubleElementResult: public ElementResult{
+
+	private: 
+		int    enum_type;
+		double value;
+		int    step;
+		double time;
+
+	public:
+
+		/*DoubleElementResult constructors, destructors: {{{1*/
+		DoubleElementResult();
+		DoubleElementResult(int enum_type,double value,int step,double time);
+		~DoubleElementResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ElementResult virtual functions definitions: {{{1*/
+		ElementResult* SpawnTriaElementResult(int* indices);
+		double  GetTime(void){return time;};
+		int     GetStep(void){return step;};
+		void    ProcessUnits(Parameters* parameters);
+		int     NumberOfNodalValues(void);
+		void    PatchFill(int row, Patch* patch);
+		/*}}}*/
+		/*DoubleElementResult management: {{{1*/
+		int   InstanceEnum();
+		void GetVectorFromResults(Vec vector,int* doflist,int* connectivitylist,int numdofs){_error_("not implemented");};
+		void GetElementVectorFromResults(Vec vector,int dof){_error_("not implemented");};
+		/*}}}*/
+};
+#endif  /* _DOUBLEELEMENTRESULT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/ElementResults/ElementResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ElementResults/ElementResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ElementResults/ElementResult.h	(revision 11330)
@@ -0,0 +1,32 @@
+/*!\file:  ElementResult.h
+ * \brief abstract class for ElementResult object
+ */ 
+
+
+#ifndef _ELEMENTRESULT_H_
+#define _ELEMENTRESULT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../Object.h"
+/*}}}*/
+
+class ElementResult:public Object{
+
+	public: 
+		
+		virtual        ~ElementResult(){};
+		
+		virtual         ElementResult* SpawnTriaElementResult(int* indices)=0;
+		virtual double  GetTime(void)=0;
+		virtual int     GetStep(void)=0;
+		virtual void    ProcessUnits(Parameters* parameters)=0;
+		virtual int     NumberOfNodalValues(void)=0;
+		virtual void    PatchFill(int row, Patch* patch)=0;
+		virtual int     InstanceEnum()=0;
+		virtual void    GetVectorFromResults(Vec vector,int* doflist,int* connectivitylist,int numdof)=0;
+		virtual void    GetElementVectorFromResults(Vec vector,int dof)=0;
+
+};
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/ElementResults/ElementResultLocal.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ElementResults/ElementResultLocal.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ElementResults/ElementResultLocal.h	(revision 11330)
@@ -0,0 +1,11 @@
+/*!\file: ElementResultLocal.h
+ * \brief prototypes for ElementResultLocal.h
+ */ 
+
+#ifndef _ELEMENTRESULTLOCAL_H_
+#define  _ELEMENTRESULTLOCAL_H_
+
+class Parameters;
+
+#endif //ifndef _ELEMENTRESULTLOCAL_H_
+
Index: /issm/trunk-jpl-damage/src/c/objects/ElementResults/PentaP1ElementResult.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ElementResults/PentaP1ElementResult.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ElementResults/PentaP1ElementResult.cpp	(revision 11330)
@@ -0,0 +1,210 @@
+/*!\file PentaP1ElementResult.c
+ * \brief: implementation of the PentaP1ElementResult object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "./ElementResultLocal.h"
+#include "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+/*PentaP1ElementResult constructors and destructor*/
+/*FUNCTION PentaP1ElementResult::PentaP1ElementResult(){{{1*/
+PentaP1ElementResult::PentaP1ElementResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::PentaP1ElementResult(int in_enum_type,double* in_values,int in_step, double in_time){{{1*/
+PentaP1ElementResult::PentaP1ElementResult(int in_enum_type,double* in_values,int in_step, double in_time){
+
+	int i;
+
+	enum_type=in_enum_type;
+	for(i=0;i<6;i++)values[i]=in_values[i];
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::~PentaP1ElementResult(){{{1*/
+PentaP1ElementResult::~PentaP1ElementResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION PentaP1ElementResult::Echo {{{1*/
+void PentaP1ElementResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::DeepEcho{{{1*/
+void PentaP1ElementResult::DeepEcho(void){
+
+	printf("PentaP1ElementResult:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   values: [%g %g %g %g %g %g]\n",this->values[0],this->values[1],this->values[2],this->values[3],this->values[4],this->values[5]);
+	printf("   step: %i\n",this->step);
+	printf("   time: %g\n",this->time);
+
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::Id{{{1*/
+int    PentaP1ElementResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::MyRank{{{1*/
+int    PentaP1ElementResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION PentaP1ElementResult::Marshall{{{1*/
+void  PentaP1ElementResult::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of PentaP1ElementResult: */
+	enum_value=PentaP1ElementResultEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall PentaP1ElementResult data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&values,sizeof(values));marshalled_dataset+=sizeof(values);
+	memcpy(marshalled_dataset,&time,sizeof(time));marshalled_dataset+=sizeof(time);
+	memcpy(marshalled_dataset,&step,sizeof(step));marshalled_dataset+=sizeof(step);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::MarshallSize{{{1*/
+int   PentaP1ElementResult::MarshallSize(){
+	
+	return sizeof(values)+
+		+sizeof(enum_type)
+		+sizeof(time)
+		+sizeof(step)
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::Demarshall{{{1*/
+void  PentaP1ElementResult::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&values,marshalled_dataset,sizeof(values));marshalled_dataset+=sizeof(values);
+	memcpy(&time,marshalled_dataset,sizeof(time));marshalled_dataset+=sizeof(time);
+	memcpy(&step,marshalled_dataset,sizeof(step));marshalled_dataset+=sizeof(step);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION PentaP1ElementResult::ObjectEnum{{{1*/
+int PentaP1ElementResult::ObjectEnum(void){
+
+	return PentaP1ElementResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::copy{{{1*/
+Object* PentaP1ElementResult::copy() {
+	
+	return new PentaP1ElementResult(this->enum_type,this->values,this->step,this->time);
+
+}
+/*}}}*/
+
+/*ElementResult management*/
+/*FUNCTION PentaP1ElementResult::InstanceEnum{{{1*/
+int PentaP1ElementResult::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::SpawnTriaElementResult{{{1*/
+ElementResult* PentaP1ElementResult::SpawnTriaElementResult(int* indices){
+
+	/*output*/
+	TriaP1ElementResult* outresult=NULL;
+	double newvalues[3];
+
+	/*Loop over the new indices*/
+	for(int i=0;i<3;i++){
+
+		/*Check index value*/
+		_assert_(indices[i]>=0 && indices[i]<6);
+
+		/*Assign value to new result*/
+		newvalues[i]=this->values[indices[i]];
+	}
+
+	/*Create new Tria result*/
+	outresult=new TriaP1ElementResult(this->enum_type,&newvalues[0],this->step,this->time);
+
+	/*Assign output*/
+	return outresult;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::ProcessUnits{{{1*/
+void PentaP1ElementResult::ProcessUnits(Parameters* parameters){
+	
+	UnitConversion(this->values,6,IuToExtEnum,this->enum_type);
+
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::NumberOfNodalValues{{{1*/
+int PentaP1ElementResult::NumberOfNodalValues(void){
+	return 6;
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::PatchFill{{{1*/
+void PentaP1ElementResult::PatchFill(int row, Patch* patch){
+	
+	 /*Here, we fill the result information into the patch object. First, let's remember what is in a row 
+	  * of the patch object: enum_type step time element_id interpolation vertices_ids nodal_values
+	  * Here, we will supply the enum_type, step, time, interpolation and nodal_values: */
+	patch->fillresultinfo(row,this->enum_type,this->step,this->time,P1Enum,this->values,6);
+
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::GetVectorFromResults{{{1*/
+void PentaP1ElementResult::GetVectorFromResults(Vec vector,int* doflist,int* connectivitylist,int numdofs){
+
+	double data[6];
+
+	if(numdofs!=6)_error_("Result %s is a PentaP1ElementResult and cannot write vector of %i dofs",numdofs);
+	for(int i=0;i<6;i++) data[i]=this->values[i]/(double)connectivitylist[i];
+	VecSetValues(vector,numdofs,doflist,(const double*)&data,ADD_VALUES);
+
+} /*}}}*/
+/*FUNCTION PentaP1ElementResult::GetElementVectorFromResults{{{1*/
+void PentaP1ElementResult::GetElementVectorFromResults(Vec vector,int dof){
+
+	_error_("Result %s is a PentaP1ElementResult and should not write vector of size numberofelemenrs",EnumToStringx(enum_type));
+} /*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/ElementResults/PentaP1ElementResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ElementResults/PentaP1ElementResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ElementResults/PentaP1ElementResult.h	(revision 11330)
@@ -0,0 +1,59 @@
+/*! \file PentaP1ElementResult.h 
+ *  \brief: header file for PentaP1ElementResult object
+ *  this object is just a PentaP1Input with additional time and step info.
+ */
+
+
+#ifndef _PENTAP1ELEMENTRESULT_H_
+#define _PENTAP1ELEMENTRESULT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../Inputs/Input.h"
+#include "../../include/include.h"
+/*}}}*/
+
+class PentaP1ElementResult: public ElementResult{
+
+	private: 
+		int    enum_type;
+		double values[6];
+		int    step;
+		double time;
+
+	public:
+
+		/*PentaP1ElementResult constructors, destructors: {{{1*/
+		PentaP1ElementResult();
+		PentaP1ElementResult(int enum_type,double* values,int step, double time);
+		~PentaP1ElementResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ElementResult virtual functions definitions: {{{1*/
+		ElementResult* SpawnTriaElementResult(int* indices);
+		double  GetTime(void){return time;};
+		int     GetStep(void){return step;};
+		void    ProcessUnits(Parameters* parameters);
+		int     NumberOfNodalValues(void);
+		void    PatchFill(int row, Patch* patch);
+		/*}}}*/
+		/*PentaP1ElementResult management: {{{1*/
+		int   InstanceEnum();
+		void GetVectorFromResults(Vec vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vec vector,int dof);
+		/*}}}*/
+
+};
+#endif  /* _PENTAP1ELEMENTRESULT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/ElementResults/TriaP1ElementResult.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ElementResults/TriaP1ElementResult.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ElementResults/TriaP1ElementResult.cpp	(revision 11330)
@@ -0,0 +1,199 @@
+/*!\file TriaP1ElementResult.c
+ * \brief: implementation of the TriaP1ElementResult object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "./ElementResultLocal.h"
+#include "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+/*TriaP1ElementResult constructors and destructor*/
+/*FUNCTION TriaP1ElementResult::TriaP1ElementResult(){{{1*/
+TriaP1ElementResult::TriaP1ElementResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::TriaP1ElementResult(int in_enum_type,double* in_values,int in_step, double in_time){{{1*/
+TriaP1ElementResult::TriaP1ElementResult(int in_enum_type,double* in_values,int in_step, double in_time){
+
+	enum_type=in_enum_type;
+	values[0]=in_values[0];
+	values[1]=in_values[1];
+	values[2]=in_values[2];
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::~TriaP1ElementResult(){{{1*/
+TriaP1ElementResult::~TriaP1ElementResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION TriaP1ElementResult::Echo {{{1*/
+void TriaP1ElementResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::DeepEcho{{{1*/
+void TriaP1ElementResult::DeepEcho(void){
+		
+	printf("TriaP1ElementResult:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   values: [%g %g %g]\n",this->values[0],this->values[1],this->values[2]);
+	printf("   step: %i\n",this->step);
+	printf("   time: %g\n",this->time);
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::Id{{{1*/
+int    TriaP1ElementResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::MyRank{{{1*/
+int    TriaP1ElementResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION TriaP1ElementResult::Marshall{{{1*/
+void  TriaP1ElementResult::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of TriaP1ElementResult: */
+	enum_value=TriaP1ElementResultEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall TriaP1ElementResult data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&values,sizeof(values));marshalled_dataset+=sizeof(values);
+	memcpy(marshalled_dataset,&time,sizeof(time));marshalled_dataset+=sizeof(time);
+	memcpy(marshalled_dataset,&step,sizeof(step));marshalled_dataset+=sizeof(step);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::MarshallSize{{{1*/
+int   TriaP1ElementResult::MarshallSize(){
+	
+	return sizeof(values)
+		+sizeof(enum_type)
+		+sizeof(time)
+		+sizeof(step)
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::Demarshall{{{1*/
+void  TriaP1ElementResult::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&values,marshalled_dataset,sizeof(values));marshalled_dataset+=sizeof(values);
+	memcpy(&time,marshalled_dataset,sizeof(time));marshalled_dataset+=sizeof(time);
+	memcpy(&step,marshalled_dataset,sizeof(step));marshalled_dataset+=sizeof(step);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION TriaP1ElementResult::ObjectEnum{{{1*/
+int TriaP1ElementResult::ObjectEnum(void){
+
+	return TriaP1ElementResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::copy{{{1*/
+Object* TriaP1ElementResult::copy() {
+	
+	return new TriaP1ElementResult(this->enum_type,this->values,this->step,this->time);
+
+}
+/*}}}*/
+
+/*ElementResult management*/
+/*FUNCTION TriaP1ElementResult::InstanceEnum{{{1*/
+int TriaP1ElementResult::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::SpawnTriaElementResult{{{1*/
+ElementResult* TriaP1ElementResult::SpawnTriaElementResult(int* indices){
+
+	/*output*/
+	TriaP1ElementResult* outresult=NULL;
+
+	/*Create new Tria result (copy of current result)*/
+	outresult=new TriaP1ElementResult(this->enum_type,&this->values[0],this->step,this->time);
+
+	/*Assign output*/
+	return outresult;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::ProcessUnits{{{1*/
+void TriaP1ElementResult::ProcessUnits(Parameters* parameters){
+	
+	UnitConversion(this->values,3,IuToExtEnum,this->enum_type);
+
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::NumberOfNodalValues{{{1*/
+int TriaP1ElementResult::NumberOfNodalValues(void){
+	return 3;
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::PatchFill{{{1*/
+void TriaP1ElementResult::PatchFill(int row, Patch* patch){
+	
+	 /*Here, we fill the result information into the patch object. First, let's remember what is in a row 
+	  * of the patch object: enum_type step time element_id interpolation vertices_ids nodal_values
+	  * Here, we will supply the enum_type, step, time, interpolation and nodal_values: */
+	patch->fillresultinfo(row,this->enum_type,this->step,this->time,P1Enum,this->values,3);
+
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::GetVectorFromResults{{{1*/
+void TriaP1ElementResult::GetVectorFromResults(Vec vector,int* doflist,int* connectivitylist,int numdofs){
+
+	double data[3];
+
+	if(numdofs!=3)_error_("Result %s is a TriaP1ElementResult and cannot write vector of %i dofs",numdofs);
+	for(int i=0;i<3;i++) data[i]=this->values[i]/(double)connectivitylist[i];
+	VecSetValues(vector,numdofs,doflist,(const double*)&data,ADD_VALUES);
+
+} /*}}}*/
+/*FUNCTION TriaP1ElementResult::GetElementVectorFromResults{{{1*/
+void TriaP1ElementResult::GetElementVectorFromResults(Vec vector,int dof){
+
+	_error_("Result %s is a TriaP1ElementResult and should not write vector of size numberofelemenrs",EnumToStringx(enum_type));
+} /*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/ElementResults/TriaP1ElementResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ElementResults/TriaP1ElementResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ElementResults/TriaP1ElementResult.h	(revision 11330)
@@ -0,0 +1,58 @@
+/*! \file TriaP1ElementResult.h 
+ *  \brief: header file for TriaP1ElementResult object
+ */
+
+
+#ifndef _TRIAP1ELEMENTRESULT_H_
+#define _TRIAP1ELEMENTRESULT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../Inputs/Input.h"
+#include "../../include/include.h"
+/*}}}*/
+
+class TriaP1ElementResult: public ElementResult{
+
+	private: 
+		int    enum_type;
+		double values[3];
+		int    step;
+		double time;
+
+	public:
+
+		/*TriaP1ElementResult constructors, destructors: {{{1*/
+		TriaP1ElementResult();
+		TriaP1ElementResult(int enum_type,double* values,int step,double time);
+		~TriaP1ElementResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ElementResult virtual functions definitions: {{{1*/
+		ElementResult* SpawnTriaElementResult(int* indices);
+		double  GetTime(void){return time;};
+		int     GetStep(void){return step;};
+		void    ProcessUnits(Parameters* parameters);
+		int     NumberOfNodalValues(void);
+		void    PatchFill(int row, Patch* patch);
+		/*}}}*/
+		/*TriaP1ElementResult management: {{{1*/
+		int   InstanceEnum();
+		void GetVectorFromResults(Vec vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vec vector,int dof);
+		/*}}}*/
+
+};
+#endif  /* _TRIAP1ELEMENTRESULT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Elements/Element.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Elements/Element.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Elements/Element.h	(revision 11330)
@@ -0,0 +1,108 @@
+/*!\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:*/
+/*{{{1*/
+#include "../Object.h"
+
+class DataSet;
+class Parameters;
+class Patch;
+
+#include "../../toolkits/toolkits.h"
+/*}}}*/
+
+class Element: public Object,public Update{
+
+	public: 
+		
+		virtual        ~Element(){};
+	
+		virtual void   Configure(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters)=0;
+		virtual void   SetCurrentConfiguration(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters)=0;
+		virtual void   CreateKMatrix(Mat Kff, Mat Kfs,Vec df)=0;
+		virtual void   CreatePVector(Vec pf)=0;
+		virtual void   GetSolutionFromInputs(Vec solution)=0;
+		virtual int    GetNodeIndex(Node* node)=0;
+		virtual int    Sid()=0;
+		virtual bool   IsFloating()=0; 
+		virtual bool   IsNodeOnShelf()=0; 
+		virtual bool   IsNodeOnShelfFromFlags(double* flags)=0; 
+		virtual bool   IsOnBed()=0;
+		virtual void   GetInputListOnVertices(double* pvalue,int enumtype)=0;
+		virtual void   GetInputListOnVertices(double* pvalue,int enumtype,double defaultvalue)=0;
+		virtual void   GetInputValue(double* pvalue,Node* node,int enumtype)=0;
+		
+		virtual double SurfaceArea(void)=0;
+		virtual void   InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum)=0;
+		virtual void   ComputeBasalStress(Vec sigma_b)=0;
+		virtual void   ComputeStrainRate(Vec eps)=0;
+		virtual void   PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes)=0;
+		virtual void   PatchFill(int* pcount, Patch* patch)=0;
+		virtual void   ListResultsInfo(int** results_enums,int** results_size,double** results_times,int** results_steps,int* num_results)=0;
+		virtual void   DeleteResults(void)=0;
+		virtual void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type)=0;
+		virtual void   InputToResult(int enum_type,int step,double time)=0;
+		virtual void   InputDuplicate(int original_enum,int new_enum)=0;
+		virtual void   InputCreate(double scalar,int name,int code)=0;
+		virtual void   InputCreate(double* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code)=0;
+		virtual void   ProcessResultsUnits(void)=0;
+		virtual void   RequestedOutput(int output_enum,int step,double time)=0;
+		
+		virtual void   InputScale(int enum_type,double scale_factor)=0;
+		virtual void   GetVectorFromInputs(Vec vector, int name_enum)=0;
+		virtual void   GetVectorFromResults(Vec vector,int id,int interp)=0;
+		virtual void   InputArtificialNoise(int enum_type,double min,double max)=0;
+		virtual bool   InputConvergence(double* eps, int* enums,int num_enums,int* criterionenums,double* criterionvalues,int num_criterionenums)=0;
+		virtual void   AverageOntoPartition(Vec partition_contributions,Vec partition_areas,double* vertex_response,double* qmu_part)=0;
+		virtual int*   GetHorizontalNeighboorSids(void)=0;
+		virtual double TimeAdapt()=0;
+		virtual void   MigrateGroundingLine(double* old_floating_ice,double* sheet_ungrounding)=0;
+		virtual void   PotentialSheetUngrounding(Vec potential_sheet_ungrounding)=0;
+		virtual int    UpdatePotentialSheetUngrounding(double* potential_sheet_ungrounding,Vec vec_nodes_on_iceshelf,double* nodes_on_iceshelf)=0;
+		virtual void   ResetCoordinateSystem()=0;
+		virtual void   SmearFunction(Vec smearedvector,double (*WeightFunction)(double distance,double radius),double radius)=0;
+
+		#ifdef _HAVE_RESPONSES_
+		virtual void   MinVel(double* pminvel, bool process_units)=0;
+		virtual void   MaxVel(double* pmaxvel, bool process_units)=0;
+		virtual void   MinVx(double* pminvx, bool process_units)=0;
+		virtual void   MaxVx(double* pmaxvx, bool process_units)=0;
+		virtual void   MaxAbsVx(double* pmaxabsvx, bool process_units)=0;
+		virtual void   MinVy(double* pminvy, bool process_units)=0;
+		virtual void   MaxVy(double* pmaxvy, bool process_units)=0;
+		virtual void   MaxAbsVy(double* pmaxabsvy, bool process_units)=0;
+		virtual void   MinVz(double* pminvz, bool process_units)=0;
+		virtual void   MaxVz(double* pmaxvz, bool process_units)=0;
+		virtual void   MaxAbsVz(double* pmaxabsvz, bool process_units)=0;
+		virtual double MassFlux(double* segment,bool process_units)=0;
+		virtual void   ElementResponse(double* presponse,int response_enum,bool process_units)=0;
+		virtual double IceVolume(void)=0;
+		virtual int    NodalValue(double* pvalue, int index, int natureofdataenum,bool process_units)=0;
+		#endif
+
+		#ifdef _HAVE_CONTROL_
+		virtual void   Gradj(Vec gradient,int control_type)=0;
+		virtual double ThicknessAbsMisfit(bool process_units  ,int weight_index)=0;
+		virtual double SurfaceAbsVelMisfit(bool process_units ,int weight_index)=0;
+		virtual double SurfaceRelVelMisfit(bool process_units ,int weight_index)=0;
+		virtual double SurfaceLogVelMisfit(bool process_units ,int weight_index)=0;
+		virtual double SurfaceLogVxVyMisfit(bool process_units,int weight_index)=0;
+		virtual double SurfaceAverageVelMisfit(bool process_units,int weight_index)=0;
+		virtual double ThicknessAbsGradient(bool process_units,int weight_index)=0;
+		virtual double RheologyBbarAbsGradient(bool process_units,int weight_index)=0;
+		virtual double DragCoefficientAbsGradient(bool process_units,int weight_index)=0;
+		virtual void   ControlInputGetGradient(Vec gradient,int enum_type)=0;
+		virtual void   ControlInputSetGradient(double* gradient,int enum_type)=0;
+		virtual void   ControlInputScaleGradient(int enum_type, double scale)=0;
+		virtual void   InputControlUpdate(double scalar,bool save_parameter)=0;
+		#endif
+};
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Elements/Penta.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Elements/Penta.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Elements/Penta.cpp	(revision 11330)
@@ -0,0 +1,8219 @@
+/*!\file Penta.cpp
+ * \brief: implementation of the Penta object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../Container/Container.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES   6
+#define NUMVERTICES2D 3
+
+/*Constructors/destructor/copy*/
+/*FUNCTION Penta::Penta(){{{1*/
+Penta::Penta(){
+
+	int i;
+
+	this->nodes=NULL;
+	this->matice=NULL;
+	this->matpar=NULL;
+	this->verticalneighbors=NULL;
+	this->inputs=NULL;
+	this->parameters=NULL;
+	this->results=NULL;
+	for(i=0;i<3;i++)this->horizontalneighborsids[i]=UNDEF;
+}
+/*}}}*/
+/*FUNCTION Penta::~Penta(){{{1*/
+Penta::~Penta(){
+	delete inputs;
+	delete results;
+	this->parameters=NULL;
+}
+/*}}}*/
+/*FUNCTION Penta::Penta(int id, int index, IoModel* iomodel,int nummodels) {{{1*/
+Penta::Penta(int penta_id, int penta_sid, int index, IoModel* iomodel,int nummodels)
+	:PentaRef(nummodels)
+	,PentaHook(nummodels,index+1,iomodel) //index+1: matice id, iomodel->numberofelements+1: matpar id
+                                                                      { //i is the element index
+
+	int i;
+	int penta_elements_ids[2];
+
+	/*Checks in debugging mode*/
+	/*{{{2*/
+	_assert_(iomodel->Data(MeshUpperelementsEnum));
+	_assert_(iomodel->Data(MeshLowerelementsEnum));
+	/*}}}*/
+
+	/*id: */
+	this->id=penta_id;
+	this->sid=penta_sid;
+
+	/*Build neighbors list*/
+	if (isnan(iomodel->Data(MeshUpperelementsEnum)[index])) penta_elements_ids[1]=this->id; //upper penta is the same penta
+	else                                    penta_elements_ids[1]=(int)(iomodel->Data(MeshUpperelementsEnum)[index]);
+	if (isnan(iomodel->Data(MeshLowerelementsEnum)[index])) penta_elements_ids[0]=this->id; //lower penta is the same penta
+	else                                    penta_elements_ids[0]=(int)(iomodel->Data(MeshLowerelementsEnum)[index]);
+	this->InitHookNeighbors(penta_elements_ids);
+
+	/*Build horizontalneighborsids list: */
+	_assert_(iomodel->Data(MeshElementconnectivityEnum));
+	for(i=0;i<3;i++) this->horizontalneighborsids[i]=(int)iomodel->Data(MeshElementconnectivityEnum)[3*index+i]-1;
+
+	//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+	this->parameters=NULL;
+
+	/*intialize inputs and results: */
+	this->inputs=new Inputs();
+	this->results=new Results();
+	
+	/*initialize pointers:*/
+	this->nodes=NULL;
+	this->matice=NULL;
+	this->matpar=NULL;
+	this->verticalneighbors=NULL;
+}
+/*}}}*/
+/*FUNCTION Penta::copy {{{1*/
+Object* Penta::copy() {
+
+	int i;
+
+	Penta* penta=NULL;
+
+	penta=new Penta();
+
+	//deal with PentaRef mother class
+	penta->element_type_list=(int*)xmalloc(this->numanalyses*sizeof(int));
+	for(i=0;i<this->numanalyses;i++) penta->element_type_list[i]=this->element_type_list[i];
+
+	//deal with PentaHook mother class
+	penta->numanalyses=this->numanalyses;
+	penta->hnodes=new Hook*[penta->numanalyses];
+	for(i=0;i<penta->numanalyses;i++)penta->hnodes[i]=(Hook*)this->hnodes[i]->copy();
+	penta->hmatice=(Hook*)this->hmatice->copy();
+	penta->hmatpar=(Hook*)this->hmatpar->copy();
+	penta->hneighbors=(Hook*)this->hneighbors->copy();
+
+	/*deal with Penta  copy fields: */
+	penta->id=this->id;
+	penta->sid=this->sid;
+	if(this->inputs){
+		penta->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		penta->inputs=new Inputs();
+	}
+	if(this->results){
+		penta->results=(Results*)this->results->Copy();
+	}
+	else{
+		penta->results=new Results();
+	}
+	/*point parameters: */
+	penta->parameters=this->parameters;
+
+	/*recover objects: */
+	penta->nodes=(Node**)xmalloc(6*sizeof(Node*)); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
+	for(i=0;i<6;i++)penta->nodes[i]=this->nodes[i];
+	penta->matice=(Matice*)penta->hmatice->delivers();
+	penta->matpar=(Matpar*)penta->hmatpar->delivers();
+	penta->verticalneighbors=(Penta**)penta->hneighbors->deliverp();
+
+	/*neighbors: */
+	for(i=0;i<3;i++)penta->horizontalneighborsids[i]=this->horizontalneighborsids[i];
+
+	return penta;
+}
+/*}}}*/
+
+/*Marshall*/
+#ifdef _SERIAL_
+/*FUNCTION Penta::Marshall {{{1*/
+void  Penta::Marshall(char** pmarshalled_dataset){
+
+	int   i;
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+	char* marshalled_inputs=NULL;
+	int   marshalled_inputs_size;
+	char* marshalled_results=NULL;
+	int   marshalled_results_size;
+	int   flaghook; //to indicate if hook is NULL or exists
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of Penta: */
+	enum_type=PentaEnum;
+
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+
+	/*marshall Penta data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&sid,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(marshalled_dataset,&numanalyses,sizeof(numanalyses));marshalled_dataset+=sizeof(numanalyses);
+
+	/*Mershall Ref: */
+	for(i=0;i<numanalyses;i++){
+		memcpy(marshalled_dataset,&element_type_list[i],sizeof(element_type_list[i]));marshalled_dataset+=sizeof(element_type_list[i]);
+	}
+
+	/*Marshall hooks: */
+	for(i=0;i<numanalyses;i++){
+		if(hnodes[i]){
+			/*Set flag to 1 as there is a hook */
+			flaghook=1;
+			memcpy(marshalled_dataset,&flaghook,sizeof(flaghook));marshalled_dataset+=sizeof(flaghook);
+			hnodes[i]->Marshall(&marshalled_dataset);
+		}
+		else{
+			/*Set flag to 0 and do not marshall flag as there is no Hook */
+			flaghook=0;
+			memcpy(marshalled_dataset,&flaghook,sizeof(flaghook));marshalled_dataset+=sizeof(flaghook);
+		}
+	}
+	hmatice->Marshall(&marshalled_dataset);
+	hmatpar->Marshall(&marshalled_dataset);
+	hneighbors->Marshall(&marshalled_dataset);
+
+	/*Marshall inputs and results: */
+	marshalled_inputs_size=inputs->MarshallSize();
+	marshalled_inputs=inputs->Marshall();
+	memcpy(marshalled_dataset,marshalled_inputs,marshalled_inputs_size*sizeof(char));
+	marshalled_dataset+=marshalled_inputs_size;
+
+	marshalled_results_size=results->MarshallSize();
+	marshalled_results=results->Marshall();
+	memcpy(marshalled_dataset,marshalled_results,marshalled_results_size*sizeof(char));
+	marshalled_dataset+=marshalled_results_size;
+
+	/*parameters: don't do anything about it. parameters are marshalled somewhere else!*/
+
+	xfree((void**)&marshalled_inputs);
+	xfree((void**)&marshalled_results);
+
+	/*marshall horizontal neighbors: */
+	memcpy(marshalled_dataset,horizontalneighborsids,3*sizeof(int));marshalled_dataset+=3*sizeof(int);
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+/*FUNCTION Penta::MarshallSize {{{1*/
+int   Penta::MarshallSize(){
+
+	int i;
+	int hnodes_size=0;;
+
+	for(i=0;i<numanalyses;i++){
+		hnodes_size+=sizeof(int); //Flag 0 or 1
+		if (hnodes[i]) hnodes_size+=hnodes[i]->MarshallSize();
+	}
+
+	return sizeof(id)
+		+sizeof(sid)
+		+hnodes_size
+		+sizeof(numanalyses)
+		+numanalyses*sizeof(int) //element_type_lists
+		+hmatice->MarshallSize()
+		+hmatpar->MarshallSize()
+		+hneighbors->MarshallSize()
+		+inputs->MarshallSize()
+		+results->MarshallSize()
+		+3*sizeof(int)
+		+sizeof(int); //sizeof(int) for enum type
+}
+/*}}}*/
+/*FUNCTION Penta::Demarshall {{{1*/
+void  Penta::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+	int flaghook;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&sid,marshalled_dataset,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(&numanalyses,marshalled_dataset,sizeof(numanalyses));marshalled_dataset+=sizeof(numanalyses);
+
+	/*demarshall Ref: */
+	this->element_type_list=(int*)xmalloc(this->numanalyses*sizeof(int));
+	for(i=0;i<numanalyses;i++){ memcpy(&element_type_list[i],marshalled_dataset,sizeof(int));marshalled_dataset+=sizeof(int);}
+
+	/*allocate dynamic memory: */
+	this->hnodes=new Hook*[this->numanalyses];
+	/*demarshall hooks: */
+	for(i=0;i<numanalyses;i++){
+		memcpy(&flaghook,marshalled_dataset,sizeof(flaghook));marshalled_dataset+=sizeof(flaghook);
+		if(flaghook){ // there is a hook so demarshall it
+			hnodes[i]=new Hook();
+			hnodes[i]->Demarshall(&marshalled_dataset);
+		}
+		else hnodes[i]=NULL; //There is no hook so it is NULL
+	}
+	hmatice=new Hook(); hmatice->Demarshall(&marshalled_dataset);
+	hmatpar=new Hook(); hmatpar->Demarshall(&marshalled_dataset);
+	hneighbors=new Hook(); hneighbors->Demarshall(&marshalled_dataset);
+
+	/*pointers are garbage, until configuration is carried out: */
+	nodes=NULL;
+	matice=NULL;
+	matpar=NULL;
+	verticalneighbors=NULL;
+
+	/*demarshall inputs and results: */
+	inputs=(Inputs*)DataSetDemarshallRaw(&marshalled_dataset); 
+	results=(Results*)DataSetDemarshallRaw(&marshalled_dataset); 
+
+	/*parameters: may not exist even yet, so let Configure handle it: */
+	this->parameters=NULL;
+
+	/*neighbors: */
+	memcpy(&this->horizontalneighborsids,marshalled_dataset,3*sizeof(int));marshalled_dataset+=3*sizeof(int);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+
+/*Other*/
+/*FUNCTION Penta::AverageOntoPartition {{{1*/
+void  Penta::AverageOntoPartition(Vec partition_contributions,Vec partition_areas,double* vertex_response,double* qmu_part){
+	_error_("Not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Penta::BedNormal {{{1*/
+void Penta::BedNormal(double* bed_normal, double xyz_list[3][3]){
+
+	int i;
+	double v13[3],v23[3];
+	double normal[3];
+	double normal_norm;
+
+	for (i=0;i<3;i++){
+		v13[i]=xyz_list[0][i]-xyz_list[2][i];
+		v23[i]=xyz_list[1][i]-xyz_list[2][i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+	normal_norm=sqrt( pow(normal[0],2)+pow(normal[1],2)+pow(normal[2],2) );
+
+	/*Bed normal is opposite to surface normal*/
+	*(bed_normal)=-normal[0]/normal_norm;
+	*(bed_normal+1)=-normal[1]/normal_norm;
+	*(bed_normal+2)=-normal[2]/normal_norm;
+}
+/*}}}*/
+/*FUNCTION Penta::BasalFrictionCreateInput {{{1*/
+void Penta::BasalFrictionCreateInput(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int    count,ig;
+	double basalfriction[NUMVERTICES]={0,0,0,0,0,0};
+	double alpha2,vx,vy;
+	Friction*  friction=NULL;
+	GaussPenta* gauss=NULL;
+
+
+	/* Basal friction can only be found at the base of an ice sheet: */
+	if (!IsOnBed() || IsFloating()){
+		//empty friction: 
+		this->inputs->AddInput(new PentaP1Input(BasalFrictionEnum,&basalfriction[0]));
+		return;
+	}
+
+	/*Retrieve all inputs and parameters*/
+	Input* vx_input=inputs->GetInput(VxEnum);                         _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                         _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);                         _assert_(vz_input);
+
+
+	/*Build friction element, needed later: */
+	friction=new Friction("3d",inputs,matpar,DiagnosticHorizAnalysisEnum);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	count=0;
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		friction->GetAlpha2(&alpha2,gauss,VxEnum,VyEnum,VzEnum);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		basalfriction[count]=alpha2*(pow(vx,2.0)+pow(vy,2.0));
+		count++;
+	}
+	
+	/*Create PentaVertex input, which will hold the basal friction:*/
+	this->inputs->AddInput(new PentaP1Input(BasalFrictionEnum,&basalfriction[0]));
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+}
+/*}}}*/
+/*FUNCTION Penta::ComputeBasalStress {{{1*/
+void  Penta::ComputeBasalStress(Vec sigma_b){
+
+	int         i,j,ig;
+	int         dofv[3]={0,1,2};
+	int         dofp[1]={3};
+	int         analysis_type,approximation;
+	int         doflist[NUMVERTICES];
+	double      xyz_list[NUMVERTICES][3];
+	double      xyz_list_tria[3][3];
+	double      rho_ice,gravity,stokesreconditioning;
+	double      pressure,viscosity,bed,Jdet2d;
+	double      bed_normal[3];
+	double      basalforce[3];
+	double      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	double      devstresstensor[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	double      stresstensor[6]={0.0};
+	double      sigma_xx,sigma_yy,sigma_zz;
+	double      sigma_xy,sigma_xz,sigma_yz;
+	double      surface=0,value=0;
+	GaussPenta* gauss;
+
+	/*retrive parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*Check analysis_types*/
+	if (analysis_type!=DiagnosticHorizAnalysisEnum) _error_("Not supported yet!");
+	if (approximation!=StokesApproximationEnum) _error_("Not supported yet!");
+
+	/*retrieve some parameters: */
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	
+	if(!IsOnBed()){
+		//put zero
+		VecSetValue(sigma_b,id-1,0.0,INSERT_VALUES);
+		return;
+	}
+
+	/*recovre material parameters: */
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<3;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*Retrieve all inputs we will be needing: */
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
+	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);             _assert_(vz_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(0,1,2,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/*Compute strain rate viscosity and pressure: */
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		pressure_input->GetInputValue(&pressure,gauss);
+
+		/*Compute Stress*/
+		sigma_xx=2*viscosity*epsilon[0]-pressure*stokesreconditioning; // sigma = nu eps - pressure
+		sigma_yy=2*viscosity*epsilon[1]-pressure*stokesreconditioning;
+		sigma_zz=2*viscosity*epsilon[2]-pressure*stokesreconditioning;
+		sigma_xy=2*viscosity*epsilon[3];
+		sigma_xz=2*viscosity*epsilon[4];
+		sigma_yz=2*viscosity*epsilon[5];
+
+		/*Get normal vector to the bed */
+		BedNormal(&bed_normal[0],xyz_list_tria);
+
+		/*basalforce*/
+		basalforce[0] += sigma_xx*bed_normal[0] + sigma_xy*bed_normal[1] + sigma_xz*bed_normal[2];
+		basalforce[1] += sigma_xy*bed_normal[0] + sigma_yy*bed_normal[1] + sigma_yz*bed_normal[2];
+		basalforce[2] += sigma_xz*bed_normal[0] + sigma_yz*bed_normal[1] + sigma_zz*bed_normal[2];
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		value+=sigma_zz*Jdet2d*gauss->weight;
+		surface+=Jdet2d*gauss->weight;
+	}
+	value=value/surface;
+
+	/*Add value to output*/
+	VecSetValue(sigma_b,id-1,value,INSERT_VALUES);
+}
+/*}}}*/
+/*FUNCTION Penta::ComputeStrainRate {{{1*/
+void  Penta::ComputeStrainRate(Vec eps){
+
+	_error_("Not implemented yet");
+
+}
+/*}}}*/
+/*FUNCTION Penta::ComputeStressTensor {{{1*/
+void  Penta::ComputeStressTensor(){
+
+	int         iv;
+	double      xyz_list[NUMVERTICES][3];
+	double      pressure,viscosity;
+	double      epsilon[6]; /* epsilon=[exx,eyy,exy];*/
+	double      sigma_xx[NUMVERTICES];
+	double		sigma_yy[NUMVERTICES];
+	double		sigma_zz[NUMVERTICES];
+	double      sigma_xy[NUMVERTICES];
+	double		sigma_xz[NUMVERTICES];
+	double		sigma_yz[NUMVERTICES];
+	GaussPenta* gauss=NULL;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
+	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);             _assert_(vz_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/*Compute strain rate viscosity and pressure: */
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3d(&viscosity,&epsilon[0]);
+		pressure_input->GetInputValue(&pressure,gauss);
+
+		/*Compute Stress*/
+		sigma_xx[iv]=2*viscosity*epsilon[0]-pressure; // sigma = nu eps - pressure
+		sigma_yy[iv]=2*viscosity*epsilon[1]-pressure;
+		sigma_zz[iv]=2*viscosity*epsilon[2]-pressure;
+		sigma_xy[iv]=2*viscosity*epsilon[3];
+		sigma_xz[iv]=2*viscosity*epsilon[4];
+		sigma_yz[iv]=2*viscosity*epsilon[5];
+	}
+	
+	/*Add Stress tensor components into inputs*/
+	this->inputs->AddInput(new PentaP1Input(StressTensorxxEnum,&sigma_xx[0]));
+	this->inputs->AddInput(new PentaP1Input(StressTensorxyEnum,&sigma_xy[0]));
+	this->inputs->AddInput(new PentaP1Input(StressTensorxzEnum,&sigma_xz[0]));
+	this->inputs->AddInput(new PentaP1Input(StressTensoryyEnum,&sigma_yy[0]));
+	this->inputs->AddInput(new PentaP1Input(StressTensoryzEnum,&sigma_yz[0]));
+	this->inputs->AddInput(new PentaP1Input(StressTensorzzEnum,&sigma_zz[0]));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+		/*FUNCTION Penta::Configure {{{1*/
+void  Penta::Configure(Elements* elementsin, Loads* loadsin, DataSet* nodesin, Materials* materialsin, Parameters* parametersin){
+
+	int analysis_counter;
+	
+	/*go into parameters and get the analysis_counter: */
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	if (this->hnodes[analysis_counter]) this->hnodes[analysis_counter]->configure(nodesin);
+	this->hmatice->configure(materialsin);
+	this->hmatpar->configure(materialsin);
+	this->hneighbors->configure(elementsin);
+
+	/*Now, go pick up the objects inside the hooks: */
+	if (this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+	this->matice=(Matice*)this->hmatice->delivers();
+	this->matpar=(Matpar*)this->hmatpar->delivers();
+	this->verticalneighbors=(Penta**)this->hneighbors->deliverp();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+	/*get inputs configured too: */
+	this->inputs->Configure(parameters);
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrix {{{1*/
+void  Penta::CreateKMatrix(Mat Kff, Mat Kfs,Vec df){
+
+	/*retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	ElementVector* De=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging {{{2*/
+	_assert_(this->nodes && this->matice && this->matpar && this->verticalneighbors && this->parameters && this->inputs);
+	/*}}}*/
+	
+	/*Skip if water element*/
+	if(IsOnWater()) return;
+
+	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum: case AdjointHorizAnalysisEnum:
+			Ke=CreateKMatrixDiagnosticHoriz(); De=CreateDVectorDiagnosticHoriz();
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			Ke=CreateKMatrixDiagnosticHutter();
+			break;
+		case DiagnosticVertAnalysisEnum:
+			Ke=CreateKMatrixDiagnosticVert();
+			break;
+		#endif
+		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
+			Ke=CreateKMatrixSlope();
+			break;
+		case PrognosticAnalysisEnum:
+			Ke=CreateKMatrixPrognostic();
+			break;
+		#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixBalancethickness();
+			break;
+		#endif
+		#ifdef _HAVE_THERMAL_
+		case ThermalAnalysisEnum:
+			Ke=CreateKMatrixThermal();
+			break;
+		case EnthalpyAnalysisEnum:
+			Ke=CreateKMatrixEnthalpy();
+			break;
+		case MeltingAnalysisEnum:
+			Ke=CreateKMatrixMelting();
+			break;
+		#endif
+		default:
+			_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+	/*Add to global Vector*/
+	if(De){
+		De->InsertIntoGlobal(df);
+		delete De;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixPrognostic {{{1*/
+ElementMatrix* Penta::CreateKMatrixPrognostic(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixPrognostic();
+	delete tria->matice; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixSlope {{{1*/
+ElementMatrix* Penta::CreateKMatrixSlope(void){
+
+	if (!IsOnBed()) return NULL;
+
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixSlope();
+	delete tria->matice; delete tria;
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVector {{{1*/
+void  Penta::CreatePVector(Vec pf){
+
+	/*retrive parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*if debugging mode, check that all pointers exist {{{2*/
+	_assert_(this->nodes && this->matice && this->matpar && this->verticalneighbors && this->parameters && this->inputs);
+	/*}}}*/
+
+	/*Skip if water element*/
+	if(IsOnWater()) return;
+
+	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum:
+			pe=CreatePVectorDiagnosticHoriz();
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			pe=CreatePVectorDiagnosticHutter();
+			break;
+		case DiagnosticVertAnalysisEnum:
+			pe=CreatePVectorDiagnosticVert();
+			break;
+		#endif
+	 	#ifdef _HAVE_CONTROL_
+		case AdjointHorizAnalysisEnum:
+			pe=CreatePVectorAdjointHoriz();
+			break;
+		#endif
+		#ifdef _HAVE_THERMAL_
+		case ThermalAnalysisEnum:
+			pe=CreatePVectorThermal();
+			break;
+		case EnthalpyAnalysisEnum:
+			pe=CreatePVectorEnthalpy();
+			break;
+		case MeltingAnalysisEnum:
+			pe=CreatePVectorMelting();
+			break;
+		#endif
+		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
+			pe=CreatePVectorSlope();
+			break;
+		case PrognosticAnalysisEnum:
+			pe=CreatePVectorPrognostic();
+			break;
+		#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			pe=CreatePVectorBalancethickness();
+			break;
+		#endif
+		default:
+			_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+
+	/*Add to global Vector*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorPrognostic {{{1*/
+ElementVector* Penta::CreatePVectorPrognostic(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorPrognostic();
+	delete tria->matice; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorSlope {{{1*/
+ElementVector* Penta::CreatePVectorSlope(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorSlope();
+	delete tria->matice; delete tria;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::DeepEcho{{{1*/
+void Penta::DeepEcho(void){
+
+	int i;
+	
+	printf("Penta:\n");
+	printf("   id: %i\n",id);
+	nodes[0]->DeepEcho();
+	nodes[1]->DeepEcho();
+	nodes[2]->DeepEcho();
+	nodes[3]->DeepEcho();
+	nodes[4]->DeepEcho();
+	nodes[5]->DeepEcho();
+	matice->DeepEcho();
+	matpar->DeepEcho();
+	printf("   neighbor ids: %i-%i\n",verticalneighbors[0]->Id(),verticalneighbors[1]->Id());
+	printf("   parameters\n");
+	parameters->DeepEcho();
+	printf("   inputs\n");
+	inputs->DeepEcho();
+	printf("   results\n");
+	results->DeepEcho();
+	printf("neighboor sids: \n");
+	printf(" %i %i %i\n",horizontalneighborsids[0],horizontalneighborsids[1],horizontalneighborsids[2]);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Penta::DeleteResults {{{1*/
+void  Penta::DeleteResults(void){
+
+	/*Delete and reinitialize results*/
+	delete this->results;
+	this->results=new Results();
+
+}
+/*}}}*/
+/*FUNCTION Penta::Echo{{{1*/
+
+void Penta::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION Penta::ObjectEnum{{{1*/
+int Penta::ObjectEnum(void){
+
+	return PentaEnum;
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetBasalElement{{{1*/
+Penta* Penta::GetBasalElement(void){
+
+	/*Output*/
+	Penta* penta=NULL;
+
+	/*Go through all elements till the bed is reached*/
+	penta=this;
+	for(;;){
+		/*Stop if we have reached the surface, else, take lower penta*/
+		if (penta->IsOnBed()) break;
+
+		/* get lower Penta*/
+		penta=penta->GetLowerElement();
+		_assert_(penta->Id()!=this->id);
+	}
+
+	/*return output*/
+	return penta;
+}
+/*}}}*/
+/*FUNCTION Penta::GetDofList {{{1*/
+void  Penta::GetDofList(int** pdoflist,int approximation_enum,int setenum){
+
+	int  i,j,count=0;
+	int  numberofdofs=0;
+	int* doflist=NULL;
+
+	/*First, figure out size of doflist: */
+	for(i=0;i<6;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
+
+	/*Allocate: */
+	doflist=(int*)xmalloc(numberofdofs*sizeof(int));
+
+	/*Populate: */
+	count=0;
+	for(i=0;i<6;i++){
+		nodes[i]->GetDofList(doflist+count,approximation_enum,setenum);
+		count+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
+	}
+
+	/*Assign output pointers:*/
+	*pdoflist=doflist;
+}
+/*}}}*/
+/*FUNCTION Penta::GetDofList1 {{{1*/
+void  Penta::GetDofList1(int* doflist){
+
+	int i;
+	for(i=0;i<6;i++) doflist[i]=nodes[i]->GetDofList1();
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetConnectivityList {{{1*/
+void  Penta::GetConnectivityList(int* connectivity){
+	for(int i=0;i<NUMVERTICES;i++) connectivity[i]=nodes[i]->GetConnectivity();
+}
+/*}}}*/
+/*FUNCTION Penta::GetElementType {{{1*/
+int Penta::GetElementType(){
+
+	/*return PentaRef field*/
+	return this->element_type;
+}
+/*}}}*/
+/*FUNCTION Penta::GetElementSizes{{{1*/
+void Penta::GetElementSizes(double* hx,double* hy,double* hz){
+
+	double xyz_list[NUMVERTICES][3];
+	double xmin,ymin,zmin;
+	double xmax,ymax,zmax;
+
+	/*Get xyz list: */
+	GetVerticesCoordinates(&xyz_list[0][0],nodes,NUMVERTICES);
+	xmin=xyz_list[0][0]; xmax=xyz_list[0][0];
+	ymin=xyz_list[0][1]; ymax=xyz_list[0][1];
+	zmin=xyz_list[0][2]; zmax=xyz_list[0][2];
+
+	for(int i=1;i<NUMVERTICES;i++){
+		if(xyz_list[i][0]<xmin) xmin=xyz_list[i][0];
+		if(xyz_list[i][0]>xmax) xmax=xyz_list[i][0];
+		if(xyz_list[i][1]<ymin) ymin=xyz_list[i][1];
+		if(xyz_list[i][1]>ymax) ymax=xyz_list[i][1];
+		if(xyz_list[i][2]<zmin) zmin=xyz_list[i][2];
+		if(xyz_list[i][2]>zmax) zmax=xyz_list[i][2];
+	}
+
+	*hx=xmax-xmin;
+	*hy=ymax-ymin;
+	*hz=zmax-zmin;
+}
+/*}}}*/
+/*FUNCTION Penta::GetHorizontalNeighboorSids {{{1*/
+int* Penta::GetHorizontalNeighboorSids(){
+
+	/*return PentaRef field*/
+	return &this->horizontalneighborsids[0];
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetLowerElement{{{1*/
+Penta* Penta::GetLowerElement(void){
+
+	Penta* upper_penta=NULL;
+
+	upper_penta=(Penta*)verticalneighbors[0]; //first one (0) under, second one (1) above
+
+	return upper_penta;
+}
+/*}}}*/
+/*FUNCTION Penta::GetNodeIndex {{{1*/
+int Penta::GetNodeIndex(Node* node){
+
+	_assert_(nodes);
+	for(int i=0;i<NUMVERTICES;i++){
+		if(node==nodes[i])
+		 return i;
+	}
+	_error_("Node provided not found among element nodes");
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetInputListOnVertices(double* pvalue,int enumtype) {{{1*/
+void Penta::GetInputListOnVertices(double* pvalue,int enumtype){
+
+	/*Intermediaries*/
+	double     value[NUMVERTICES];
+	GaussPenta *gauss              = NULL;
+
+	/*Recover input*/
+	Input* input=inputs->GetInput(enumtype);
+	if (!input) _error_("Input %s not found in element",EnumToStringx(enumtype));
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+		input->GetInputValue(&pvalue[iv],gauss);
+	}
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::GetInputListOnVertices(double* pvalue,int enumtype,double defaultvalue) {{{1*/
+void Penta::GetInputListOnVertices(double* pvalue,int enumtype,double defaultvalue){
+
+	/*Intermediaries*/
+	double     value[NUMVERTICES];
+	GaussPenta *gauss              = NULL;
+
+	/*Recover input*/
+	Input* input=inputs->GetInput(enumtype);
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	if (input){
+		gauss=new GaussPenta();
+		for (int iv=0;iv<NUMVERTICES;iv++){
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&pvalue[iv],gauss);
+		}
+	}
+	else{
+		for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
+	}
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::GetInputValue(double* pvalue,Node* node,int enumtype) {{{1*/
+void Penta::GetInputValue(double* pvalue,Node* node,int enumtype){
+
+	Input* input=inputs->GetInput(enumtype);
+	if(!input) _error_("No input of type %s found in tria",EnumToStringx(enumtype));
+
+	GaussPenta* gauss=new GaussPenta();
+	gauss->GaussVertex(this->GetNodeIndex(node));
+
+	input->GetInputValue(pvalue,gauss);
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::GetPhi {{{1*/
+void Penta::GetPhi(double* phi, double*  epsilon, double viscosity){
+	/*Compute deformational heating from epsilon and viscosity */
+
+	double epsilon_matrix[3][3];
+	double epsilon_eff;
+	double epsilon_sqr[3][3];
+
+	/* Build epsilon matrix */
+	epsilon_matrix[0][0]=*(epsilon+0);
+	epsilon_matrix[1][0]=*(epsilon+3);
+	epsilon_matrix[2][0]=*(epsilon+4);
+	epsilon_matrix[0][1]=*(epsilon+3);
+	epsilon_matrix[1][1]=*(epsilon+1);
+	epsilon_matrix[2][1]=*(epsilon+5);
+	epsilon_matrix[0][2]=*(epsilon+4);
+	epsilon_matrix[1][2]=*(epsilon+5);
+	epsilon_matrix[2][2]=*(epsilon+2);
+
+	/* Effective value of epsilon_matrix */
+	epsilon_sqr[0][0]=pow(epsilon_matrix[0][0],2);
+	epsilon_sqr[1][0]=pow(epsilon_matrix[1][0],2);
+	epsilon_sqr[2][0]=pow(epsilon_matrix[2][0],2);
+	epsilon_sqr[0][1]=pow(epsilon_matrix[0][1],2);
+	epsilon_sqr[1][1]=pow(epsilon_matrix[1][1],2);
+	epsilon_sqr[2][1]=pow(epsilon_matrix[2][1],2);
+	epsilon_sqr[0][2]=pow(epsilon_matrix[0][2],2);
+	epsilon_sqr[1][2]=pow(epsilon_matrix[1][2],2);
+	epsilon_sqr[2][2]=pow(epsilon_matrix[2][2],2);
+	epsilon_eff=1/pow(2,0.5)*pow((epsilon_sqr[0][0]+epsilon_sqr[0][1]+ epsilon_sqr[0][2]+ epsilon_sqr[1][0]+ epsilon_sqr[1][1]+ epsilon_sqr[1][2]+ epsilon_sqr[2][0]+ epsilon_sqr[2][1]+ epsilon_sqr[2][2]),0.5);
+
+	/*Phi = Tr(sigma * eps) 
+	 *    = Tr(sigma'* eps)
+	 *    = 2 * eps_eff * sigma'_eff
+	 *    = 4 * mu * eps_eff ^2*/
+	*phi=4*pow(epsilon_eff,2.0)*viscosity;
+}
+/*}}}*/
+/*FUNCTION Penta::GetSidList{{{1*/
+void  Penta::GetSidList(int* sidlist){
+
+	int i;
+	for(i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->GetSidList();
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputs{{{1*/
+void  Penta::GetSolutionFromInputs(Vec solution){
+
+	int analysis_type;
+
+	/*retrive parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Just branch to the correct InputUpdateFromSolution generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+	#ifdef _HAVE_DIAGNOSTIC_
+	case DiagnosticHorizAnalysisEnum:
+		int approximation;
+		inputs->GetInputValue(&approximation,ApproximationEnum);
+		if(approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
+			GetSolutionFromInputsDiagnosticStokes(solution);
+		}
+		else if (approximation==MacAyealApproximationEnum || approximation==PattynApproximationEnum || approximation==HutterApproximationEnum){
+			GetSolutionFromInputsDiagnosticHoriz(solution);
+		}
+		else if (approximation==MacAyealPattynApproximationEnum || approximation==PattynStokesApproximationEnum || approximation==MacAyealStokesApproximationEnum){
+			return; //the elements around will create the solution
+		}
+		break;
+	case DiagnosticHutterAnalysisEnum:
+		GetSolutionFromInputsDiagnosticHutter(solution);
+		break;
+	case DiagnosticVertAnalysisEnum:
+		GetSolutionFromInputsDiagnosticVert(solution);
+		break;
+	#endif
+	#ifdef _HAVE_THERMAL_
+	case ThermalAnalysisEnum:
+		GetSolutionFromInputsThermal(solution);
+		break;
+	case EnthalpyAnalysisEnum:
+		GetSolutionFromInputsEnthalpy(solution);
+		break;
+	#endif
+	default:
+		_error_("analysis: %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::GetStabilizationParameter {{{1*/
+double Penta::GetStabilizationParameter(double u, double v, double w, double diameter, double rho_ice, double heatcapacity, double thermalconductivity){
+	/*Compute stabilization parameter*/
+
+	double normu;
+	double tau_parameter;
+
+	normu=pow(pow(u,2)+pow(v,2)+pow(w,2),0.5);
+	if(normu*diameter/(3*2*thermalconductivity/(rho_ice*heatcapacity))<1){
+		tau_parameter=pow(diameter,2)/(3*2*2*thermalconductivity/(rho_ice*heatcapacity));
+	}
+	else tau_parameter=diameter/(2*normu);
+
+	return tau_parameter;
+}
+/*}}}*/
+/*FUNCTION Penta::GetStrainRate3dPattyn{{{1*/
+void Penta::GetStrainRate3dPattyn(double* epsilon,double* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input){
+	/*Compute the 3d Blatter/PattynStrain Rate (5 components):
+	 *
+	 * epsilon=[exx eyy exy exz eyz]
+	 *
+	 * with exz=1/2 du/dz
+	 *      eyz=1/2 dv/dz
+	 *
+	 * the contribution of vz is neglected
+	 */
+
+	int i;
+	double epsilonvx[5];
+	double epsilonvy[5];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input){
+		_error_("Input missing. Here are the input pointers we have for vx: %p, vy: %p\n",vx_input,vy_input);
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetVxStrainRate3dPattyn(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate3dPattyn(epsilonvy,xyz_list,gauss);
+
+	/*Sum all contributions*/
+	for(i=0;i<5;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i];
+}
+/*}}}*/
+/*FUNCTION Penta::GetStrainRate3d{{{1*/
+void Penta::GetStrainRate3d(double* epsilon,double* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input, Input* vz_input){
+	/*Compute the 3d Strain Rate (6 components):
+	 *
+	 * epsilon=[exx eyy ezz exy exz eyz]
+	 */
+
+	int i;
+	double epsilonvx[6];
+	double epsilonvy[6];
+	double epsilonvz[6];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input || !vz_input){
+		_error_("Input missing. Here are the input pointers we have for vx: %p, vy: %p, vz: %p\n",vx_input,vy_input,vz_input);
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetVxStrainRate3d(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate3d(epsilonvy,xyz_list,gauss);
+	vz_input->GetVzStrainRate3d(epsilonvz,xyz_list,gauss);
+
+	/*Sum all contributions*/
+	for(i=0;i<6;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i]+epsilonvz[i];
+}
+/*}}}*/
+/*FUNCTION Penta::GetUpperElement{{{1*/
+Penta* Penta::GetUpperElement(void){
+
+	Penta* upper_penta=NULL;
+
+	upper_penta=(Penta*)verticalneighbors[1]; //first one under, second one above
+
+	return upper_penta;
+}
+/*}}}*/
+/*FUNCTION Penta::GetVectorFromInputs{{{1*/
+void  Penta::GetVectorFromInputs(Vec vector,int input_enum){
+
+	int doflist1[NUMVERTICES];
+
+	/*Get out if this is not an element input*/
+	if (!IsInput(input_enum)) return;
+
+	/*Prepare index list*/
+	this->GetDofList1(&doflist1[0]);
+
+	/*Get input (either in element or material)*/
+	Input* input=inputs->GetInput(input_enum);
+	if(!input) _error_("Input %s not found in element",EnumToStringx(input_enum));
+
+	/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
+	input->GetVectorFromInputs(vector,&doflist1[0]);
+}
+/*}}}*/
+/*FUNCTION Penta::GetVectorFromResults{{{1*/
+void  Penta::GetVectorFromResults(Vec vector,int offset,int interp){
+
+	/*Get result*/
+	ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(offset);
+	if(interp==P1Enum){
+		int doflist1[NUMVERTICES];
+		int connectivity[NUMVERTICES];
+		this->GetSidList(&doflist1[0]);
+		this->GetConnectivityList(&connectivity[0]);
+		elementresult->GetVectorFromResults(vector,&doflist1[0],&connectivity[0],NUMVERTICES);
+	}
+	else if(interp==P0Enum){
+		elementresult->GetElementVectorFromResults(vector,sid);
+	}
+	else{
+		printf("Interpolation %s not supported\n",EnumToStringx(interp));
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::GetZcoord {{{1*/
+double Penta::GetZcoord(GaussPenta* gauss){
+
+	int    i;
+	double z;
+	double xyz_list[NUMVERTICES][3];
+	double z_list[NUMVERTICES];
+
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES;i++) z_list[i]=xyz_list[i][2];
+	PentaRef::GetInputValue(&z,z_list,gauss);
+
+	return z;
+}
+/*}}}*/
+/*FUNCTION Penta::Sid {{{1*/
+int    Penta::Sid(){
+	
+	return sid;
+
+}
+/*}}}*/
+/*FUNCTION Penta::Id {{{1*/
+int    Penta::Id(void){
+	return id; 
+}
+/*}}}*/
+/*FUNCTION Penta::InputArtificialNoise{{{1*/
+void  Penta::InputArtificialNoise(int enum_type,double min,double max){
+
+	Input* input=NULL;
+
+	/*Make a copy of the original input: */
+	input=(Input*)this->inputs->GetInput(enum_type);
+	if(!input)_error_(" could not find old input with enum: %s",EnumToStringx(enum_type));
+
+	/*ArtificialNoise: */
+	input->ArtificialNoise(min,max);
+}
+/*}}}*/
+/*FUNCTION Penta::InputConvergence{{{1*/
+bool Penta::InputConvergence(double* eps, int* enums,int num_enums,int* criterionenums,double* criterionvalues,int num_criterionenums){
+
+	int i;
+	bool    converged=true;
+	Input** new_inputs=NULL;
+	Input** old_inputs=NULL;
+
+	new_inputs=(Input**)xmalloc(num_enums/2*sizeof(Input*)); //half the enums are for the new inputs
+	old_inputs=(Input**)xmalloc(num_enums/2*sizeof(Input*)); //half the enums are for the old inputs
+
+	for(i=0;i<num_enums/2;i++){
+		new_inputs[i]=(Input*)this->inputs->GetInput(enums[2*i+0]);
+		old_inputs[i]=(Input*)this->inputs->GetInput(enums[2*i+1]);
+		if(!new_inputs[i])_error_("%s%s"," could not find input with enum ",EnumToStringx(enums[2*i+0]));
+		if(!old_inputs[i])_error_("%s%s"," could not find input with enum ",EnumToStringx(enums[2*i+0]));
+	}
+
+	/*ok, we've got the inputs (new and old), now loop throught the number of criterions and fill the eps array:*/
+	for(i=0;i<num_criterionenums;i++){
+		IsInputConverged(eps+i,new_inputs,old_inputs,num_enums/2,criterionenums[i]);
+		if(eps[i]>criterionvalues[i]) converged=false; 
+	}
+
+	/*clean up*/
+	xfree((void**)&new_inputs);
+	xfree((void**)&old_inputs);
+
+	/*Return output*/
+	return converged;
+}
+/*}}}*/
+/*FUNCTION Penta::InputCreate(double scalar,int enum,int code);{{{1*/
+void Penta::InputCreate(double scalar,int name,int code){
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+	
+	if ((code==5) || (code==1)){ //boolean
+		this->inputs->AddInput(new BoolInput(name,(bool)scalar));
+	}
+	else if ((code==6) || (code==2)){ //integer
+		this->inputs->AddInput(new IntInput(name,(int)scalar));
+	}
+	else if ((code==7) || (code==3)){ //double
+		this->inputs->AddInput(new DoubleInput(name,(double)scalar));
+	}
+	else _error_("%s%i"," could not recognize nature of vector from code ",code);
+
+}
+/*}}}*/
+/*FUNCTION Penta::InputCreate(double* vector,int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){{{1*/
+void Penta::InputCreate(double* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){//index into elements
+
+	/*Intermediaries*/
+	int    i,j,t;
+	int    penta_vertex_ids[6];
+	int    row;
+	double nodeinputs[6];
+	double time;
+	TransientInput* transientinput=NULL;
+
+	int    numberofvertices;
+	int    numberofelements;
+	double yts;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+
+	/*Branch on type of vector: nodal or elementary: */
+	if(vector_type==1){ //nodal vector
+
+		/*Recover vertices ids needed to initialize inputs*/
+		for(i=0;i<6;i++){ 
+			penta_vertex_ids[i]=(int)iomodel->Data(MeshElementsEnum)[6*index+i]; //ids for vertices are in the elements array from Matlab
+		}
+
+		/*Are we in transient or static? */
+		if(M==numberofvertices){
+
+			/*create input values: */
+			for(i=0;i<6;i++)nodeinputs[i]=(double)vector[penta_vertex_ids[i]-1];
+
+			/*process units: */
+			UnitConversion(&nodeinputs[0], 6 ,ExtToIuEnum, vector_enum);
+
+			/*create static input: */
+			this->inputs->AddInput(new PentaP1Input(vector_enum,nodeinputs));
+		}
+		else if(M==numberofvertices+1){
+			/*create transient input: */
+			for(t=0;t<N;t++){ //N is the number of times
+
+				/*create input values: */
+				for(i=0;i<6;i++){
+					row=penta_vertex_ids[i]-1;
+					nodeinputs[i]=(double)vector[N*row+t];
+				}
+
+				/*process units: */
+				UnitConversion(&nodeinputs[0], 6 ,ExtToIuEnum, vector_enum);
+
+				/*time? :*/
+				time=(double)vector[(M-1)*N+t]*yts;
+
+				if(t==0)transientinput=new TransientInput(vector_enum);
+				transientinput->AddTimeInput(new PentaP1Input(vector_enum,nodeinputs),time);
+			}
+			this->inputs->AddInput(transientinput);
+		}
+		else _error_("nodal vector is either numberofnodes (%i), or numberofnodes+1 long. Field provided is %i long. Enum %s",numberofvertices,M,EnumToStringx(vector_enum));
+	}
+	else if(vector_type==2){ //element vector
+		/*Are we in transient or static? */
+		if(M==numberofelements){
+
+			/*static mode: create an input out of the element value: */
+
+			if (code==5){ //boolean
+				this->inputs->AddInput(new BoolInput(vector_enum,(bool)vector[index]));
+			}
+			else if (code==6){ //integer
+				this->inputs->AddInput(new IntInput(vector_enum,(int)vector[index]));
+			}
+			else if (code==7){ //double
+				this->inputs->AddInput(new DoubleInput(vector_enum,(double)vector[index]));
+			}
+			else _error_("%s%i"," could not recognize nature of vector from code ",code);
+		}
+		else {
+			_error_("transient elementary inputs not supported yet!");
+		}
+	}
+	else{
+		_error_("Cannot add input for vector type %i (not supported)",vector_type);
+	}
+
+}
+/*}}}*/
+/*FUNCTION Penta::InputDepthAverageAtBase{{{1*/
+void  Penta::InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum){
+
+	int  step,i;
+	double  xyz_list[NUMVERTICES][3];
+	double  Helem_list[NUMVERTICES];
+	double  zeros_list[NUMVERTICES]={0.0};
+	Penta* penta=NULL;
+	Input* original_input=NULL;
+	Input* element_integrated_input=NULL;
+	Input* total_integrated_input=NULL;
+	Input* element_thickness_input=NULL;
+	Input* total_thickness_input=NULL;
+	Input* depth_averaged_input=NULL;
+
+	/*recover parameters: */
+
+	/*Are we on the base? If not, return*/
+	if(!IsOnBed()) return;
+
+	/*OK, we are on bed. Initialize global inputs as 0*/
+	total_thickness_input =new PentaP1Input(ThicknessEnum,zeros_list);
+
+	/*Now follow all the upper element from the base to the surface to integrate the input*/
+	penta=this;
+	step =0;
+	for(;;){
+
+		/*Step1: Get original input (to be depth avegaged): */
+		if (object_enum==MeshElementsEnum)
+		 original_input=(Input*)penta->inputs->GetInput(enum_type);
+		else if (object_enum==MaterialsEnum)
+		 original_input=(Input*)penta->matice->inputs->GetInput(enum_type);
+		else
+		 _error_("object %s not supported yet",EnumToStringx(object_enum));
+		if(!original_input) _error_("could not find input with enum %s",EnumToStringx(enum_type));
+
+		/*If first time, initialize total_integrated_input*/
+		if (step==0){
+			if (original_input->ObjectEnum()==PentaP1InputEnum)
+			 total_integrated_input=new PentaP1Input(average_enum_type,zeros_list);
+			else if (original_input->ObjectEnum()==ControlInputEnum)
+			 total_integrated_input=new PentaP1Input(average_enum_type,zeros_list);
+			else if (original_input->ObjectEnum()==DoubleInputEnum)
+			 total_integrated_input=new DoubleInput(average_enum_type,0.0);
+			else
+			 _error_("object %s not supported yet",EnumToStringx(original_input->ObjectEnum()));
+		}
+
+		/*Step2: Create element thickness input*/
+		GetVerticesCoordinates(&xyz_list[0][0],penta->nodes,NUMVERTICES);
+		for(i=0;i<3;i++){
+			Helem_list[i]=xyz_list[i+3][2]-xyz_list[i][2];
+			Helem_list[i+3]=Helem_list[i];
+		}
+		element_thickness_input=new PentaP1Input(ThicknessEnum,Helem_list);
+
+		/*Step3: Vertically integrate A COPY of the original*/
+		element_integrated_input=(Input*)original_input->copy();
+		element_integrated_input->VerticallyIntegrate(element_thickness_input);
+
+		/*Add contributions to global inputs*/
+		total_integrated_input->AXPY(element_integrated_input,1.0);
+		total_thickness_input ->AXPY(element_thickness_input,1.0);
+
+		/*Clean up*/
+		delete element_thickness_input;
+		delete element_integrated_input;
+
+		/*Stop if we have reached the surface, else, take upper penta*/
+		if (penta->IsOnSurface()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetUpperElement();
+		_assert_(penta->Id()!=this->id);
+
+		/*increase couter*/
+		step++;
+	}
+
+	/*OK, now we only need to divide the depth integrated input by the total thickness!*/
+	depth_averaged_input=total_integrated_input->PointwiseDivide(total_thickness_input);
+	depth_averaged_input->ChangeEnum(average_enum_type);
+
+	/*Clean up*/
+	delete total_thickness_input;
+	delete total_integrated_input;
+
+	/*Finally, add to inputs*/
+	if (object_enum==MeshElementsEnum)
+	 this->inputs->AddInput((Input*)depth_averaged_input);
+	else if (object_enum==MaterialsEnum)
+	 this->matice->inputs->AddInput((Input*)depth_averaged_input);
+	else
+	 _error_("object %s not supported yet",EnumToStringx(object_enum));
+}
+/*}}}*/
+/*FUNCTION Penta::InputDuplicate{{{1*/
+void  Penta::InputDuplicate(int original_enum,int new_enum){
+
+	/*Call inputs method*/
+	if (IsInput(original_enum)) inputs->DuplicateInput(original_enum,new_enum);
+
+}
+/*}}}*/
+/*FUNCTION Penta::InputExtrude {{{1*/
+void  Penta::InputExtrude(int enum_type,int object_type){
+
+	int     i,num_inputs;
+	Penta  *penta       = NULL;
+	Input  *copy        = NULL;
+	Input **base_inputs = NULL;
+
+	/*Are we on the base, not on the surface?:*/
+	if(!IsOnBed()) return;
+
+	/*Step1: Get and Extrude original input: */
+	if (object_type==ElementEnum){
+		num_inputs=1;
+		base_inputs=(Input**)xmalloc(num_inputs*sizeof(Input*));
+		base_inputs[0]=(Input*)this->inputs->GetInput(enum_type);
+	}
+	else if (object_type==MaterialsEnum){
+		num_inputs=1;
+		base_inputs=(Input**)xmalloc(num_inputs*sizeof(Input*));
+		base_inputs[0]=(Input*)matice->inputs->GetInput(enum_type);
+	}
+	else if (object_type==NodeEnum){
+		num_inputs=3; //only the three upper nodes
+		base_inputs=(Input**)xmalloc(num_inputs*sizeof(Input*));
+		for(i=0;i<num_inputs;i++){
+			base_inputs[i]=(Input*)this->nodes[i]->inputs->GetInput(enum_type);
+		}
+	}
+	else{
+		_error_("object of type %s not supported yet",EnumToStringx(object_type));
+	}
+	for(i=0;i<num_inputs;i++){
+		if(!base_inputs[i]) _error_("could not find input with enum %s in object %s",EnumToStringx(enum_type),EnumToStringx(object_type));
+		base_inputs[i]->Extrude();
+	}
+
+	/*Stop if there is only one layer of element*/
+	if (this->IsOnSurface()) return;
+
+	/*Step 2: this input has been extruded for this element, now follow the upper element*/
+	penta=this;
+	for(;;){
+		/* get upper Penta*/
+		penta=penta->GetUpperElement();
+		_assert_(penta->Id()!=this->id);
+
+		/*Add input of the basal element to penta->inputs*/
+		for(i=0;i<num_inputs;i++){
+			copy=(Input*)base_inputs[i]->copy();
+			if (object_type==ElementEnum){
+				penta->inputs->AddInput((Input*)copy);
+			}
+			else if(object_type==MaterialsEnum){
+				penta->matice->inputs->AddInput((Input*)copy);
+			}
+			else if(object_type==NodeEnum){
+				penta->nodes[i+3]->inputs->AddInput((Input*)copy); //change only the three upper nodes
+			}
+			else{
+				_error_("object of type %s not supported yet",EnumToStringx(object_type));
+			}
+		}
+
+		/*Stop if we have reached the surface*/
+		if (penta->IsOnSurface()) break;
+	}
+
+	/*clean-up and return*/
+	xfree((void**)&base_inputs);
+}
+/*}}}*/
+/*FUNCTION Penta::InputScale{{{1*/
+void  Penta::InputScale(int enum_type,double 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: %s",EnumToStringx(enum_type));
+
+	/*Scale: */
+	input->Scale(scale_factor);
+}
+/*}}}*/
+/*FUNCTION Penta::InputToResult{{{1*/
+void  Penta::InputToResult(int enum_type,int step,double time){
+
+	int    i;
+	bool   found = false;
+	Input *input = NULL;
+
+	/*Go through all the input objects, and find the one corresponding to enum_type, if it exists: */
+	if (enum_type==MaterialsRheologyBbarEnum) input=this->matice->inputs->GetInput(MaterialsRheologyBEnum);
+	else input=this->inputs->GetInput(enum_type);
+	//if (!input) _error_("Input %s not found in penta->inputs",EnumToStringx(enum_type)); why error out? if the requested input does not exist, we should still 
+	//try and output whatever we can instead of just failing.
+	if(!input)return;
+
+	/*If we don't find it, no big deal, just don't do the transfer. Otherwise, build a new Result 
+	 * object out of the input, with the additional step and time information: */
+	this->results->AddObject((Object*)input->SpawnResult(step,time));
+	#ifdef _HAVE_CONTROL_
+	if(input->ObjectEnum()==ControlInputEnum) this->results->AddObject((Object*)((ControlInput*)input)->SpawnGradient(step,time));
+	#endif
+
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromConstant(bool value, int name);{{{1*/
+void  Penta::InputUpdateFromConstant(bool constant, int name){
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new BoolInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromConstant(double value, int name);{{{1*/
+void  Penta::InputUpdateFromConstant(double constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new DoubleInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromConstant(int value, int name);{{{1*/
+void  Penta::InputUpdateFromConstant(int constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new IntInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromIoModel {{{1*/
+void Penta::InputUpdateFromIoModel(int index,IoModel* iomodel){ 
+
+	/*Intermediaries*/
+	IssmInt i,j;
+	int     penta_vertex_ids[6];
+	double  nodeinputs[6];
+	double  cmmininputs[6];
+	double  cmmaxinputs[6];
+
+	double  yts;
+	bool    control_analysis;
+	int     num_control_type;
+	int     num_cm_responses;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
+	if(control_analysis) iomodel->Constant(&num_cm_responses,InversionNumCostFunctionsEnum);
+
+	/*Checks if debuging*/
+	/*{{{2*/
+	_assert_(iomodel->Data(MeshElementsEnum));
+	/*}}}*/
+
+	/*Recover vertices ids needed to initialize inputs*/
+	for(i=0;i<6;i++){ 
+		penta_vertex_ids[i]=(int)iomodel->Data(MeshElementsEnum)[6*index+i]; //ids for vertices are in the elements array from Matlab
+	}
+
+	/*Control Inputs*/
+	#ifdef _HAVE_CONTROL_
+	if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+		for(i=0;i<num_control_type;i++){
+			switch((int)iomodel->Data(InversionControlParametersEnum)[i]){
+				case BalancethicknessThickeningRateEnum:
+					if (iomodel->Data(BalancethicknessThickeningRateEnum)){
+						for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(BalancethicknessThickeningRateEnum)[penta_vertex_ids[j]-1]/yts;
+						for(j=0;j<6;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<6;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case VxEnum:
+					if (iomodel->Data(VxEnum)){
+						for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(VxEnum)[penta_vertex_ids[j]-1]/yts;
+						for(j=0;j<6;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<6;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(VxEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case VyEnum:
+					if (iomodel->Data(VyEnum)){
+						for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(VyEnum)[penta_vertex_ids[j]-1]/yts;
+						for(j=0;j<6;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<6;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(VyEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case FrictionCoefficientEnum:
+					if (iomodel->Data(FrictionCoefficientEnum)){
+						for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(FrictionCoefficientEnum)[penta_vertex_ids[j]-1];
+						for(j=0;j<6;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<6;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case MaterialsRheologyBbarEnum:
+					/*Matice will take care of it*/ break;
+				default:
+					_error_("Control %s not implemented yet",EnumToStringx((int)iomodel->Data(InversionControlParametersEnum)[i]));
+			}
+		}
+	}
+	#endif
+
+	//Need to know the type of approximation for this element
+	if(iomodel->Data(FlowequationElementEquationEnum)){
+		if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==MacAyealApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,MacAyealApproximationEnum));
+		}
+		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==PattynApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,PattynApproximationEnum));
+		}
+		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==MacAyealPattynApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,MacAyealPattynApproximationEnum));
+		}
+		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==HutterApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,HutterApproximationEnum));
+		}
+		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==StokesApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,StokesApproximationEnum));
+		}
+		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==MacAyealStokesApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,MacAyealStokesApproximationEnum));
+		}
+		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==PattynStokesApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,PattynStokesApproximationEnum));
+		}
+		else if (*(iomodel->Data(FlowequationElementEquationEnum)+index)==NoneApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,NoneApproximationEnum));
+		}
+		else{
+			_error_("Approximation type %s not supported yet",EnumToStringx((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_cm_responses;i++){
+			for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(InversionCostFunctionsCoefficientsEnum)[(penta_vertex_ids[j]-1)*num_cm_responses+i];
+			datasetinput->inputs->AddObject(new PentaP1Input(InversionCostFunctionsCoefficientsEnum,nodeinputs));
+		}
+
+		/*Add datasetinput to element inputs*/
+		this->inputs->AddInput(datasetinput);
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolution {{{1*/
+void  Penta::InputUpdateFromSolution(double* solution){
+
+	int analysis_type;
+
+	/*retreive parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Just branch to the correct InputUpdateFromSolution generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+	#ifdef _HAVE_DIAGNOSTIC_
+	case DiagnosticHorizAnalysisEnum:
+		InputUpdateFromSolutionDiagnosticHoriz( solution);
+		break;
+	case DiagnosticHutterAnalysisEnum:
+		InputUpdateFromSolutionDiagnosticHutter( solution);
+		break;
+	case DiagnosticVertAnalysisEnum:
+		InputUpdateFromSolutionDiagnosticVert( solution);
+		break;
+	#endif
+	#ifdef _HAVE_CONTROL_
+	case AdjointHorizAnalysisEnum:
+		int approximation;
+		inputs->GetInputValue(&approximation,ApproximationEnum);
+		if(approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
+			InputUpdateFromSolutionAdjointStokes( solution);
+		}
+		else{
+			InputUpdateFromSolutionAdjointHoriz( solution);
+		}
+		break;
+	#endif
+	#ifdef _HAVE_THERMAL_
+	case ThermalAnalysisEnum:
+		InputUpdateFromSolutionThermal( solution);
+		break;
+	case EnthalpyAnalysisEnum:
+		InputUpdateFromSolutionEnthalpy( solution);
+		break;
+	case MeltingAnalysisEnum:
+		InputUpdateFromSolutionOneDof(solution,BasalforcingsMeltingRateEnum);
+		break;
+	#endif
+	case BedSlopeXAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,BedSlopeXEnum);
+		break;
+	case BedSlopeYAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,BedSlopeYEnum);
+		break;
+	case SurfaceSlopeXAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,SurfaceSlopeXEnum);
+		break;
+	case SurfaceSlopeYAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,SurfaceSlopeYEnum);
+		break;
+	case PrognosticAnalysisEnum:
+		InputUpdateFromSolutionPrognostic(solution);
+		break;
+	#ifdef _HAVE_BALANCED_
+	case BalancethicknessAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,ThicknessEnum);
+		break;
+	#endif
+	default: 
+		_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionPrognostic{{{1*/
+void  Penta::InputUpdateFromSolutionPrognostic(double* solution){
+
+	const int  numdof   = NDOF1*NUMVERTICES;
+	const int  numdof2d = NDOF1*NUMVERTICES2D;
+
+	int    i,hydroadjustment;
+	int*   doflist = NULL;
+	double rho_ice,rho_water,minthickness;
+	double newthickness[numdof];
+	double newbed[numdof];
+	double newsurface[numdof];
+	double oldbed[NUMVERTICES];
+	double oldsurface[NUMVERTICES];
+	double oldthickness[NUMVERTICES];
+	Penta  *penta   = NULL;
+
+	/*If not on bed, return*/
+	if (!IsOnBed()) return;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector and extrude it */
+	this->parameters->FindParam(&minthickness,PrognosticMinThicknessEnum);
+	for(i=0;i<numdof2d;i++){
+		newthickness[i]=solution[doflist[i]];
+		if(isnan(newthickness[i])) _error_("NaN found in solution vector");
+		/*Constrain thickness to be at least 1m*/
+		if(newthickness[i]<minthickness) newthickness[i]=minthickness;
+		newthickness[i+numdof2d]=newthickness[i];
+	}
+
+	/*Get previous bed, thickness and surface*/
+	GetInputListOnVertices(&oldbed[0],BedEnum);
+	GetInputListOnVertices(&oldsurface[0],SurfaceEnum);
+	GetInputListOnVertices(&oldthickness[0],ThicknessEnum);
+
+	/*Fing PrognosticHydrostaticAdjustment to figure out how to update the geometry:*/
+	this->parameters->FindParam(&hydroadjustment,PrognosticHydrostaticAdjustmentEnum);
+
+	/*recover material parameters: */
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	for(i=0;i<numdof;i++) {
+		/*If shelf: hydrostatic equilibrium*/
+		if (this->nodes[i]->IsGrounded()){
+			newsurface[i]=oldbed[i]+newthickness[i]; //surface = oldbed + newthickness
+			newbed[i]=oldbed[i];               //same bed: do nothing
+		}
+		else{ //so it is an ice shelf
+			if(hydroadjustment==AbsoluteEnum){
+				newsurface[i]=newthickness[i]*(1-rho_ice/rho_water);
+				newbed[i]=newthickness[i]*(-rho_ice/rho_water);
+			}
+			else if(hydroadjustment==IncrementalEnum){
+				newsurface[i]=oldsurface[i]+(1.0-rho_ice/rho_water)*(newthickness[i]-oldthickness[i]); //surface = oldsurface + (1-di) * dH 
+				newbed[i]=oldbed[i]-rho_ice/rho_water*(newthickness[i]-oldthickness[i]); //bed = oldbed + di * dH
+			}
+			else _error_("Hydrostatic adjustment %i (%s) not supported yet",hydroadjustment,EnumToStringx(hydroadjustment));
+		}
+	}
+
+	/*Start looping over all elements above current element and update all inputs*/
+	penta=this;
+	for(;;){
+		/*Add input to the element: */
+		penta->inputs->AddInput(new PentaP1Input(ThicknessEnum,newthickness));
+		penta->inputs->AddInput(new PentaP1Input(SurfaceEnum,newsurface));
+		penta->inputs->AddInput(new PentaP1Input(BedEnum,newbed));
+
+		/*Stop if we have reached the surface*/
+		if (penta->IsOnSurface()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
+	}
+	
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionOneDof{{{1*/
+void  Penta::InputUpdateFromSolutionOneDof(double* solution,int enum_type){
+
+	const int numdof = NDOF1*NUMVERTICES;
+
+	double values[numdof];
+	int*   doflist=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+		if(isnan(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new PentaP1Input(enum_type,values));
+	
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionOneDofCollpased{{{1*/
+void  Penta::InputUpdateFromSolutionOneDofCollapsed(double* solution,int enum_type){
+
+	const int  numdof   = NDOF1*NUMVERTICES;
+	const int  numdof2d = NDOF1*NUMVERTICES2D;
+
+	double  values[numdof];
+	int*    doflist = NULL;
+	Penta  *penta   = NULL;
+
+	/*If not on bed, return*/
+	if (!IsOnBed()) return;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector and extrude it */
+	for(int i=0;i<numdof2d;i++){
+		values[i]         =solution[doflist[i]];
+		values[i+numdof2d]=values[i];
+		if(isnan(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Start looping over all elements above current element and update all inputs*/
+	penta=this;
+	for(;;){
+		/*Add input to the element: */
+		penta->inputs->AddInput(new PentaP1Input(enum_type,values));
+
+		/*Stop if we have reached the surface*/
+		if (penta->IsOnSurface()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
+	}
+	
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromVector(double* vector, int name, int type);{{{1*/
+void  Penta::InputUpdateFromVector(double* vector, int name, int type){
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*Penta update B in InputUpdateFromSolutionThermal, so don't look for B update here.*/
+
+	switch(type){
+
+		case VertexEnum:
+
+			/*New PentaVertexInpu*/
+			double values[6];
+
+			/*Get values on the 6 vertices*/
+			for (int i=0;i<6;i++){
+				values[i]=vector[this->nodes[i]->GetVertexDof()];
+			}
+
+			/*update input*/
+			this->inputs->AddInput(new PentaP1Input(name,values));
+			return;
+
+		default:
+
+			_error_("type %i (%s) not implemented yet",type,EnumToStringx(type));
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromVector(int* vector, int name, int type);{{{1*/
+void  Penta::InputUpdateFromVector(int* vector, int name, int type){
+	_error_(" not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromVector(bool* vector, int name, int type);{{{1*/
+void  Penta::InputUpdateFromVector(bool* vector, int name, int type){
+	_error_(" not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Penta::IsOnBed{{{1*/
+bool Penta::IsOnBed(void){
+
+	bool onbed;
+	inputs->GetInputValue(&onbed,MeshElementonbedEnum);
+	return onbed;
+}
+/*}}}*/
+/*FUNCTION Penta::IsInput{{{1*/
+bool Penta::IsInput(int name){
+	if (
+				name==ThicknessEnum ||
+				name==SurfaceEnum ||
+				name==BedEnum ||
+				name==SurfaceSlopeXEnum ||
+				name==SurfaceSlopeYEnum ||
+				name==SurfaceforcingsMassBalanceEnum ||
+				name==BasalforcingsMeltingRateEnum ||
+				name==BasalforcingsGeothermalfluxEnum ||
+				name==SurfaceAreaEnum||
+				name==PressureEnum ||
+				name==VxEnum ||
+				name==VyEnum ||
+				name==VzEnum ||
+				name==VxMeshEnum ||
+				name==VyMeshEnum ||
+				name==VzMeshEnum ||
+				name==InversionVxObsEnum ||
+				name==InversionVyObsEnum ||
+				name==InversionVzObsEnum ||
+				name==TemperatureEnum ||
+				name==EnthalpyEnum ||
+				name==EnthalpyPicardEnum ||
+				name==WaterfractionEnum||
+				name==FrictionCoefficientEnum ||
+				name==GradientEnum ||
+				name==OldGradientEnum  ||
+				name==ConvergedEnum || 
+				name==QmuVxEnum ||
+				name==QmuVyEnum ||
+				name==QmuPressureEnum ||
+				name==QmuBedEnum ||
+				name==QmuThicknessEnum ||
+				name==QmuSurfaceEnum ||
+				name==QmuTemperatureEnum ||
+				name==QmuMeltingEnum
+				) {
+		return true;
+	}
+	else return false;
+}
+/*}}}*/
+/*FUNCTION Penta::IsFloating{{{1*/
+bool   Penta::IsFloating(){
+
+	bool onshelf;
+	inputs->GetInputValue(&onshelf,MaskElementonfloatingiceEnum);
+	return onshelf;
+}
+/*}}}*/
+/*FUNCTION Penta::IsNodeOnShelf {{{1*/
+bool   Penta::IsNodeOnShelf(){
+
+	int  i;
+	bool shelf=false;
+
+	for(i=0;i<6;i++){
+		if (nodes[i]->IsFloating()){
+			shelf=true;
+			break;
+		}
+	}
+	return shelf;
+}
+/*}}}*/
+/*FUNCTION Penta::IsNodeOnShelfFromFlags {{{1*/
+bool   Penta::IsNodeOnShelfFromFlags(double* flags){
+
+	int  i;
+	bool shelf=false;
+
+	for(i=0;i<NUMVERTICES;i++){
+		if (flags[nodes[i]->Sid()]){
+			shelf=true;
+			break;
+		}
+	}
+	return shelf;
+}
+/*}}}*/
+/*FUNCTION Penta::IsOnSurface{{{1*/
+bool Penta::IsOnSurface(void){
+
+	bool onsurface;
+	inputs->GetInputValue(&onsurface,MeshElementonsurfaceEnum);
+	return onsurface;
+}
+/*}}}*/
+/*FUNCTION Penta::IsOnWater {{{1*/
+bool   Penta::IsOnWater(){
+
+	bool onwater;
+	inputs->GetInputValue(&onwater,MaskElementonwaterEnum);
+	return onwater;
+}
+/*}}}*/
+/*FUNCTION Penta::ListResultsInfo{{{*/
+void Penta::ListResultsInfo(int** in_resultsenums,int** in_resultssizes,double** in_resultstimes,int** in_resultssteps,int* in_num_results){
+
+	/*Intermediaries*/
+	int     i;
+	int     numberofresults = 0;
+	int     *resultsenums   = NULL;
+	int     *resultssizes   = NULL;
+	double  *resultstimes   = NULL;
+	int     *resultssteps   = NULL;
+
+	/*Checks*/
+	_assert_(in_num_results);
+
+	/*Count number of results*/
+	for(i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+		numberofresults++;
+	}
+
+	if(numberofresults){
+
+		/*Allocate output*/
+		resultsenums=(int*)xmalloc(numberofresults*sizeof(int));
+		resultssizes=(int*)xmalloc(numberofresults*sizeof(int));
+		resultstimes=(double*)xmalloc(numberofresults*sizeof(double));
+		resultssteps=(int*)xmalloc(numberofresults*sizeof(int));
+
+		/*populate enums*/
+		for(i=0;i<this->results->Size();i++){
+			ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+			resultsenums[i]=elementresult->InstanceEnum();
+			resultstimes[i]=elementresult->GetTime();
+			resultssteps[i]=elementresult->GetStep();
+			if(elementresult->ObjectEnum()==PentaP1ElementResultEnum){
+				resultssizes[i]=P1Enum;
+			}
+			else{
+				resultssizes[i]=P0Enum;
+			}
+		}
+	}
+
+	/*Assign output pointers:*/
+	*in_num_results=numberofresults;
+	*in_resultsenums=resultsenums;
+	*in_resultssizes=resultssizes;
+	*in_resultstimes=resultstimes;
+	*in_resultssteps=resultssteps;
+
+}/*}}}*/
+/*FUNCTION Penta::MigrateGroundingLine{{{1*/
+void  Penta::MigrateGroundingLine(double* old_floating_ice,double* sheet_ungrounding){
+
+	int     i,migration_style,unground;
+	bool    elementonshelf = false;
+	double  bed_hydro,yts,gl_melting_rate;
+	double  rho_water,rho_ice,density;
+	double  melting[NUMVERTICES];
+	double  h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],ba[NUMVERTICES];
+
+	if(!IsOnBed()) return;
+
+	/*Recover info at the vertices: */
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	parameters->FindParam(&yts,ConstantsYtsEnum);
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&s[0],SurfaceEnum);
+	GetInputListOnVertices(&b[0],BedEnum);
+	GetInputListOnVertices(&ba[0],BathymetryEnum);
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	density=rho_ice/rho_water;
+	
+	/*go through vertices, and update inputs, considering them to be PentaVertex type: */
+	for(i=0;i<NUMVERTICES;i++){
+		/*Ice shelf: if bed below bathymetry, impose it at the bathymetry and update surface, elso do nothing */
+		if(old_floating_ice[nodes[i]->Sid()]){
+			if(b[i]<=ba[i]){ 
+				b[i]=ba[i];
+				s[i]=b[i]+h[i];
+				nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,false));
+				nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,true));
+			}
+		}
+		/*Ice sheet: if hydrostatic bed above bathymetry, ice sheet starts to unground, elso do nothing */
+		/*Change only if AgressiveMigration or if the ice sheet is in contact with the ocean*/
+		else{
+			bed_hydro=-density*h[i];
+			if (bed_hydro>ba[i]){
+				/*Unground only if the element is connected to the ice shelf*/
+				if(migration_style==AgressiveMigrationEnum){
+					s[i]=(1-density)*h[i];
+					b[i]=-density*h[i];
+					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,true));
+					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,false));
+				}
+				else if(migration_style==SoftMigrationEnum && sheet_ungrounding[nodes[i]->Sid()]){
+					s[i]=(1-density)*h[i];
+					b[i]=-density*h[i];
+					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,true));
+					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,false));
+				}
+			}
+		}
+	}
+
+	/*If at least one vertex is now floating, the element is now floating*/
+	for(i=0;i<NUMVERTICES;i++){
+		if(nodes[i]->IsFloating()){
+			elementonshelf=true;
+			break;
+		}
+	}
+	
+   /*Add basal melting rate if element just ungrounded*/
+	if(!this->IsFloating() && elementonshelf==true){
+		for(i=0;i<NUMVERTICES;i++)melting[i]=gl_melting_rate/yts;
+		this->inputs->AddInput(new PentaP1Input(BasalforcingsMeltingRateEnum,&melting[0]));
+	} 
+
+	/*Update inputs*/
+	this->inputs->AddInput(new PentaP1Input(SurfaceEnum,&s[0]));
+	this->inputs->AddInput(new PentaP1Input(BedEnum,&b[0]));
+   this->inputs->AddInput(new BoolInput(MaskElementonfloatingiceEnum,elementonshelf));
+
+	/*Extrude inputs*/
+	this->InputExtrude(SurfaceEnum,ElementEnum);
+	this->InputExtrude(BedEnum,ElementEnum);
+	this->InputExtrude(MaskElementonfloatingiceEnum,ElementEnum);
+	this->InputExtrude(MaskVertexonfloatingiceEnum,NodeEnum);
+	this->InputExtrude(MaskVertexongroundediceEnum,NodeEnum);
+}
+/*}}}*/
+/*FUNCTION Penta::MinEdgeLength{{{1*/
+double Penta::MinEdgeLength(double xyz_list[6][3]){
+	/*Return the minimum lenght of the nine egdes of the penta*/
+
+	int    i,node0,node1;
+	int    edges[9][2]={{0,1},{0,2},{1,2},{3,4},{3,5},{4,5},{0,3},{1,4},{2,5}}; //list of the nine edges
+	double length;
+	double minlength=-1;
+
+	for(i=0;i<9;i++){
+		/*Find the two nodes for this edge*/
+		node0=edges[i][0];
+		node1=edges[i][1];
+
+		/*Compute the length of this edge and compare it to the minimal length*/
+		length=pow(pow(xyz_list[node0][0]-xyz_list[node1][0],2.0)+pow(xyz_list[node0][1]-xyz_list[node1][1],2.0)+pow(xyz_list[node0][2]-xyz_list[node1][2],2.0),0.5);
+		if(length<minlength || minlength<0) minlength=length;
+	}
+
+	return minlength;
+}
+/*}}}*/
+/*FUNCTION Penta::MyRank {{{1*/
+int    Penta::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION Penta::PatchFill{{{1*/
+void  Penta::PatchFill(int* pcount, Patch* patch){
+
+	int i,count;
+	int vertices_ids[6];
+
+	/*recover pointer: */
+	count=*pcount;
+		
+	/*will be needed later: */
+	for(i=0;i<6;i++) vertices_ids[i]=nodes[i]->GetVertexId(); //vertices id start at column 3 of the patch.
+
+	for(i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+
+		/*For this result,fill the information in the Patch object (element id + vertices ids), and then hand 
+		 *it to the result object, to fill the rest: */
+		patch->fillelementinfo(count,this->sid+1,vertices_ids,6);
+		elementresult->PatchFill(count,patch);
+
+		/*increment counter: */
+		count++;
+	}
+
+	/*Assign output pointers:*/
+	*pcount=count;
+}/*}}}*/
+/*FUNCTION Penta::PatchSize{{{1*/
+void  Penta::PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes){
+
+	int     i;
+	int     numrows       = 0;
+	int     numnodes      = 0;
+	int     temp_numnodes = 0;
+
+	/*Go through all the results objects, and update the counters: */
+	for (i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+		/*first, we have one more result: */
+		numrows++;
+		/*now, how many vertices and how many nodal values for this result? :*/
+		temp_numnodes=elementresult->NumberOfNodalValues(); //ask result object.
+		if(temp_numnodes>numnodes)numnodes=temp_numnodes;
+	}
+
+	/*Assign output pointers:*/
+	*pnumrows=numrows;
+	*pnumvertices=NUMVERTICES;
+	*pnumnodes=numnodes;
+}
+/*}}}*/
+/*FUNCTION Penta::PotentialSheetUngrounding{{{1*/
+void  Penta::PotentialSheetUngrounding(Vec potential_sheet_ungrounding){
+
+	int     i;
+	double  h[NUMVERTICES],ba[NUMVERTICES];
+	double  bed_hydro;
+	double  rho_water,rho_ice,density;
+	bool    elementonshelf = false;
+
+	/*material parameters: */
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	density=rho_ice/rho_water;
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&ba[0],BathymetryEnum);
+
+	/*go through vertices, and figure out which ones are on the ice sheet, and want to unground: */
+	for(i=0;i<NUMVERTICES;i++){
+		/*Find if grounded vertices want to start floating*/
+		if (!nodes[i]->IsFloating()){
+			bed_hydro=-density*h[i];
+			if (bed_hydro>ba[i]){
+				/*Vertex that could potentially unground, flag it*/
+				VecSetValue(potential_sheet_ungrounding,nodes[i]->Sid(),1,INSERT_VALUES);
+			}
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::ProcessResultsUnits{{{1*/
+void  Penta::ProcessResultsUnits(void){
+
+	int i;
+
+	for(i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+		elementresult->ProcessUnits(this->parameters);
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::ReduceMatrixStokes {{{1*/
+void Penta::ReduceMatrixStokes(double* Ke_reduced, double* Ke_temp){
+
+	int    i,j;
+	double Kii[24][24];
+	double Kib[24][3];
+	double Kbb[3][3];
+	double Kbi[3][24];
+	double Kbbinv[3][3];
+	double Kright[24][24];
+
+	/*Create the four matrices used for reduction */
+	for(i=0;i<24;i++){
+		for(j=0;j<24;j++){
+			Kii[i][j]=*(Ke_temp+27*i+j);
+		}
+		for(j=0;j<3;j++){
+			Kib[i][j]=*(Ke_temp+27*i+j+24);
+		}
+	}
+	for(i=0;i<3;i++){
+		for(j=0;j<24;j++){
+			Kbi[i][j]=*(Ke_temp+27*(i+24)+j);
+		}
+		for(j=0;j<3;j++){
+			Kbb[i][j]=*(Ke_temp+27*(i+24)+j+24);
+		}
+	}
+
+	/*Inverse the matrix corresponding to bubble part Kbb */
+	Matrix3x3Invert(&Kbbinv[0][0], &Kbb[0][0]);
+
+	/*Multiply matrices to create the reduce matrix Ke_reduced */
+	TripleMultiply(&Kib[0][0],24,3,0,
+				&Kbbinv[0][0],3,3,0,
+				&Kbi[0][0],3,24,0,
+				&Kright[0][0],0);
+
+	/*Affect value to the reduced matrix */
+	for(i=0;i<24;i++) for(j=0;j<24;j++) *(Ke_reduced+24*i+j)=Kii[i][j]-Kright[i][j];
+}
+/*}}}*/
+/*FUNCTION Penta::ReduceVectorStokes {{{1*/
+void Penta::ReduceVectorStokes(double* Pe_reduced, double* Ke_temp, double* Pe_temp){
+
+	int    i,j;
+	double Pi[24];
+	double Pb[3];
+	double Kbb[3][3];
+	double Kib[24][3];
+	double Kbbinv[3][3];
+	double Pright[24];
+
+	/*Create the four matrices used for reduction */
+	for(i=0;i<24;i++) Pi[i]=*(Pe_temp+i);
+	for(i=0;i<3;i++) Pb[i]=*(Pe_temp+i+24);
+	for(j=0;j<3;j++){
+		for(i=0;i<24;i++){
+			Kib[i][j]=*(Ke_temp+3*i+j);
+		}
+		for(i=0;i<3;i++){
+			Kbb[i][j]=*(Ke_temp+3*(i+24)+j);
+		}
+	}
+
+	/*Inverse the matrix corresponding to bubble part Kbb */
+	Matrix3x3Invert(&Kbbinv[0][0], &Kbb[0][0]);
+
+	/*Multiply matrices to create the reduce matrix Ke_reduced */
+	TripleMultiply(&Kib[0][0],24,3,0,
+				&Kbbinv[0][0],3,3,0,
+				&Pb[0],3,1,0,&Pright[0],0);
+
+	/*Affect value to the reduced matrix */
+	for(i=0;i<24;i++) *(Pe_reduced+i)=Pi[i]-Pright[i];
+}
+/*}}}*/
+/*FUNCTION Penta::RequestedOutput{{{1*/
+void Penta::RequestedOutput(int output_enum,int step,double time){
+			
+	if(IsInput(output_enum)){
+		/*just transfer this input to results, and we are done: */
+		InputToResult(output_enum,step,time);
+	}
+	else{
+		/*this input does not exist, compute it, and then transfer to results: */
+		switch(output_enum){
+			case BasalFrictionEnum:
+
+				/*create input: */
+				BasalFrictionCreateInput();
+
+				/*transfer to results :*/
+				InputToResult(output_enum,step,time);
+
+				/*erase input: */
+				inputs->DeleteInput(output_enum);
+				break;
+			case ViscousHeatingEnum:
+
+				/*create input: */
+				ViscousHeatingCreateInput();
+
+				/*transfer to results :*/
+				InputToResult(output_enum,step,time);
+
+				/*erase input: */
+				inputs->DeleteInput(output_enum);
+				break;
+
+			case StressTensorEnum: 
+				this->ComputeStressTensor();
+				InputToResult(StressTensorxxEnum,step,time);
+				InputToResult(StressTensorxyEnum,step,time);
+				InputToResult(StressTensorxzEnum,step,time);
+				InputToResult(StressTensoryyEnum,step,time);
+				InputToResult(StressTensoryzEnum,step,time);
+				InputToResult(StressTensorzzEnum,step,time);
+				break;
+
+			default:
+				/*do nothing, no need to derail the computation because one of the outputs requested cannot be found: */
+				break;
+		}
+	}
+
+}
+/*}}}*/
+/*FUNCTION Penta::ResetCoordinateSystem{{{1*/
+void  Penta::ResetCoordinateSystem(void){
+
+	int    approximation;
+	double slopex[NUMVERTICES];
+	double slopey[NUMVERTICES];
+	double xz_plane[6];
+
+	/*For Stokes only: we want the CS to be tangential to the bedrock*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(IsFloating() || !IsOnBed() || (approximation!=StokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum &&  approximation!=PattynStokesApproximationEnum)) return;
+
+	/*Get slope on each node*/
+	GetInputListOnVertices(&slopex[0],BedSlopeXEnum);
+	GetInputListOnVertices(&slopey[0],BedSlopeYEnum);
+
+	/*Loop over basal nodes (first 3) and update their CS*/
+	for(int i=0;i<NUMVERTICES2D;i++){
+
+		/*New X axis             New Z axis*/
+		xz_plane[0]=1.;          xz_plane[3]=-slopex[i];  
+		xz_plane[1]=0.;          xz_plane[4]=-slopey[i];  
+		xz_plane[2]=slopex[i];   xz_plane[5]=1.;          
+
+		XZvectorsToCoordinateSystem(&this->nodes[i]->coord_system[0][0],&xz_plane[0]);
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SetClone {{{1*/
+void  Penta::SetClone(int* minranks){
+
+	_error_("not implemented yet");
+}
+/*}}}1*/
+/*FUNCTION Penta::SetCurrentConfiguration {{{1*/
+void  Penta::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, DataSet* nodesin, Materials* materialsin, Parameters* parametersin){
+
+	int analysis_counter;
+
+	/*go into parameters and get the analysis_counter: */
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Pick up nodes */
+	if (this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+}
+/*}}}*/
+/*FUNCTION Penta::SpawnTria {{{1*/
+Tria*  Penta::SpawnTria(int g0, int g1, int g2){
+
+	int   i,analysis_counter;
+	int   indices[3];
+	int   zero=0;
+	Tria*       tria            = NULL;
+	Inputs*     tria_inputs     = NULL;
+	Results*    tria_results    = NULL;
+	Parameters* tria_parameters = NULL;
+
+	/*go into parameters and get the analysis_counter: */
+	this->parameters->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	indices[0]=g0;
+	indices[1]=g1;
+	indices[2]=g2;
+
+	tria_parameters=this->parameters;
+	tria_inputs=(Inputs*)this->inputs->SpawnTriaInputs(indices);
+	tria_results=(Results*)this->results->SpawnTriaResults(indices);
+
+	tria=new Tria();
+	tria->id=this->id;
+	tria->inputs=tria_inputs;
+	tria->results=tria_results;
+	tria->parameters=tria_parameters;
+	tria->element_type=P1Enum; //Only P1 CG for now (TO BE CHANGED)
+	this->SpawnTriaHook(dynamic_cast<TriaHook*>(tria),&indices[0]);
+
+	/*Spawn matice*/
+	tria->matice=NULL;
+	tria->matice=(Matice*)this->matice->copy();
+	delete tria->matice->inputs;
+	tria->matice->inputs=(Inputs*)this->matice->inputs->SpawnTriaInputs(indices);
+
+	/*recover nodes, matice and matpar: */
+	tria->nodes=(Node**)tria->hnodes[analysis_counter]->deliverp();
+	tria->matpar=(Matpar*)tria->hmatpar->delivers();
+
+	return tria;
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceArea {{{1*/
+double Penta::SurfaceArea(void){
+
+	int    approximation;
+	double S;
+	Tria*  tria=NULL;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/*Bail out if this element if:
+	 * -> Non MacAyeal not on the surface
+	 * -> MacAyeal (2d model) and not on bed) */
+	if ((approximation!=MacAyealApproximationEnum && !IsOnSurface()) || (approximation==MacAyealApproximationEnum && !IsOnBed())){
+		return 0;
+	}
+	else if (approximation==MacAyealApproximationEnum){
+
+		/*This element should be collapsed into a tria element at its base. Create this tria element, 
+		 * and compute SurfaceArea*/
+		tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+		S=tria->SurfaceArea();
+		delete tria->matice; delete tria;
+		return S;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		S=tria->SurfaceArea();
+		delete tria->matice; delete tria;
+		return S;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceNormal {{{1*/
+void Penta::SurfaceNormal(double* surface_normal, double xyz_list[3][3]){
+
+	int    i;
+	double v13[3],v23[3];
+	double normal[3];
+	double normal_norm;
+
+	for (i=0;i<3;i++){
+		v13[i]=xyz_list[0][i]-xyz_list[2][i];
+		v23[i]=xyz_list[1][i]-xyz_list[2][i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+
+	normal_norm=sqrt( pow(normal[0],2)+pow(normal[1],2)+pow(normal[2],2) );
+
+	*(surface_normal)=normal[0]/normal_norm;
+	*(surface_normal+1)=normal[1]/normal_norm;
+	*(surface_normal+2)=normal[2]/normal_norm;
+}
+/*}}}*/
+/*FUNCTION Penta::TimeAdapt{{{1*/
+double  Penta::TimeAdapt(void){
+
+	int    i;
+	double C,dx,dy,dz,dt;
+	double maxabsvx,maxabsvy,maxabsvz;
+	double maxx,minx,maxy,miny,maxz,minz;
+	double xyz_list[NUMVERTICES][3];
+
+	/*get CFL coefficient:*/
+	this->parameters->FindParam(&C,TimesteppingCflCoefficientEnum);
+
+	/*Get for Vx and Vy, the max of abs value: */
+	this->MaxAbsVx(&maxabsvx,false);
+	this->MaxAbsVy(&maxabsvy,false);
+	this->MaxAbsVz(&maxabsvz,false);
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], this->nodes, NUMVERTICES);
+
+	minx=xyz_list[0][0];
+	maxx=xyz_list[0][0];
+	miny=xyz_list[0][1];
+	maxy=xyz_list[0][1];
+	minz=xyz_list[0][2];
+	maxz=xyz_list[0][2];
+	
+	for(i=1;i<NUMVERTICES;i++){
+		if (xyz_list[i][0]<minx)minx=xyz_list[i][0];
+		if (xyz_list[i][0]>maxx)maxx=xyz_list[i][0];
+		if (xyz_list[i][1]<miny)miny=xyz_list[i][1];
+		if (xyz_list[i][1]>maxy)maxy=xyz_list[i][1];
+		if (xyz_list[i][2]<minz)minz=xyz_list[i][2];
+		if (xyz_list[i][2]>maxz)maxz=xyz_list[i][2];
+	}
+	dx=maxx-minx;
+	dy=maxy-miny;
+	dz=maxz-minz;
+
+	/*CFL criterion: */
+	dt=C/(maxabsvy/dx+maxabsvy/dy+maxabsvz/dz);
+
+	return dt;
+}
+/*FUNCTION Penta::Update(int index,IoModel* iomodel,int analysis_counter,int analysis_type) {{{1*/
+void Penta::Update(int index,IoModel* iomodel,int analysis_counter,int analysis_type){ 
+
+	/*Intermediaries*/
+	IssmInt i,j;
+	int     penta_type;
+	int     penta_node_ids[6];
+	int     penta_vertex_ids[6];
+	double  nodeinputs[6];
+	double  yts;
+	int     stabilization;
+	bool    dakota_analysis;
+	bool    isstokes;
+	double  beta,heatcapacity,referencetemperature,meltingpoint,latentheat;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&stabilization,PrognosticStabilizationEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
+	iomodel->Constant(&beta,MaterialsBetaEnum);
+	iomodel->Constant(&heatcapacity,MaterialsHeatcapacityEnum);
+	iomodel->Constant(&referencetemperature,ConstantsReferencetemperatureEnum);
+	iomodel->Constant(&meltingpoint,MaterialsMeltingpointEnum);
+	iomodel->Constant(&latentheat,MaterialsLatentheatEnum);
+
+	/*Checks if debuging*/
+	/*{{{2*/
+	_assert_(iomodel->Data(MeshElementsEnum));
+	/*}}}*/
+
+	/*Recover element type*/
+	if ((analysis_type==PrognosticAnalysisEnum || analysis_type==BalancethicknessAnalysisEnum) && stabilization==3){
+		/*P1 Discontinuous Galerkin*/
+		penta_type=P1DGEnum;
+	}
+	else{
+		/*P1 Continuous Galerkin*/
+		penta_type=P1Enum;
+	}
+	this->SetElementType(penta_type,analysis_counter);
+
+	/*Recover vertices ids needed to initialize inputs*/
+	for(i=0;i<6;i++) penta_vertex_ids[i]=(int)iomodel->Data(MeshElementsEnum)[6*index+i]; //ids for vertices are in the elements array from Matlab
+
+	/*Recover nodes ids needed to initialize the node hook.*/
+	for(i=0;i<6;i++){ 
+		//go recover node ids, needed to initialize the node hook.
+		//WARNING: We assume P1 elements here!!!!!
+		penta_node_ids[i]=iomodel->nodecounter+(int)iomodel->Data(MeshElementsEnum)[6*index+i]; //ids for vertices are in the elements array from Matlab
+	}
+
+	/*hooks: */
+	this->SetHookNodes(penta_node_ids,analysis_counter); this->nodes=NULL; //set hook to nodes, for this analysis type
+
+	/*Fill with IoModel*/
+	this->InputUpdateFromIoModel(index,iomodel);
+
+	/*Defaults if not provided in iomodel*/
+	switch(analysis_type){
+
+		case DiagnosticHorizAnalysisEnum:
+
+			/*default vx,vy and vz: either observation or 0 */
+			if(!iomodel->Data(VxEnum)){
+				for(i=0;i<6;i++)nodeinputs[i]=0;
+				this->inputs->AddInput(new PentaP1Input(VxEnum,nodeinputs));
+				if(dakota_analysis) this->inputs->AddInput(new PentaP1Input(QmuVxEnum,nodeinputs));
+			}
+			if(!iomodel->Data(VyEnum)){
+				for(i=0;i<6;i++)nodeinputs[i]=0;
+				this->inputs->AddInput(new PentaP1Input(VyEnum,nodeinputs));
+				if(dakota_analysis) this->inputs->AddInput(new PentaP1Input(QmuVyEnum,nodeinputs));
+			}
+			if(!iomodel->Data(VzEnum)){
+				for(i=0;i<6;i++)nodeinputs[i]=0;
+				this->inputs->AddInput(new PentaP1Input(VzEnum,nodeinputs));
+				if(dakota_analysis) this->inputs->AddInput(new PentaP1Input(QmuVzEnum,nodeinputs));
+			}
+			if(!iomodel->Data(PressureEnum)){
+				for(i=0;i<6;i++)nodeinputs[i]=0;
+				if(dakota_analysis){
+					this->inputs->AddInput(new PentaP1Input(PressureEnum,nodeinputs));
+					this->inputs->AddInput(new PentaP1Input(QmuPressureEnum,nodeinputs));
+				}
+				if(isstokes){
+					this->inputs->AddInput(new PentaP1Input(PressureEnum,nodeinputs));
+					this->inputs->AddInput(new PentaP1Input(PressurePicardEnum,nodeinputs));
+				}
+			}
+			if(*(iomodel->Data(FlowequationElementEquationEnum)+index)==PattynStokesApproximationEnum){
+				/*Create VzPattyn and VzStokes Enums*/
+				if(iomodel->Data(VzEnum) && iomodel->Data(FlowequationBorderstokesEnum)){
+					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]/yts*iomodel->Data(FlowequationBorderstokesEnum)[penta_vertex_ids[i]-1];
+					this->inputs->AddInput(new PentaP1Input(VzStokesEnum,nodeinputs));
+					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]/yts*(1-iomodel->Data(FlowequationBorderstokesEnum)[penta_vertex_ids[i]-1]);
+					this->inputs->AddInput(new PentaP1Input(VzPattynEnum,nodeinputs));
+				}
+				else{
+					for(i=0;i<6;i++)nodeinputs[i]=0;
+					this->inputs->AddInput(new PentaP1Input(VzStokesEnum,nodeinputs));
+					this->inputs->AddInput(new PentaP1Input(VzPattynEnum,nodeinputs));
+				}
+			}
+			if(*(iomodel->Data(FlowequationElementEquationEnum)+index)==MacAyealStokesApproximationEnum){
+				/*Create VzMacAyeal and VzStokes Enums*/
+				if(iomodel->Data(VzEnum) && iomodel->Data(FlowequationBorderstokesEnum)){
+					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]/yts*iomodel->Data(FlowequationBorderstokesEnum)[penta_vertex_ids[i]-1];
+					this->inputs->AddInput(new PentaP1Input(VzStokesEnum,nodeinputs));
+					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]/yts*(1-iomodel->Data(FlowequationBorderstokesEnum)[penta_vertex_ids[i]-1]);
+					this->inputs->AddInput(new PentaP1Input(VzMacAyealEnum,nodeinputs));
+				}
+				else{
+					for(i=0;i<6;i++)nodeinputs[i]=0;
+					this->inputs->AddInput(new PentaP1Input(VzStokesEnum,nodeinputs));
+					this->inputs->AddInput(new PentaP1Input(VzMacAyealEnum,nodeinputs));
+				}
+			}
+			break;
+
+		case ThermalAnalysisEnum:
+			/*Initialize mesh velocity*/
+			for(i=0;i<6;i++)nodeinputs[i]=0;
+			this->inputs->AddInput(new PentaP1Input(VxMeshEnum,nodeinputs));
+			this->inputs->AddInput(new PentaP1Input(VyMeshEnum,nodeinputs));
+			this->inputs->AddInput(new PentaP1Input(VzMeshEnum,nodeinputs));
+			break;
+
+		case EnthalpyAnalysisEnum:
+			/*Initialize mesh velocity*/
+			for(i=0;i<6;i++)nodeinputs[i]=0;
+			this->inputs->AddInput(new PentaP1Input(VxMeshEnum,nodeinputs));
+			this->inputs->AddInput(new PentaP1Input(VyMeshEnum,nodeinputs));
+			this->inputs->AddInput(new PentaP1Input(VzMeshEnum,nodeinputs));
+			if (iomodel->Data(TemperatureEnum) && iomodel->Data(WaterfractionEnum) && iomodel->Data(PressureEnum)) {
+				for(i=0;i<6;i++){
+					if(iomodel->Data(TemperatureEnum)[penta_vertex_ids[i]-1] < meltingpoint-beta*iomodel->Data(PressureEnum)[penta_vertex_ids[i]-1]){
+						nodeinputs[i]=heatcapacity*(iomodel->Data(TemperatureEnum)[penta_vertex_ids[i]-1]-referencetemperature);
+					}
+					else nodeinputs[i]=heatcapacity*
+					 (meltingpoint-beta*iomodel->Data(PressureEnum)[penta_vertex_ids[i]-1]-referencetemperature)
+						+latentheat*iomodel->Data(WaterfractionEnum)[penta_vertex_ids[i]-1];
+				}
+				this->inputs->AddInput(new PentaP1Input(EnthalpyEnum,nodeinputs));
+			}
+			else _error_("temperature and waterfraction required for the enthalpy solution");
+			break;
+
+		default:
+			/*No update for other solution types*/
+			break;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::UpdatePotentialSheetUngrounding{{{1*/
+int Penta::UpdatePotentialSheetUngrounding(double* vertices_potentially_ungrounding,Vec vec_nodes_on_iceshelf,double* nodes_on_iceshelf){
+
+	int i;
+	int nflipped=0;
+
+	/*Go through nodes, and whoever is on the potential_sheet_ungrounding, ends up in nodes_on_iceshelf: */
+	for(i=0;i<NUMVERTICES;i++){
+		if (vertices_potentially_ungrounding[nodes[i]->Sid()]){
+			VecSetValue(vec_nodes_on_iceshelf,nodes[i]->Sid(),1,INSERT_VALUES);
+		
+			/*If node was not on ice shelf, we flipped*/
+			if(nodes_on_iceshelf[nodes[i]->Sid()]==0){
+				nflipped++;
+			}
+		}
+	}
+	return nflipped;
+}
+/*}}}*/
+/*FUNCTION Penta::ViscousHeatingCreateInput {{{1*/
+void Penta::ViscousHeatingCreateInput(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries*/
+	int    iv;
+	double phi;
+	double viscosity;
+	double xyz_list[NUMVERTICES][3];
+	double epsilon[6];
+	double     viscousheating[NUMVERTICES]={0,0,0,0,0,0};
+	double     thickness;
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum); _assert_(vz_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/*loop over vertices: */
+	gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+		
+		thickness_input->GetInputValue(&thickness,gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		GetPhi(&phi, &epsilon[0], viscosity);
+		
+
+		viscousheating[iv]=phi*thickness;
+	}
+
+	/*Create PentaVertex input, which will hold the basal friction:*/
+	this->inputs->AddInput(new PentaP1Input(ViscousHeatingEnum,&viscousheating[0]));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::SmearFunction {{{1*/
+void  Penta::SmearFunction(Vec smearedvector,double (*WeightFunction)(double distance,double radius),double radius){
+	_error_("not implemented yet");
+}
+/*}}}1*/
+
+#ifdef _HAVE_RESPONSES_
+/*FUNCTION Penta::IceVolume {{{1*/
+double Penta::IceVolume(void){
+
+	/*The volume of a troncated prism is base * 1/3 sum(length of edges)*/
+	double base,height;
+	double xyz_list[NUMVERTICES][3];
+
+	if(IsOnWater())return 0;
+
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Pentangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2.*fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average height*/
+	height = 1./3.*((xyz_list[3][2]-xyz_list[0][2])+(xyz_list[4][2]-xyz_list[1][2])+(xyz_list[5][2]-xyz_list[2][2]));
+
+	/*Return: */
+	return base*height;
+}
+/*}}}*/
+/*FUNCTION Penta::NodalValue {{{1*/
+int    Penta::NodalValue(double* pvalue, int index, int natureofdataenum,bool process_units){
+
+	int i;
+	int found=0;
+	double value;
+	Input* data=NULL;
+	GaussPenta* gauss=NULL;
+
+	/*First, serarch the input: */
+	data=inputs->GetInput(natureofdataenum); 
+
+	/*figure out if we have the vertex id: */
+	found=0;
+	for(i=0;i<NUMVERTICES;i++){
+		if(index==nodes[i]->GetVertexId()){
+			/*Do we have natureofdataenum in our inputs? :*/
+			if(data){
+				/*ok, we are good. retrieve value of input at vertex :*/
+				gauss=new GaussPenta(); gauss->GaussVertex(i);
+				data->GetInputValue(&value,gauss);
+				found=1;
+				break;
+			}
+		}
+	}
+
+	if(found)*pvalue=value;
+	return found;
+}
+/*}}}*/
+/*FUNCTION Penta::MinVel{{{1*/
+void  Penta::MinVel(double* pminvel, bool process_units){
+
+	/*Get minimum:*/
+	double minvel=this->inputs->Min(VelEnum);
+
+	/*process units if requested: */
+	if(process_units) minvel=UnitConversion(minvel,IuToExtEnum,VelEnum);
+
+	/*Assign output pointers:*/
+	*pminvel=minvel;
+}
+/*}}}*/
+/*FUNCTION Penta::MinVx{{{1*/
+void  Penta::MinVx(double* pminvx, bool process_units){
+
+	/*Get minimum:*/
+	double minvx=this->inputs->Min(VxEnum);
+
+	/*process units if requested: */
+	if(process_units) minvx=UnitConversion(minvx,IuToExtEnum,VxEnum);
+
+	/*Assign output pointers:*/
+	*pminvx=minvx;
+}
+/*}}}*/
+/*FUNCTION Penta::MinVy{{{1*/
+void  Penta::MinVy(double* pminvy, bool process_units){
+
+	/*Get minimum:*/
+	double minvy=this->inputs->Min(VyEnum);
+
+	/*process units if requested: */
+	if(process_units) minvy=UnitConversion(minvy,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pminvy=minvy;
+}
+/*}}}*/
+/*FUNCTION Penta::MinVz{{{1*/
+void  Penta::MinVz(double* pminvz, bool process_units){
+
+	/*Get minimum:*/
+	double minvz=this->inputs->Min(VzEnum);
+
+	/*process units if requested: */
+	if(process_units) minvz=UnitConversion(minvz,IuToExtEnum,VzEnum);
+
+	/*Assign output pointers:*/
+	*pminvz=minvz;
+}
+/*}}}*/
+/*FUNCTION Penta::MassFlux {{{1*/
+double Penta::MassFlux( double* segment,bool process_units){
+
+	double mass_flux=0;
+
+	if(!IsOnBed()) return mass_flux;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Spawn Tria element from the base of the Penta: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	mass_flux=tria->MassFlux(segment,process_units);
+	delete tria->matice; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return mass_flux;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxAbsVx{{{1*/
+void  Penta::MaxAbsVx(double* pmaxabsvx, bool process_units){
+
+	/*Get maximum:*/
+	double maxabsvx=this->inputs->MaxAbs(VxEnum);
+
+	/*process units if requested: */
+	if(process_units) maxabsvx=UnitConversion(maxabsvx,IuToExtEnum,VxEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvx=maxabsvx;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxAbsVy{{{1*/
+void  Penta::MaxAbsVy(double* pmaxabsvy, bool process_units){
+
+	/*Get maximum:*/
+	double maxabsvy=this->inputs->MaxAbs(VyEnum);
+
+	/*process units if requested: */
+	if(process_units) maxabsvy=UnitConversion(maxabsvy,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvy=maxabsvy;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxAbsVz{{{1*/
+void  Penta::MaxAbsVz(double* pmaxabsvz, bool process_units){
+
+	/*Get maximum:*/
+	double maxabsvz=this->inputs->MaxAbs(VzEnum);
+
+	/*process units if requested: */
+	if(process_units) maxabsvz=UnitConversion(maxabsvz,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvz=maxabsvz;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxVel{{{1*/
+void  Penta::MaxVel(double* pmaxvel, bool process_units){
+
+	/*Get maximum:*/
+	double maxvel=this->inputs->Max(VelEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvel=UnitConversion(maxvel,IuToExtEnum,VelEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvel=maxvel;
+
+}
+/*}}}*/
+/*FUNCTION Penta::MaxVx{{{1*/
+void  Penta::MaxVx(double* pmaxvx, bool process_units){
+
+	/*Get maximum:*/
+	double maxvx=this->inputs->Max(VxEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvx=UnitConversion(maxvx,IuToExtEnum,VxEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvx=maxvx;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxVy{{{1*/
+void  Penta::MaxVy(double* pmaxvy, bool process_units){
+
+	/*Get maximum:*/
+	double maxvy=this->inputs->Max(VyEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvy=UnitConversion(maxvy,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvy=maxvy;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxVz{{{1*/
+void  Penta::MaxVz(double* pmaxvz, bool process_units){
+
+	/*Get maximum:*/
+	double maxvz=this->inputs->Max(VzEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvz=UnitConversion(maxvz,IuToExtEnum,VzEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvz=maxvz;
+}
+/*}}}*/
+/*FUNCTION Penta::ElementResponse{{{1*/
+void Penta::ElementResponse(double* presponse,int response_enum,bool process_units){
+
+	switch(response_enum){
+		case MaterialsRheologyBbarEnum:
+			*presponse=this->matice->GetBbar();
+			break;
+		case VelEnum:
+
+			/*Get input:*/
+			double vel;
+			Input* vel_input;
+
+			vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
+			vel_input->GetInputAverage(&vel);
+
+			/*process units if requested: */
+			if(process_units) vel=UnitConversion(vel,IuToExtEnum,VelEnum);
+
+			/*Assign output pointers:*/
+			*presponse=vel;
+		default:  
+			_error_("Response type %s not supported yet!",EnumToStringx(response_enum));
+	}
+
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_THERMAL_
+/*FUNCTION Penta::CreateKMatrixEnthalpy {{{1*/
+ElementMatrix* Penta::CreateKMatrixEnthalpy(void){
+	
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixEnthalpyVolume();
+	ElementMatrix* Ke2=CreateKMatrixEnthalpyShelf();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+	
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixEnthalpyVolume {{{1*/
+ElementMatrix* Penta::CreateKMatrixEnthalpyVolume(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        stabilization;
+	int        i,j,ig,found=0;
+	double     Jdet,u,v,w,um,vm,wm;
+	double     h,hx,hy,hz,vx,vy,vz,vel;
+	double     gravity,rho_ice,rho_water;
+	double     epsvel=2.220446049250313e-16;
+	double     heatcapacity,thermalconductivity,dt;
+	double     pressure,enthalpy;
+	double     latentheat,kappa;
+	double     tau_parameter,diameter;
+	double     xyz_list[NUMVERTICES][3];
+	double     B_conduct[3][numdof];
+	double     B_advec[3][numdof];
+	double     Bprime_advec[3][numdof];
+	double     L[numdof];
+	double     dbasis[3][6];
+	double     D_scalar_conduct,D_scalar_advec;
+	double     D_scalar_trans,D_scalar_stab;
+	double     D[3][3];
+	double     K[3][3]={0.0};
+	Tria*      tria=NULL;
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+	heatcapacity=matpar->GetHeatCapacity();
+	latentheat=matpar->GetLatentHeat();
+	thermalconductivity=matpar->GetThermalConductivity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&stabilization,ThermalStabilizationEnum);
+	Input* pressure_input=inputs->GetInput(PressureEnum);      _assert_(pressure_input);
+	Input* enthalpy_input=inputs->GetInput(EnthalpyPicardEnum);_assert_(enthalpy_input); //for this iteration of the step
+	Input* vx_input=inputs->GetInput(VxEnum);                  _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                  _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);                  _assert_(vz_input);
+	Input* vxm_input=inputs->GetInput(VxMeshEnum);             _assert_(vxm_input);
+	Input* vym_input=inputs->GetInput(VyMeshEnum);             _assert_(vym_input);
+	Input* vzm_input=inputs->GetInput(VzMeshEnum);             _assert_(vzm_input);
+	if (stabilization==2) diameter=MinEdgeLength(xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Conduction: */  
+		/*Need to change that depending on enthalpy value -> cold or temperate ice: */  
+		GetBConduct(&B_conduct[0][0],&xyz_list[0][0],gauss); 
+
+		enthalpy_input->GetInputValue(&enthalpy, gauss);
+		pressure_input->GetInputValue(&pressure, gauss);
+		kappa=matpar->GetEnthalpyDiffusionParameter(enthalpy,pressure);
+		D_scalar_conduct=gauss->weight*Jdet*kappa;
+		if(dt) D_scalar_conduct=D_scalar_conduct*dt;
+
+		D[0][0]=D_scalar_conduct; D[0][1]=0; D[0][2]=0;
+		D[1][0]=0; D[1][1]=D_scalar_conduct; D[1][2]=0;
+		D[2][0]=0; D[2][1]=0; D[2][2]=D_scalar_conduct;
+
+		TripleMultiply(&B_conduct[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&B_conduct[0][0],3,numdof,0,
+					&Ke->values[0],1);
+
+		/*Advection: */
+		GetBAdvec(&B_advec[0][0],&xyz_list[0][0],gauss); 
+		GetBprimeAdvec(&Bprime_advec[0][0],&xyz_list[0][0],gauss); 
+
+		vx_input->GetInputValue(&u, gauss);
+		vy_input->GetInputValue(&v, gauss);
+		vz_input->GetInputValue(&w, gauss);
+		vxm_input->GetInputValue(&um,gauss);
+		vym_input->GetInputValue(&vm,gauss);
+		vzm_input->GetInputValue(&wm,gauss);
+		vx=u-um; vy=v-vm; vz=w-wm;
+
+		D_scalar_advec=gauss->weight*Jdet;
+		if(dt) D_scalar_advec=D_scalar_advec*dt;
+
+		D[0][0]=D_scalar_advec*vx;D[0][1]=0;                D[0][2]=0;
+		D[1][0]=0;                D[1][1]=D_scalar_advec*vy;D[1][2]=0;
+		D[2][0]=0;                D[2][1]=0;                D[2][2]=D_scalar_advec*vz;
+
+		TripleMultiply(&B_advec[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&Bprime_advec[0][0],3,numdof,0,
+					&Ke->values[0],1);
+
+		/*Transient: */
+		if(dt){
+			GetNodalFunctionsP1(&L[0], gauss);
+			D_scalar_trans=gauss->weight*Jdet;
+			D_scalar_trans=D_scalar_trans;
+
+			TripleMultiply(&L[0],numdof,1,0,
+						&D_scalar_trans,1,1,0,
+						&L[0],1,numdof,0,
+						&Ke->values[0],1);
+		}
+
+		/*Artifficial diffusivity*/
+		if(stabilization==1){
+			/*Build K: */
+			GetElementSizes(&hx,&hy,&hz);
+			vel=sqrt(pow(vx,2.)+pow(vy,2.)+pow(vz,2.))+1.e-14;
+			h=sqrt( pow(hx*vx/vel,2.) + pow(hy*vy/vel,2.) + pow(hz*vz/vel,2.));
+			K[0][0]=h/(2*vel)*fabs(vx*vx);  K[0][1]=h/(2*vel)*fabs(vx*vy); K[0][2]=h/(2*vel)*fabs(vx*vz);
+			K[1][0]=h/(2*vel)*fabs(vy*vx);  K[1][1]=h/(2*vel)*fabs(vy*vy); K[1][2]=h/(2*vel)*fabs(vy*vz);
+			K[2][0]=h/(2*vel)*fabs(vz*vx);  K[2][1]=h/(2*vel)*fabs(vz*vy); K[2][2]=h/(2*vel)*fabs(vz*vz);
+			D_scalar_stab=gauss->weight*Jdet;
+			if(dt) D_scalar_stab=D_scalar_stab*dt;
+			for(i=0;i<3;i++) for(j=0;j<3;j++) K[i][j] = D_scalar_stab*K[i][j];
+
+			GetBprimeAdvec(&Bprime_advec[0][0],&xyz_list[0][0],gauss); 
+
+			TripleMultiply(&Bprime_advec[0][0],3,numdof,1,
+						&K[0][0],3,3,0,
+						&Bprime_advec[0][0],3,numdof,0,
+						&Ke->values[0],1);
+		}
+		else if(stabilization==2){
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+			tau_parameter=GetStabilizationParameter(u-um,v-vm,w-wm,diameter,rho_ice,heatcapacity,thermalconductivity);
+
+			for(i=0;i<numdof;i++){
+				for(j=0;j<numdof;j++){
+					Ke->values[i*numdof+j]+=tau_parameter*D_scalar_advec*
+					  ((u-um)*dbasis[0][i]+(v-vm)*dbasis[1][i]+(w-wm)*dbasis[2][i])*((u-um)*dbasis[0][j]+(v-vm)*dbasis[1][j]+(w-wm)*dbasis[2][j]);
+				}
+			}
+			if(dt){
+				for(i=0;i<numdof;i++){
+					for(j=0;j<numdof;j++){
+						Ke->values[i*numdof+j]+=tau_parameter*D_scalar_trans*L[j]*((u-um)*dbasis[0][i]+(v-vm)*dbasis[1][i]+(w-wm)*dbasis[2][i]);
+					}
+				}
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixEnthalpyShelf {{{1*/
+ElementMatrix* Penta::CreateKMatrixEnthalpyShelf(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int       i,j,ig;
+	double    mixed_layer_capacity,thermal_exchange_velocity;
+	double    rho_ice,rho_water,heatcapacity;
+	double    Jdet2d,dt;
+	double    xyz_list[NUMVERTICES][3];
+	double	 xyz_list_tria[NUMVERTICES2D][3];
+	double    basis[NUMVERTICES];
+	double    D_scalar;
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if (!IsOnBed() || !IsFloating()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	mixed_layer_capacity=matpar->GetMixedLayerCapacity();
+	thermal_exchange_velocity=matpar->GetThermalExchangeVelocity();
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/* Start looping on the number of gauss (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+				
+		D_scalar=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity/(rho_ice*heatcapacity);
+		if(dt) D_scalar=dt*D_scalar;
+
+		TripleMultiply(&basis[0],numdof,1,0,
+					&D_scalar,1,1,0,
+					&basis[0],1,numdof,0,
+					&Ke->values[0],1);
+	}
+	
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixMelting {{{1*/
+ElementMatrix* Penta::CreateKMatrixMelting(void){
+
+	if (!IsOnBed()) return NULL;
+
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixMelting();
+
+	delete tria->matice; delete tria;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixThermal {{{1*/
+ElementMatrix* Penta::CreateKMatrixThermal(void){
+	
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixThermalVolume();
+	ElementMatrix* Ke2=CreateKMatrixThermalShelf();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+	
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixThermalVolume {{{1*/
+ElementMatrix* Penta::CreateKMatrixThermalVolume(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        stabilization;
+	int        i,j,ig,found=0;
+	double     Jdet,u,v,w,um,vm,wm,vel;
+	double     h,hx,hy,hz,vx,vy,vz;
+	double     gravity,rho_ice,rho_water;
+	double     heatcapacity,thermalconductivity,dt;
+	double     tau_parameter,diameter;
+	double     xyz_list[NUMVERTICES][3];
+	double     B_conduct[3][numdof];
+	double     B_advec[3][numdof];
+	double     Bprime_advec[3][numdof];
+	double     L[numdof];
+	double     dbasis[3][6];
+	double     D_scalar_conduct,D_scalar_advec;
+	double     D_scalar_trans,D_scalar_stab;
+	double     D[3][3];
+	double     K[3][3]={0.0};
+	Tria*      tria=NULL;
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+	heatcapacity=matpar->GetHeatCapacity();
+	thermalconductivity=matpar->GetThermalConductivity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&stabilization,ThermalStabilizationEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);      _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);      _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);      _assert_(vz_input);
+	Input* vxm_input=inputs->GetInput(VxMeshEnum); _assert_(vxm_input);
+	Input* vym_input=inputs->GetInput(VyMeshEnum); _assert_(vym_input);
+	Input* vzm_input=inputs->GetInput(VzMeshEnum); _assert_(vzm_input);
+	if (stabilization==2) diameter=MinEdgeLength(xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Conduction: */
+
+		GetBConduct(&B_conduct[0][0],&xyz_list[0][0],gauss); 
+
+		D_scalar_conduct=gauss->weight*Jdet*(thermalconductivity/(rho_ice*heatcapacity));
+		if(dt) D_scalar_conduct=D_scalar_conduct*dt;
+
+		D[0][0]=D_scalar_conduct; D[0][1]=0; D[0][2]=0;
+		D[1][0]=0; D[1][1]=D_scalar_conduct; D[1][2]=0;
+		D[2][0]=0; D[2][1]=0; D[2][2]=D_scalar_conduct;
+
+		TripleMultiply(&B_conduct[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&B_conduct[0][0],3,numdof,0,
+					&Ke->values[0],1);
+
+		/*Advection: */
+
+		GetBAdvec(&B_advec[0][0],&xyz_list[0][0],gauss); 
+		GetBprimeAdvec(&Bprime_advec[0][0],&xyz_list[0][0],gauss); 
+
+		vx_input->GetInputValue(&u, gauss); vxm_input->GetInputValue(&um,gauss); vx=u-um;
+		vy_input->GetInputValue(&v, gauss); vym_input->GetInputValue(&vm,gauss); vy=v-vm;
+		vz_input->GetInputValue(&w, gauss); vzm_input->GetInputValue(&wm,gauss); vz=w-wm;
+
+		D_scalar_advec=gauss->weight*Jdet;
+		if(dt) D_scalar_advec=D_scalar_advec*dt;
+
+		D[0][0]=D_scalar_advec*vx;    D[0][1]=0;                    D[0][2]=0;
+		D[1][0]=0;                    D[1][1]=D_scalar_advec*vy;    D[1][2]=0;
+		D[2][0]=0;                    D[2][1]=0;                    D[2][2]=D_scalar_advec*vz;
+
+		TripleMultiply(&B_advec[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&Bprime_advec[0][0],3,numdof,0,
+					&Ke->values[0],1);
+
+		/*Transient: */
+		if(dt){
+			GetNodalFunctionsP1(&L[0], gauss);
+			D_scalar_trans=gauss->weight*Jdet;
+			D_scalar_trans=D_scalar_trans;
+
+			TripleMultiply(&L[0],numdof,1,0,
+						&D_scalar_trans,1,1,0,
+						&L[0],1,numdof,0,
+						&Ke->values[0],1);
+		}
+
+		/*Artifficial diffusivity*/
+		if(stabilization==1){
+			/*Build K: */
+			GetElementSizes(&hx,&hy,&hz);
+			vel=sqrt(pow(vx,2.)+pow(vy,2.)+pow(vz,2.))+1.e-14;
+			h=sqrt( pow(hx*vx/vel,2.) + pow(hy*vy/vel,2.) + pow(hz*vz/vel,2.));
+
+			K[0][0]=h/(2*vel)*fabs(vx*vx);  K[0][1]=h/(2*vel)*fabs(vx*vy); K[0][2]=h/(2*vel)*fabs(vx*vz);
+			K[1][0]=h/(2*vel)*fabs(vy*vx);  K[1][1]=h/(2*vel)*fabs(vy*vy); K[1][2]=h/(2*vel)*fabs(vy*vz);
+			K[2][0]=h/(2*vel)*fabs(vz*vx);  K[2][1]=h/(2*vel)*fabs(vz*vy); K[2][2]=h/(2*vel)*fabs(vz*vz);
+
+			D_scalar_stab=gauss->weight*Jdet;
+			if(dt) D_scalar_stab=D_scalar_stab*dt;
+			for(i=0;i<3;i++) for(j=0;j<3;j++) K[i][j] = D_scalar_stab*K[i][j];
+
+			GetBprimeAdvec(&Bprime_advec[0][0],&xyz_list[0][0],gauss); 
+
+			TripleMultiply(&Bprime_advec[0][0],3,numdof,1,
+						&K[0][0],3,3,0,
+						&Bprime_advec[0][0],3,numdof,0,
+						&Ke->values[0],1);
+		}
+		else if(stabilization==2){
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+			tau_parameter=GetStabilizationParameter(u-um,v-vm,w-wm,diameter,rho_ice,heatcapacity,thermalconductivity);
+
+			for(i=0;i<numdof;i++){
+				for(j=0;j<numdof;j++){
+					Ke->values[i*numdof+j]+=tau_parameter*D_scalar_advec*
+					  ((u-um)*dbasis[0][i]+(v-vm)*dbasis[1][i]+(w-wm)*dbasis[2][i])*((u-um)*dbasis[0][j]+(v-vm)*dbasis[1][j]+(w-wm)*dbasis[2][j]);
+				}
+			}
+			if(dt){
+				for(i=0;i<numdof;i++){
+					for(j=0;j<numdof;j++){
+						Ke->values[i*numdof+j]+=tau_parameter*D_scalar_trans*L[j]*((u-um)*dbasis[0][i]+(v-vm)*dbasis[1][i]+(w-wm)*dbasis[2][i]);
+					}
+				}
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixThermalShelf {{{1*/
+ElementMatrix* Penta::CreateKMatrixThermalShelf(void){
+
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int       i,j,ig;
+	double    mixed_layer_capacity,thermal_exchange_velocity;
+	double    rho_ice,rho_water,heatcapacity;
+	double    Jdet2d,dt;
+	double    xyz_list[NUMVERTICES][3];
+	double	 xyz_list_tria[NUMVERTICES2D][3];
+	double    basis[NUMVERTICES];
+	double    D_scalar;
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if (!IsOnBed() || !IsFloating()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	mixed_layer_capacity=matpar->GetMixedLayerCapacity();
+	thermal_exchange_velocity=matpar->GetThermalExchangeVelocity();
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/* Start looping on the number of gauss (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+				
+		D_scalar=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity/(heatcapacity*rho_ice);
+		if(dt) D_scalar=dt*D_scalar;
+
+		TripleMultiply(&basis[0],numdof,1,0,
+					&D_scalar,1,1,0,
+					&basis[0],1,numdof,0,
+					&Ke->values[0],1);
+	}
+	
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorEnthalpy {{{1*/
+ElementVector* Penta::CreatePVectorEnthalpy(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorEnthalpyVolume();
+	ElementVector* pe2=CreatePVectorEnthalpySheet();
+	ElementVector* pe3=CreatePVectorEnthalpyShelf();
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorEnthalpyVolume {{{1*/
+ElementVector* Penta::CreatePVectorEnthalpyVolume(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries*/
+	int    i,j,ig,found=0;
+	int    friction_type,stabilization;
+	double Jdet,phi,dt;
+	double rho_ice,heatcapacity;
+	double thermalconductivity;
+	double viscosity,enthalpy;
+	double tau_parameter,diameter;
+	double u,v,w;
+	double scalar_def,scalar_transient;
+	double temperature_list[NUMVERTICES];
+	double xyz_list[NUMVERTICES][3];
+	double L[numdof];
+	double dbasis[3][6];
+	double epsilon[6];
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	thermalconductivity=matpar->GetThermalConductivity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&stabilization,ThermalStabilizationEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum); _assert_(vz_input);
+	Input* enthalpy_input=NULL;
+	if (dt) enthalpy_input=inputs->GetInput(EnthalpyEnum); _assert_(inputs);
+	if (stabilization==2) diameter=MinEdgeLength(xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,3);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsP1(&L[0], gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		GetPhi(&phi, &epsilon[0], viscosity);
+
+		scalar_def=phi/(rho_ice)*Jdet*gauss->weight;
+		if(dt) scalar_def=scalar_def*dt;
+
+		for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_def*L[i];
+
+		/* Build transient now */
+		if(dt){
+			enthalpy_input->GetInputValue(&enthalpy, gauss);
+			scalar_transient=enthalpy*Jdet*gauss->weight;
+			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_transient*L[i];
+		}
+
+		if(stabilization==2){
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+
+			vx_input->GetInputValue(&u, gauss);
+			vy_input->GetInputValue(&v, gauss);
+			vz_input->GetInputValue(&w, gauss);
+
+			tau_parameter=GetStabilizationParameter(u,v,w,diameter,rho_ice,heatcapacity,thermalconductivity);
+
+			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_def*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
+			if(dt){
+				for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_transient*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorEnthalpyShelf {{{1*/
+ElementVector* Penta::CreatePVectorEnthalpyShelf(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	double     Jdet2d;
+	double     heatcapacity,h_pmp;
+	double     mixed_layer_capacity,thermal_exchange_velocity;
+	double     rho_ice,rho_water,pressure,dt,scalar_ocean;
+	double     xyz_list[NUMVERTICES][3];
+	double     xyz_list_tria[NUMVERTICES2D][3];
+	double     basis[NUMVERTICES];
+	GaussPenta* gauss=NULL;
+
+	/* Ice/ocean heat exchange flux on ice shelf base */
+	if (!IsOnBed() || !IsFloating()) return NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	mixed_layer_capacity=matpar->GetMixedLayerCapacity();
+	thermal_exchange_velocity=matpar->GetThermalExchangeVelocity();
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+		pressure_input->GetInputValue(&pressure,gauss);
+		h_pmp=matpar->PureIceEnthalpy(pressure);
+
+		scalar_ocean=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity*(h_pmp)/(rho_ice*heatcapacity);
+		if(dt) scalar_ocean=dt*scalar_ocean;
+
+		for(i=0;i<numdof;i++) pe->values[i]+=scalar_ocean*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorEnthalpySheet {{{1*/
+ElementVector* Penta::CreatePVectorEnthalpySheet(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	int        analysis_type;
+	double     xyz_list[NUMVERTICES][3];
+	double     xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	double     Jdet2d,dt;
+	double     rho_ice,heatcapacity,geothermalflux_value;
+	double     basalfriction,alpha2,vx,vy;
+	double     scalar;
+	double     basis[NUMVERTICES];
+	Friction*  friction=NULL;
+	GaussPenta* gauss=NULL;
+
+	/* Geothermal flux on ice sheet base and basal friction */
+	if (!IsOnBed() || IsFloating()) return NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);                         _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                         _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);                         _assert_(vz_input);
+	Input* geothermalflux_input=inputs->GetInput(BasalforcingsGeothermalfluxEnum); _assert_(geothermalflux_input);
+
+	/*Build frictoin element, needed later: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+		geothermalflux_input->GetInputValue(&geothermalflux_value,gauss);
+		friction->GetAlpha2(&alpha2,gauss,VxEnum,VyEnum,VzEnum);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		basalfriction=alpha2*(pow(vx,2.0)+pow(vy,2.0));
+		
+		scalar=gauss->weight*Jdet2d*(basalfriction+geothermalflux_value)/(rho_ice);
+		if(dt) scalar=dt*scalar;
+
+		for(i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorMelting {{{1*/
+ElementVector* Penta::CreatePVectorMelting(void){
+	return NULL;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorThermal {{{1*/
+ElementVector* Penta::CreatePVectorThermal(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorThermalVolume();
+	ElementVector* pe2=CreatePVectorThermalSheet();
+	ElementVector* pe3=CreatePVectorThermalShelf();
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorThermalVolume {{{1*/
+ElementVector* Penta::CreatePVectorThermalVolume(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries*/
+	int    i,j,ig,found=0;
+	int    friction_type,stabilization;
+	double Jdet,phi,dt;
+	double rho_ice,heatcapacity;
+	double thermalconductivity;
+	double viscosity,temperature;
+	double tau_parameter,diameter;
+	double u,v,w;
+	double scalar_def,scalar_transient;
+	double temperature_list[NUMVERTICES];
+	double xyz_list[NUMVERTICES][3];
+	double L[numdof];
+	double dbasis[3][6];
+	double epsilon[6];
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	thermalconductivity=matpar->GetThermalConductivity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&stabilization,ThermalStabilizationEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum); _assert_(vz_input);
+	Input* temperature_input=NULL;
+	if (dt) temperature_input=inputs->GetInput(TemperatureEnum); _assert_(inputs);
+	if (stabilization==2) diameter=MinEdgeLength(xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,3);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsP1(&L[0], gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		GetPhi(&phi, &epsilon[0], viscosity);
+
+		scalar_def=phi/(rho_ice*heatcapacity)*Jdet*gauss->weight;
+		if(dt) scalar_def=scalar_def*dt;
+
+		for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_def*L[i];
+
+		/* Build transient now */
+		if(dt){
+			temperature_input->GetInputValue(&temperature, gauss);
+			scalar_transient=temperature*Jdet*gauss->weight;
+			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_transient*L[i];
+		}
+
+		if(stabilization==2){
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+
+			vx_input->GetInputValue(&u, gauss);
+			vy_input->GetInputValue(&v, gauss);
+			vz_input->GetInputValue(&w, gauss);
+
+			tau_parameter=GetStabilizationParameter(u,v,w,diameter,rho_ice,heatcapacity,thermalconductivity);
+
+			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_def*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
+			if(dt){
+				for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_transient*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorThermalShelf {{{1*/
+ElementVector* Penta::CreatePVectorThermalShelf(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	double     Jdet2d;
+	double     mixed_layer_capacity,thermal_exchange_velocity;
+	double     rho_ice,rho_water,pressure,dt,scalar_ocean;
+	double     heatcapacity,t_pmp;
+	double     xyz_list[NUMVERTICES][3];
+	double     xyz_list_tria[NUMVERTICES2D][3];
+	double     basis[NUMVERTICES];
+	GaussPenta* gauss=NULL;
+
+	/* Ice/ocean heat exchange flux on ice shelf base */
+	if (!IsOnBed() || !IsFloating()) return NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	mixed_layer_capacity=matpar->GetMixedLayerCapacity();
+	thermal_exchange_velocity=matpar->GetThermalExchangeVelocity();
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+		pressure_input->GetInputValue(&pressure,gauss);
+		t_pmp=matpar->TMeltingPoint(pressure);
+
+		scalar_ocean=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity*(t_pmp)/(heatcapacity*rho_ice);
+		if(dt) scalar_ocean=dt*scalar_ocean;
+
+		for(i=0;i<numdof;i++) pe->values[i]+=scalar_ocean*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorThermalSheet {{{1*/
+ElementVector* Penta::CreatePVectorThermalSheet(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	int        analysis_type;
+	double     xyz_list[NUMVERTICES][3];
+	double     xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	double     Jdet2d,dt;
+	double     rho_ice,heatcapacity,geothermalflux_value;
+	double     basalfriction,alpha2,vx,vy;
+	double     scalar;
+	double     basis[NUMVERTICES];
+	Friction*  friction=NULL;
+	GaussPenta* gauss=NULL;
+
+	/* Geothermal flux on ice sheet base and basal friction */
+	if (!IsOnBed() || IsFloating()) return NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	rho_ice=matpar->GetRhoIce();
+	heatcapacity=matpar->GetHeatCapacity();
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);                         _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                         _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);                         _assert_(vz_input);
+	Input* geothermalflux_input=inputs->GetInput(BasalforcingsGeothermalfluxEnum); _assert_(geothermalflux_input);
+
+	/*Build frictoin element, needed later: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+		geothermalflux_input->GetInputValue(&geothermalflux_value,gauss);
+		friction->GetAlpha2(&alpha2,gauss,VxEnum,VyEnum,VzEnum);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		basalfriction=alpha2*(pow(vx,2.0)+pow(vy,2.0));
+		
+		scalar=gauss->weight*Jdet2d*(basalfriction+geothermalflux_value)/(heatcapacity*rho_ice);
+		if(dt) scalar=dt*scalar;
+
+		for(i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsThermal{{{1*/
+void  Penta::GetSolutionFromInputsThermal(Vec solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	double       values[numdof];
+	double       temp;
+	GaussPenta   *gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* t_input=inputs->GetInput(TemperatureEnum); _assert_(t_input);
+
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		/*Recover temperature*/
+		gauss->GaussVertex(i);
+		t_input->GetInputValue(&temp,gauss);
+		values[i]=temp;
+	}
+
+	/*Add value to global vector*/
+	VecSetValues(solution,numdof,doflist,(const double*)values,INSERT_VALUES);
+
+	/*Free ressources:*/
+	delete gauss;
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsEnthalpy{{{1*/
+void  Penta::GetSolutionFromInputsEnthalpy(Vec solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	double       values[numdof];
+	double       enthalpy;
+	GaussPenta   *gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* h_input=inputs->GetInput(EnthalpyEnum); _assert_(h_input);
+
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		/*Recover temperature*/
+		gauss->GaussVertex(i);
+		h_input->GetInputValue(&enthalpy,gauss);
+		values[i]=enthalpy;
+	}
+
+	/*Add value to global vector*/
+	VecSetValues(solution,numdof,doflist,(const double*)values,INSERT_VALUES);
+
+	/*Free ressources:*/
+	delete gauss;
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionThermal {{{1*/
+void  Penta::InputUpdateFromSolutionThermal(double* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	bool   converged;
+	int    i,rheology_law;
+	double xyz_list[NUMVERTICES][3];
+	double values[numdof];
+	double B[numdof];
+	double B_average,s_average;
+	int*   doflist=NULL;
+	//double pressure[numdof];
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+		//GetInputListOnVertices(&pressure[0],PressureEnum);
+		//if(values[i]>matpar->TMeltingPoint(pressure[i])) values[i]=matpar->TMeltingPoint(pressure[i]);
+		//if(values[i]<matpar->TMeltingPoint(pressure[i])-50) values[i]=matpar->TMeltingPoint(pressure[i])-50;
+
+		/*Check solution*/
+		if(isnan(values[i])) _error_("NaN found in solution vector");
+		//if(values[i]<0)      printf("temperature < 0°K found in solution vector\n");
+		//if(values[i]>275)    printf("temperature > 275°K found in solution vector (Paterson's rheology associated is negative)\n");
+	}
+
+	/*Get all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* surface_input=inputs->GetInput(SurfaceEnum); _assert_(surface_input);
+
+	this->inputs->GetInputValue(&converged,ConvergedEnum);
+	if(converged){
+		this->inputs->AddInput(new PentaP1Input(TemperatureEnum,values));
+
+		/*Update Rheology only if converged (we must make sure that the temperature is below melting point
+		 * otherwise the rheology could be negative*/
+		this->parameters->FindParam(&rheology_law,MaterialsRheologyLawEnum);
+		switch(rheology_law){
+			case NoneEnum:
+				/*Do nothing: B is not temperature dependent*/
+				break;
+			case PatersonEnum:
+				B_average=Paterson((values[0]+values[1]+values[2]+values[3]+values[4]+values[5])/6.0);
+				for(i=0;i<numdof;i++) B[i]=B_average;
+				this->matice->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				break;
+			case ArrheniusEnum:
+				surface_input->GetInputAverage(&s_average);
+				B_average=Arrhenius((values[0]+values[1]+values[2]+values[3]+values[4]+values[5])/6.0,
+							s_average-((xyz_list[0][2]+xyz_list[1][2]+xyz_list[2][2]+xyz_list[3][2]+xyz_list[4][2]+xyz_list[5][2])/6.0),
+							matice->GetN());
+				for(i=0;i<numdof;i++) B[i]=B_average;
+				this->matice->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				break;
+			default:
+				_error_("Rheology law %s not supported yet",EnumToStringx(rheology_law));
+
+		}
+	}
+	else{
+		this->inputs->AddInput(new PentaP1Input(TemperaturePicardEnum,values));
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionEnthalpy {{{1*/
+void  Penta::InputUpdateFromSolutionEnthalpy(double* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	bool   converged=false;
+	int    i,rheology_law;
+	double xyz_list[NUMVERTICES][3];
+	double values[numdof];
+	double pressure[NUMVERTICES];
+	double temperatures[numdof];
+	double waterfraction[numdof];
+	double B[numdof];
+	double B_average,s_average;
+	int*   doflist=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+
+		/*Check solution*/
+		if(isnan(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	GetInputListOnVertices(&pressure[0],PressureEnum);
+	Input* surface_input=inputs->GetInput(SurfaceEnum); _assert_(surface_input);
+	
+	this->inputs->GetInputValue(&converged,ConvergedEnum);
+	if(converged){
+		/*Convert enthalpy into temperature and water fraction*/
+		for(i=0;i<numdof;i++) matpar->EnthalpyToThermal(&temperatures[i],&waterfraction[i],values[i],pressure[i]);
+			
+		this->inputs->AddInput(new PentaP1Input(EnthalpyEnum,values));
+		this->inputs->AddInput(new PentaP1Input(WaterfractionEnum,waterfraction));
+		this->inputs->AddInput(new PentaP1Input(TemperatureEnum,temperatures));
+
+		/*Update Rheology only if converged (we must make sure that the temperature is below melting point
+		 * otherwise the rheology could be negative*/
+		this->parameters->FindParam(&rheology_law,MaterialsRheologyLawEnum);
+		switch(rheology_law){
+			case NoneEnum:
+				/*Do nothing: B is not temperature dependent*/
+				break;
+			case PatersonEnum:
+				B_average=Paterson((temperatures[0]+temperatures[1]+temperatures[2]+temperatures[3]+temperatures[4]+temperatures[5])/6.0);
+				for(i=0;i<numdof;i++) B[i]=B_average;
+				this->matice->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				break;
+			case ArrheniusEnum:
+				surface_input->GetInputAverage(&s_average);
+				B_average=Arrhenius((temperatures[0]+temperatures[1]+temperatures[2]+temperatures[3]+temperatures[4]+temperatures[5])/6.0,
+							s_average-((xyz_list[0][2]+xyz_list[1][2]+xyz_list[2][2]+xyz_list[3][2]+xyz_list[4][2]+xyz_list[5][2])/6.0),
+							matice->GetN());
+				for(i=0;i<numdof;i++) B[i]=B_average;
+				this->matice->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				break;
+			default:
+				_error_("Rheology law %s not supported yet",EnumToStringx(rheology_law));
+
+		}
+	}
+	else{
+		this->inputs->AddInput(new PentaP1Input(EnthalpyPicardEnum,values));
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_CONTROL_
+/*FUNCTION Penta::ControlInputGetGradient{{{1*/
+void Penta::ControlInputGetGradient(Vec gradient,int enum_type){
+
+	int doflist1[NUMVERTICES];
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		if(!IsOnBed()) return;
+		input=(Input*)matice->inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input %s not found",EnumToStringx(enum_type));
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input %s is not a ControlInput",EnumToStringx(enum_type));
+
+	this->GetDofList1(&doflist1[0]);
+	((ControlInput*)input)->GetGradient(gradient,&doflist1[0]);
+
+}/*}}}*/
+/*FUNCTION Penta::ControlInputScaleGradient{{{1*/
+void Penta::ControlInputScaleGradient(int enum_type,double scale){
+
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)matice->inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input %s not found",EnumToStringx(enum_type));
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input %s is not a ControlInput",EnumToStringx(enum_type));
+
+	((ControlInput*)input)->ScaleGradient(scale);
+}/*}}}*/
+/*FUNCTION Penta::ControlInputSetGradient{{{1*/
+void Penta::ControlInputSetGradient(double* gradient,int enum_type){
+
+	int    doflist1[NUMVERTICES];
+	double grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)matice->inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input %s not found",EnumToStringx(enum_type));
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input %s is not a ControlInput",EnumToStringx(enum_type));
+
+	this->GetDofList1(&doflist1[0]);
+	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[doflist1[i]];
+	grad_input=new PentaP1Input(GradientEnum,grad_list);
+	((ControlInput*)input)->SetGradient(grad_input);
+
+}/*}}}*/
+/*FUNCTION Penta::CreatePVectorAdjointHoriz{{{1*/
+ElementVector* Penta::CreatePVectorAdjointHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case MacAyealApproximationEnum:
+			return CreatePVectorAdjointMacAyeal();
+		case PattynApproximationEnum:
+			return CreatePVectorAdjointPattyn();
+		case NoneApproximationEnum:
+			return NULL;
+		case StokesApproximationEnum:
+			return CreatePVectorAdjointStokes();
+		default:
+			_error_("Approximation %s not supported yet",EnumToStringx(approximation));
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorAdjointMacAyeal{{{1*/
+ElementVector* Penta::CreatePVectorAdjointMacAyeal(){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorAdjointHoriz();
+	delete tria->matice; delete tria;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorAdjointPattyn{{{1*/
+ElementVector* Penta::CreatePVectorAdjointPattyn(void){
+
+	if (!IsOnSurface()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+	ElementVector* pe=tria->CreatePVectorAdjointHoriz();
+	delete tria->matice; delete tria;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorAdjointStokes{{{1*/
+ElementVector* Penta::CreatePVectorAdjointStokes(void){
+
+	if (!IsOnSurface()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+	ElementVector* pe=tria->CreatePVectorAdjointStokes();
+	delete tria->matice; delete tria;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::Gradj {{{1*/
+void  Penta::Gradj(Vec gradient,int control_type){
+	/*dJ/dalpha = ∂L/∂alpha = ∂J/∂alpha + ∂/∂alpha(KU-F)*/
+
+	int              i,approximation;
+	Tria*            tria=NULL;
+
+	/*If on water, skip grad (=0): */
+	if(IsOnWater())return;
+
+	/*First deal with ∂/∂alpha(KU-F)*/
+	switch(control_type){
+
+		case FrictionCoefficientEnum:
+			inputs->GetInputValue(&approximation,ApproximationEnum);
+			switch(approximation){
+				case MacAyealApproximationEnum:
+					GradjDragMacAyeal(gradient);
+					break;
+				case PattynApproximationEnum:
+					GradjDragPattyn(gradient);
+					break;
+				case StokesApproximationEnum:
+					GradjDragStokes(gradient);
+					break;
+				case NoneApproximationEnum:
+					/*Gradient is 0*/
+					break;
+				default:
+					_error_("approximation %s not supported yet",EnumToStringx(approximation));
+			}
+			break;
+
+		case MaterialsRheologyBbarEnum:
+			inputs->GetInputValue(&approximation,ApproximationEnum);
+			switch(approximation){
+				case MacAyealApproximationEnum:
+					GradjBbarMacAyeal(gradient);
+					break;
+				case PattynApproximationEnum:
+					GradjBbarPattyn(gradient);
+					break;
+				case StokesApproximationEnum:
+					GradjBbarStokes(gradient);
+					break;
+				case NoneApproximationEnum:
+					/*Gradient is 0*/
+					break;
+				default:
+					_error_("approximation %s not supported yet",EnumToStringx(approximation));
+			}
+			break;
+
+		default:
+			_error_("control type %s not supported yet: ",EnumToStringx(control_type));
+	}
+
+	/*Now deal with ∂J/∂alpha*/
+	int        *responses = NULL;
+	int         num_responses,resp;
+	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+
+	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+
+		case ThicknessAbsMisfitEnum:
+		case SurfaceAbsVelMisfitEnum:
+		case SurfaceRelVelMisfitEnum:
+		case SurfaceLogVelMisfitEnum:
+		case SurfaceLogVxVyMisfitEnum:
+		case SurfaceAverageVelMisfitEnum:
+			/*Nothing, J does not depends on the parameter being inverted for*/
+			break;
+		case DragCoefficientAbsGradientEnum:
+			if (!IsOnBed()) return;
+			tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+			tria->GradjDragGradient(gradient,resp);
+			delete tria->matice; delete tria;
+			break;
+		case RheologyBbarAbsGradientEnum:
+			if (!IsOnBed()) return;
+			tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+			tria->GradjBGradient(gradient,resp);
+			delete tria->matice; delete tria;
+			break;
+		default:
+			_error_("response %s not supported yet",EnumToStringx(responses[resp]));
+	}
+	xfree((void**)&responses);
+}
+/*}}}*/
+/*FUNCTION Penta::GradjDragMacAyeal {{{1*/
+void  Penta::GradjDragMacAyeal(Vec gradient){
+
+	/*Gradient is 0 if on shelf or not on bed*/
+	if(IsFloating() || !IsOnBed()) return;
+
+	/*Spawn tria*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	tria->GradjDragMacAyeal(gradient);
+	delete tria->matice; delete tria;
+
+} /*}}}*/
+/*FUNCTION Penta::GradjDragPattyn {{{1*/
+void  Penta::GradjDragPattyn(Vec gradient){
+
+	int        i,j,ig;
+	int        analysis_type;
+	int        doflist1[NUMVERTICES];
+	double     vx,vy,lambda,mu,alpha_complement,Jdet;
+	double     bed,thickness,Neff,drag;
+	double     xyz_list[NUMVERTICES][3];
+	double     xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	double     dk[NDOF3]; 
+	double     grade_g[NUMVERTICES]={0.0};
+	double     grade_g_gaussian[NUMVERTICES];
+	double     basis[6];
+	Friction*  friction=NULL;
+	GaussPenta  *gauss=NULL;
+
+	/*Gradient is 0 if on shelf or not on bed*/
+	if(IsFloating() || !IsOnBed()) return;
+
+	/*Retrieve all inputs and parameters*/
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	GetDofList1(&doflist1[0]);
+	Input* adjointx_input=inputs->GetInput(AdjointxEnum);               _assert_(adjointx_input);
+	Input* adjointy_input=inputs->GetInput(AdjointyEnum);               _assert_(adjointy_input);
+	Input* vx_input=inputs->GetInput(VxEnum);                           _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                           _assert_(vy_input);
+	Input* dragcoefficient_input=inputs->GetInput(FrictionCoefficientEnum); _assert_(dragcoefficient_input);
+
+	/*Build frictoin element, needed later: */
+	friction=new Friction("2d",inputs,matpar,analysis_type);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(0,1,2,4);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet, &xyz_list_tria[0][0],gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		/*Build alpha_complement_list: */
+		friction->GetAlphaComplement(&alpha_complement, gauss,VxEnum,VyEnum,VzEnum);
+
+		dragcoefficient_input->GetInputValue(&drag, gauss);
+		adjointx_input->GetInputValue(&lambda, gauss);
+		adjointy_input->GetInputValue(&mu, gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		dragcoefficient_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for (i=0;i<NUMVERTICES;i++){
+			grade_g_gaussian[i]=-2*drag*alpha_complement*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i]; /*basis are 0 for the 3 upper nodes*/
+		}
+
+		/*Add gradje_g_gaussian vector to gradje_g: */
+		for(i=0;i<NUMVERTICES;i++){
+			_assert_(!isnan(grade_g[i]));
+			grade_g[i]+=grade_g_gaussian[i];
+		}
+	}
+	VecSetValues(gradient,NUMVERTICES,doflist1,(const double*)grade_g,ADD_VALUES);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+}
+/*}}}*/
+/*FUNCTION Penta::GradjDragStokes {{{1*/
+void  Penta::GradjDragStokes(Vec gradient){
+
+	int        i,j,ig;
+	int        analysis_type;
+	int        doflist1[NUMVERTICES];
+	double     bed,thickness,Neff;
+	double     lambda,mu,xi,Jdet,vx,vy,vz;
+	double     alpha_complement,drag;
+	double     surface_normal[3],bed_normal[3];
+	double     xyz_list[NUMVERTICES][3];
+	double     xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	double     dk[NDOF3]; 
+	double     basis[6];
+	double     grade_g[NUMVERTICES]={0.0};
+	double     grade_g_gaussian[NUMVERTICES];
+	Friction*  friction=NULL;
+	GaussPenta* gauss=NULL;
+
+	/*Gradient is 0 if on shelf or not on bed*/
+	if(IsFloating() || !IsOnBed()) return;
+
+	/*Retrieve all inputs and parameters*/
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	GetDofList1(&doflist1[0]);
+	Input* drag_input    =inputs->GetInput(FrictionCoefficientEnum); _assert_(drag_input);
+	Input* vx_input      =inputs->GetInput(VxEnum);              _assert_(vx_input);
+	Input* vy_input      =inputs->GetInput(VyEnum);              _assert_(vy_input);
+	Input* vz_input      =inputs->GetInput(VzEnum);              _assert_(vz_input);
+	Input* adjointx_input=inputs->GetInput(AdjointxEnum);        _assert_(adjointx_input);
+	Input* adjointy_input=inputs->GetInput(AdjointyEnum);        _assert_(adjointy_input);
+	Input* adjointz_input=inputs->GetInput(AdjointzEnum);        _assert_(adjointz_input);
+
+	/*Build frictoin element, needed later: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(0,1,2,4);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/*Recover alpha_complement and drag: */
+		friction->GetAlphaComplement(&alpha_complement, gauss,VxEnum,VyEnum,VzEnum);
+		drag_input->GetInputValue(&drag,gauss);
+
+		/*recover lambda mu and xi: */
+		adjointx_input->GetInputValue(&lambda,gauss);
+		adjointy_input->GetInputValue(&mu    ,gauss);
+		adjointz_input->GetInputValue(&xi    ,gauss);
+
+		/*recover vx vy and vz: */
+		vx_input->GetInputValue(&vx, gauss);
+		vy_input->GetInputValue(&vy, gauss);
+		vz_input->GetInputValue(&vz, gauss);
+
+		/*Get normal vector to the bed */
+		SurfaceNormal(&surface_normal[0],xyz_list_tria);
+
+		bed_normal[0]=-surface_normal[0]; //Function is for upper surface, so the normal to the bed is the opposite of the result
+		bed_normal[1]=-surface_normal[1];
+		bed_normal[2]=-surface_normal[2];
+
+		/* Get Jacobian determinant: */
+		GetTriaJacobianDeterminant(&Jdet,&xyz_list_tria[0][0],gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		/*Get k derivative: dk/dx */
+		drag_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for (i=0;i<NUMVERTICES;i++){
+			//standard gradient dJ/dki
+			grade_g_gaussian[i]=(
+						-lambda*(2*drag*alpha_complement*(vx - vz*bed_normal[0]*bed_normal[2]))
+						-mu    *(2*drag*alpha_complement*(vy - vz*bed_normal[1]*bed_normal[2]))
+						-xi    *(2*drag*alpha_complement*(-vx*bed_normal[0]*bed_normal[2]-vy*bed_normal[1]*bed_normal[2]))
+						)*Jdet*gauss->weight*basis[i]; 
+		}
+
+		/*Add gradje_g_gaussian vector to gradje_g: */
+		for( i=0; i<NUMVERTICES; i++)grade_g[i]+=grade_g_gaussian[i];
+	}
+
+	VecSetValues(gradient,NUMVERTICES,doflist1,(const double*)grade_g,ADD_VALUES);
+
+	delete friction;
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::GradjBbarMacAyeal {{{1*/
+void  Penta::GradjBbarMacAyeal(Vec gradient){
+
+	/*This element should be collapsed into a tria element at its base*/
+	if (!IsOnBed()) return; 
+
+	/*Depth Average B*/
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+
+	/*Collapse element to the base*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+	tria->GradjBMacAyeal(gradient);
+	delete tria->matice; delete tria;
+
+	/*delete Average B*/
+	this->matice->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+
+} /*}}}*/
+/*FUNCTION Penta::GradjBbarPattyn {{{1*/
+void  Penta::GradjBbarPattyn(Vec gradient){
+
+	/*Gradient is computed on bed only (Bbar)*/
+	if (!IsOnBed()) return;
+
+	/*Depth Average B*/
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+
+	/*Collapse element to the base*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2);
+	tria->GradjBMacAyeal(gradient);    //We use MacAyeal as an estimate for now
+	delete tria->matice; delete tria;
+
+	/*delete Average B*/
+	this->matice->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+} /*}}}*/
+/*FUNCTION Penta::GradjBbarStokes {{{1*/
+void  Penta::GradjBbarStokes(Vec gradient){
+
+	/*Gradient is computed on bed only (Bbar)*/
+	if (!IsOnBed()) return;
+
+	/*Depth Average B*/
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+
+	/*Collapse element to the base*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2);
+	tria->GradjBMacAyeal(gradient);    //We use MacAyeal as an estimate for now
+	delete tria->matice; delete tria;
+
+	/*delete Average B*/
+	this->matice->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+} /*}}}*/
+/*FUNCTION Penta::InputControlUpdate{{{1*/
+void  Penta::InputControlUpdate(double scalar,bool save_parameter){
+
+	/*Intermediary*/
+	int    num_controls;
+	int*   control_type=NULL;
+	Input* input=NULL;
+
+	/*retrieve some parameters: */
+	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+	for(int i=0;i<num_controls;i++){
+
+		if(control_type[i]==MaterialsRheologyBbarEnum){
+			if (!IsOnBed()) goto cleanup_and_return;
+			input=(Input*)matice->inputs->GetInput(MaterialsRheologyBEnum); _assert_(input);
+		}
+		else{
+			input=(Input*)this->inputs->GetInput(control_type[i]); _assert_(input);
+		}
+
+		if (input->ObjectEnum()!=ControlInputEnum) _error_("input %s is not a ControlInput",EnumToStringx(control_type[i]));
+
+		((ControlInput*)input)->UpdateValue(scalar);
+		((ControlInput*)input)->Constrain();
+		if (save_parameter) ((ControlInput*)input)->SaveValue();
+
+		if(control_type[i]==MaterialsRheologyBbarEnum){
+			this->InputExtrude(MaterialsRheologyBEnum,MaterialsEnum);
+		}
+	}
+
+	/*Clean up and return*/
+cleanup_and_return:
+	xfree((void**)&control_type);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionAdjointStokes {{{1*/
+void  Penta::InputUpdateFromSolutionAdjointStokes(double* solution){
+
+	const int    numdof=NDOF4*NUMVERTICES;
+
+	int    i;
+	double values[numdof];
+	double lambdax[NUMVERTICES];
+	double lambday[NUMVERTICES];
+	double lambdaz[NUMVERTICES];
+	double lambdap[NUMVERTICES];
+	int*   doflist=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		lambdax[i]=values[i*NDOF4+0];
+		lambday[i]=values[i*NDOF4+1];
+		lambdaz[i]=values[i*NDOF4+2];
+		lambdap[i]=values[i*NDOF4+3];
+
+		/*Check solution*/
+		if(isnan(lambdax[i])) _error_("NaN found in solution vector");
+		if(isnan(lambday[i])) _error_("NaN found in solution vector");
+		if(isnan(lambdaz[i])) _error_("NaN found in solution vector");
+		if(isnan(lambdap[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(AdjointxEnum,lambdax));
+	this->inputs->AddInput(new PentaP1Input(AdjointyEnum,lambday));
+	this->inputs->AddInput(new PentaP1Input(AdjointzEnum,lambdaz));
+	this->inputs->AddInput(new PentaP1Input(AdjointpEnum,lambdap));
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionAdjointHoriz {{{1*/
+void  Penta::InputUpdateFromSolutionAdjointHoriz(double* solution){
+
+	const int numdof=NDOF2*NUMVERTICES;
+
+	int    i;
+	double values[numdof];
+	double lambdax[NUMVERTICES];
+	double lambday[NUMVERTICES];
+	int*   doflist=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		lambdax[i]=values[i*NDOF2+0];
+		lambday[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(isnan(lambdax[i]))       _error_("NaN found in solution vector");
+		if(isnan(lambday[i]))       _error_("NaN found in solution vector");
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(AdjointxEnum,lambdax));
+	this->inputs->AddInput(new PentaP1Input(AdjointyEnum,lambday));
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceAverageVelMisfit {{{1*/
+double Penta::SurfaceAverageVelMisfit(bool process_units,int weight_index){
+
+	int    approximation;
+	double J;
+	Tria*  tria=NULL;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/*Bail out if this element if:
+	 * -> Non MacAyeal and not on the surface
+	 * -> MacAyeal (2d model) and not on bed) */
+	if ((approximation!=MacAyealApproximationEnum && !IsOnSurface()) || (approximation==MacAyealApproximationEnum && !IsOnBed())){
+		return 0;
+	}
+	else if (approximation==MacAyealApproximationEnum){
+
+		/*This element should be collapsed into a tria element at its base. Create this tria element, 
+		 * and compute SurfaceAverageVelMisfit*/
+		tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+		J=tria->SurfaceAverageVelMisfit(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceAverageVelMisfit(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceAbsVelMisfit {{{1*/
+double Penta::SurfaceAbsVelMisfit(bool process_units,int weight_index){
+
+	int    approximation;
+	double J;
+	Tria*  tria=NULL;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/*Bail out if this element if:
+	 * -> Non MacAyeal and not on the surface
+	 * -> MacAyeal (2d model) and not on bed) */
+	if ((approximation!=MacAyealApproximationEnum && !IsOnSurface()) || (approximation==MacAyealApproximationEnum && !IsOnBed())){
+		return 0;
+	}
+	else if (approximation==MacAyealApproximationEnum){
+
+		/*This element should be collapsed into a tria element at its base. Create this tria element, 
+		 * and compute SurfaceAbsVelMisfit*/
+		tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+		J=tria->SurfaceAbsVelMisfit(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceAbsVelMisfit(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceLogVelMisfit {{{1*/
+double Penta::SurfaceLogVelMisfit(bool process_units,int weight_index){
+
+	int    approximation;
+	double J;
+	Tria*  tria=NULL;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/*Bail out if this element if:
+	 * -> Non MacAyeal and not on the surface
+	 * -> MacAyeal (2d model) and not on bed) */
+	if ((approximation!=MacAyealApproximationEnum && !IsOnSurface()) || (approximation==MacAyealApproximationEnum && !IsOnBed())){
+		return 0;
+	}
+	else if (approximation==MacAyealApproximationEnum){
+
+		/*This element should be collapsed into a tria element at its base. Create this tria element, 
+		 * and compute SurfaceLogVelMisfit*/
+		tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+		J=tria->SurfaceLogVelMisfit(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceLogVelMisfit(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceLogVxVyMisfit {{{1*/
+double Penta::SurfaceLogVxVyMisfit(bool process_units,int weight_index){
+
+	double J;
+	Tria* tria=NULL;
+
+	/*inputs: */
+	int  approximation;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/*Bail out if this element if:
+	 * -> Non MacAyeal and not on the surface
+	 * -> MacAyeal (2d model) and not on bed) */
+	if ((approximation!=MacAyealApproximationEnum && !IsOnSurface()) || (approximation==MacAyealApproximationEnum && !IsOnBed())){
+		return 0;
+	}
+	else if (approximation==MacAyealApproximationEnum){
+
+		/*This element should be collapsed into a tria element at its base. Create this tria element, 
+		 * and compute SurfaceLogVxVyMisfit*/
+		tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+		J=tria->SurfaceLogVxVyMisfit(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceLogVxVyMisfit(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceRelVelMisfit {{{1*/
+double Penta::SurfaceRelVelMisfit(bool process_units,int weight_index){
+
+	int    approximation;
+	double J;
+	Tria*  tria=NULL;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/*Bail out if this element if:
+	 * -> Non MacAyeal and not on the surface
+	 * -> MacAyeal (2d model) and not on bed) */
+	if ((approximation!=MacAyealApproximationEnum && !IsOnSurface()) || (approximation==MacAyealApproximationEnum && !IsOnBed())){
+		return 0;
+	}
+	else if (approximation==MacAyealApproximationEnum){
+
+		/*This element should be collapsed into a tria element at its base. Create this tria element, 
+		 * and compute SurfaceRelVelMisfit*/
+		tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+		J=tria->SurfaceRelVelMisfit(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceRelVelMisfit(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::ThicknessAbsGradient{{{1*/
+double Penta::ThicknessAbsGradient(bool process_units,int weight_index){
+
+	_error_("Not implemented yet");
+}
+/*}}}*/
+/*FUNCTION Penta::ThicknessAbsMisfit {{{1*/
+double Penta::ThicknessAbsMisfit(bool process_units,int weight_index){
+
+	int    approximation;
+	double J;
+	Tria*  tria=NULL;
+
+	/*retrieve inputs :*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+	_error_("Not implemented yet");
+
+	tria=(Tria*)SpawnTria(0,1,2);
+	J=tria->ThicknessAbsMisfit(process_units,weight_index);
+	delete tria->matice; delete tria;
+	return J;
+}
+/*}}}*/
+/*FUNCTION Penta::DragCoefficientAbsGradient{{{1*/
+double Penta::DragCoefficientAbsGradient(bool process_units,int weight_index){
+
+	double J;
+	Tria*  tria=NULL;
+
+	/*If on water, on shelf or not on bed, skip: */
+	if(IsOnWater()|| IsFloating() || !IsOnBed()) return 0;
+
+	tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria
+	J=tria->DragCoefficientAbsGradient(process_units,weight_index);
+	delete tria->matice; delete tria;
+	return J;
+}
+/*}}}*/
+/*FUNCTION Penta::RheologyBbarAbsGradient{{{1*/
+double Penta::RheologyBbarAbsGradient(bool process_units,int weight_index){
+
+	double J;
+	Tria*  tria=NULL;
+
+	/*If on water, on shelf or not on bed, skip: */
+	if(IsOnWater() || !IsOnBed()) return 0;
+
+	tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria
+	J=tria->RheologyBbarAbsGradient(process_units,weight_index);
+	delete tria->matice; delete tria;
+	return J;
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_DAKOTA_
+/*FUNCTION Penta::InputUpdateFromVectorDakota(double* vector, int name, int type);{{{1*/
+void  Penta::InputUpdateFromVectorDakota(double* vector, int name, int type){
+	
+	int i,j;
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			/*New PentaP1Input*/
+			double values[6];
+
+			/*Get values on the 6 vertices*/
+			for (i=0;i<6;i++){
+				values[i]=vector[this->nodes[i]->GetSidList()]; //careful, vector of values here is not parallel distributed, but serial distributed (from a serial Dakota core!)
+			}
+
+			/*Branch on the specified type of update: */
+			switch(name){
+				case ThicknessEnum:
+					/*Update thickness + surface: assume bed is constant. On ice shelves, takes hydrostatic equilibrium {{{2*/
+					double  thickness[6];
+					double  thickness_init[6];
+					double  hydrostatic_ratio[6];
+					double  surface[6];
+					double  bed[6];
+					
+					/*retrieve inputs: */
+					GetInputListOnVertices(&thickness_init[0],ThicknessEnum);
+					GetInputListOnVertices(&hydrostatic_ratio[0],GeometryHydrostaticRatioEnum);
+					GetInputListOnVertices(&bed[0],BedEnum);
+					GetInputListOnVertices(&surface[0],SurfaceEnum);
+
+					/*build new thickness: */
+//					for(j=0;j<6;j++)thickness[j]=values[j];
+
+					/*build new bed and surface: */
+					if (this->IsFloating()){
+						/*hydrostatic equilibrium: */
+						double rho_ice,rho_water,di;
+						rho_ice=this->matpar->GetRhoIce();
+						rho_water=this->matpar->GetRhoWater();
+
+						di=rho_ice/rho_water;
+
+						/*build new thickness: */
+						for (j=0; j<6; j++) {
+						/*  for observed/interpolated/hydrostatic thickness, remove scaling from any hydrostatic thickness  */
+							if     (hydrostatic_ratio[j] >= 0.)
+								thickness[j]=values[j]-(values[j]/thickness_init[j]-1.)*hydrostatic_ratio[j]*surface[j]/(1.-di);
+						/*  for minimum thickness, don't scale  */
+							else
+								thickness[j]=thickness_init[j];
+
+						/*  check the computed thickness and update bed  */
+							if (thickness[j] < 0.)
+								thickness[j]=1./(1.-di);
+							bed[j]=surface[j]-thickness[j];
+						}
+
+//						for(j=0;j<6;j++){
+//							surface[j]=(1-di)*thickness[j];
+//							bed[j]=-di*thickness[j];
+//						}
+					}
+					else{
+						/*build new thickness: */
+						for (j=0; j<6; j++) {
+						/*  for observed thickness, use scaled value  */
+							if(hydrostatic_ratio[j] >= 0.)
+								thickness[j]=values[j];
+						/*  for minimum thickness, don't scale  */
+							else
+								thickness[j]=thickness_init[j];
+						}
+
+						/*update bed on grounded ice: */
+//						for(j=0;j<6;j++)surface[j]=bed[j]+thickness[j];
+						for(j=0;j<6;j++)bed[j]=surface[j]-thickness[j];
+					}
+
+					/*Add new inputs: */
+					this->inputs->AddInput(new PentaP1Input(ThicknessEnum,thickness));
+					this->inputs->AddInput(new PentaP1Input(BedEnum,bed));
+					this->inputs->AddInput(new PentaP1Input(SurfaceEnum,surface));
+
+					/*}}}*/
+					break;
+				default:
+					this->inputs->AddInput(new PentaP1Input(name,values));
+			}
+			break;
+
+		default:
+			_error_("type %i (%s) not implemented yet",type,EnumToStringx(type));
+	}
+
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromVectorDakota(int* vector, int name, int type);{{{1*/
+void  Penta::InputUpdateFromVectorDakota(int* vector, int name, int type){
+	_error_(" not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromVectorDakota(bool* vector, int name, int type);{{{1*/
+void  Penta::InputUpdateFromVectorDakota(bool* vector, int name, int type){
+	_error_(" not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromMatrixDakota(double* matrix, int nrows, int ncols, int name, int type);{{{1*/
+void  Penta::InputUpdateFromMatrixDakota(double* matrix, int nrows, int ncols, int name, int type){
+	
+	int i,j,t;
+	TransientInput* transientinput=NULL;
+	double values[6];
+	double time;
+	int row;
+	double yts;
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+			
+			/*Create transient input: */
+						
+			parameters->FindParam(&yts,ConstantsYtsEnum);
+
+			for(t=0;t<ncols;t++){ //ncols is the number of times
+
+				/*create input values: */
+				for(i=0;i<6;i++){
+					row=this->nodes[i]->GetSidList();
+					values[i]=(double)matrix[ncols*row+t];
+				}
+
+				/*time? :*/
+				time=(double)matrix[(nrows-1)*ncols+t]*yts;
+
+				if(t==0) transientinput=new TransientInput(name);
+				transientinput->AddTimeInput(new PentaP1Input(name,values),time);
+				transientinput->Configure(parameters);
+			}
+			this->inputs->AddInput(transientinput);
+			break;
+
+		default:
+			_error_("type %i (%s) not implemented yet",type,EnumToStringx(type));
+	}
+
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_DIAGNOSTIC_
+/*FUNCTION Penta::CreateDVectorDiagnosticHoriz {{{1*/
+ElementVector* Penta::CreateDVectorDiagnosticHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case StokesApproximationEnum:
+			return CreateDVectorDiagnosticStokes();
+		default:
+			return NULL; //no need for doftypes outside of stokes approximation
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateDVectorDiagnosticStokes{{{1*/
+ElementVector* Penta::CreateDVectorDiagnosticStokes(void){
+
+	/*output: */
+	ElementVector* De=NULL;
+	/*intermediary: */
+	int approximation;
+	int i;
+
+	/*Initialize Element vector and return if necessary*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=StokesApproximationEnum) return NULL;
+
+	De=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	for (i=0;i<NUMVERTICES;i++){
+		De->values[i*4+0]=VelocityEnum;
+		De->values[i*4+1]=VelocityEnum;
+		De->values[i*4+2]=VelocityEnum;
+		De->values[i*4+3]=PressureEnum;
+	}
+
+	return De;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealPattyn{{{1*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealPattyn(void){
+	
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixCouplingMacAyealPattynViscous();
+	ElementMatrix* Ke2=CreateKMatrixCouplingMacAyealPattynFriction();
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+	
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealPattynViscous{{{1*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealPattynViscous(void){
+
+	/*Constants*/
+	const int numnodes    = 2 *NUMVERTICES;
+	const int numdofm     = NDOF2 *NUMVERTICES2D;
+	const int numdofp     = NDOF2 *NUMVERTICES;
+	const int numdoftotal = 2 *NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int         i,j,ig;
+	double      Jdet;
+	double      viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
+	double      epsilon[5],oldepsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	double      xyz_list[NUMVERTICES][3];
+	double      B[3][numdofp];
+	double      Bprime[3][numdofm];
+	double      D[3][3]={0.0};            // material matrix, simple scalar matrix.
+	double      D_scalar;
+	double      Ke_gg[numdofp][numdofm]={0.0}; //local element stiffness matrix 
+	double      Ke_gg_gaussian[numdofp][numdofm]; //stiffness matrix evaluated at the gaussian point.
+	GaussPenta *gauss=NULL;
+	GaussTria  *gauss_tria=NULL;
+	Node       *node_list[numnodes];
+	int         cs_list[numnodes];
+
+	/*Find penta on bed as pattyn must be coupled to the dofs on the bed: */
+	Penta* pentabase=GetBasalElement();
+	Tria*  tria=pentabase->SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+
+	/*Prepare node list*/
+	for(i=0;i<NUMVERTICES;i++){
+		node_list[i+0*NUMVERTICES] = pentabase->nodes[i];
+		node_list[i+1*NUMVERTICES] = this->nodes[i];
+		cs_list[i+0*NUMVERTICES] = XYEnum;
+		cs_list[i+1*NUMVERTICES] = XYEnum;
+	}
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke1=new ElementMatrix(pentabase->nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
+	ElementMatrix* Ke2=new ElementMatrix(this->nodes     ,NUMVERTICES,this->parameters,PattynApproximationEnum);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+	delete Ke1; delete Ke2;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&viscosity_overshoot,DiagnosticViscosityOvershootEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vxold_input=inputs->GetInput(VxPicardEnum); _assert_(vxold_input);
+	Input* vyold_input=inputs->GetInput(VyPicardEnum); _assert_(vyold_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	gauss_tria=new GaussTria();
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussTria(gauss_tria);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetBMacAyealPattyn(&B[0][0], &xyz_list[0][0], gauss);
+		tria->GetBprimeMacAyeal(&Bprime[0][0], &xyz_list[0][0], gauss_tria);
+
+		this->GetStrainRate3dPattyn(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		this->GetStrainRate3dPattyn(&oldepsilon[0],&xyz_list[0][0],gauss,vxold_input,vyold_input);
+		matice->GetViscosity3d(&viscosity, &epsilon[0]);
+		matice->GetViscosity3d(&oldviscosity, &oldepsilon[0]);
+
+		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		D_scalar=2*newviscosity*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],3,numdofp,1,
+					&D[0][0],3,3,0,
+					&Bprime[0][0],3,numdofm,0,
+					&Ke_gg_gaussian[0][0],0);
+
+		for( i=0; i<numdofp; i++) for(j=0;j<numdofm; j++) Ke_gg[i][j]+=Ke_gg_gaussian[i][j];
+	} 
+	for(i=0;i<numdofp;i++) for(j=0;j<numdofm;j++) Ke->values[(i+2*numdofm)*numdoftotal+j]+=Ke_gg[i][j];
+	for(i=0;i<numdofm;i++) for(j=0;j<numdofp;j++) Ke->values[i*numdoftotal+(j+2*numdofm)]+=Ke_gg[j][i];
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*Clean-up and return*/
+	delete tria->matice; delete tria;
+	delete gauss;
+	delete gauss_tria;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealPattynFriction{{{1*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealPattynFriction(void){
+
+	/*Constants*/
+	const int numnodes    = 2 *NUMVERTICES;
+	const int numdof      = NDOF2 *NUMVERTICES;
+	const int numdoftotal = NDOF4 *NUMVERTICES;
+	
+	/*Intermediaries */
+	int       i,j,ig,analysis_type;
+	double    Jdet2d,slope_magnitude,alpha2;
+	double    xyz_list[NUMVERTICES][3];
+	double    xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	double    slope[3]={0.0,0.0,0.0};
+	double    MAXSLOPE=.06; // 6 %
+	double    MOUNTAINKEXPONENT=10;
+	double    L[2][numdof];
+	double    DL[2][2]                  ={{ 0,0 },{0,0}}; //for basal drag
+	double    DL_scalar;
+	double    Ke_gg[numdof][numdof]     ={0.0};
+	double    Ke_gg_gaussian[numdof][numdof]; //stiffness matrix contribution from drag
+	Friction  *friction = NULL;
+	GaussPenta *gauss=NULL;
+	Node       *node_list[numnodes];
+	int         cs_list[numnodes];
+
+	/*Initialize Element matrix and return if necessary*/
+	if(IsFloating() || !IsOnBed()) return NULL;
+	ElementMatrix* Ke1=new ElementMatrix(nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
+	ElementMatrix* Ke2=new ElementMatrix(nodes,NUMVERTICES,this->parameters,PattynApproximationEnum);
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+	delete Ke1; delete Ke2;
+
+	/*Prepare node list*/
+	for(i=0;i<NUMVERTICES;i++){
+		node_list[i+0*NUMVERTICES] = this->nodes[i];
+		node_list[i+1*NUMVERTICES] = this->nodes[i];
+		cs_list[i+0*NUMVERTICES] = XYEnum;
+		cs_list[i+1*NUMVERTICES] = XYEnum;
+	}
+
+	/*retrieve inputs :*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	Input* surface_input=inputs->GetInput(SurfaceEnum); _assert_(surface_input);
+	Input* vx_input=inputs->GetInput(VxEnum);           _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);           _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);           _assert_(vz_input);
+
+	/*build friction object, used later on: */
+	friction=new Friction("2d",inputs,matpar,analysis_type);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(0,1,2,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/*Friction: */
+		friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum);
+
+		// If we have a slope > 6% for this element,  it means  we are on a mountain. In this particular case, 
+		//velocity should be = 0. To achieve this result, we set alpha2_list to a very high value: */
+		surface_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
+		slope_magnitude=sqrt(pow(slope[0],2)+pow(slope[1],2));
+
+		if (slope_magnitude>MAXSLOPE){
+			alpha2=pow((double)10,MOUNTAINKEXPONENT);
+		}
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		GetL(&L[0][0], gauss,NDOF2);
+
+		DL_scalar=alpha2*gauss->weight*Jdet2d;
+		for (i=0;i<2;i++) DL[i][i]=DL_scalar; 
+		
+		/*  Do the triple producte tL*D*L: */
+		TripleMultiply( &L[0][0],2,numdof,1,
+					&DL[0][0],2,2,0,
+					&L[0][0],2,numdof,0,
+					&Ke_gg_gaussian[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke_gg[i][j]+=Ke_gg_gaussian[i][j];
+	}
+
+	for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdoftotal+(numdof+j)]+=Ke_gg[i][j];
+	for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[(i+numdof)*numdoftotal+j]+=Ke_gg[i][j];
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealStokes{{{1*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealStokes(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixCouplingMacAyealStokesViscous();
+	ElementMatrix* Ke2=CreateKMatrixCouplingMacAyealStokesFriction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealStokesViscous{{{1*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealStokesViscous(void){
+
+	/*Constants*/
+	const int numnodes    = 2 *NUMVERTICES;
+	const int numdofm     = NDOF2 *NUMVERTICES2D;
+	const int numdofs     = NDOF4 *NUMVERTICES;
+	const int numdoftotal = 2 *numdofm+numdofs;
+
+	/*Intermediaries */
+	int         i,j,ig;
+	double      Jdet;
+	double      viscosity,stokesreconditioning; //viscosity
+	double      epsilon[6]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	double      xyz_list[NUMVERTICES][3];
+	double      B[4][numdofs+3];
+	double      Bprime[4][numdofm];
+	double      B2[3][numdofm];
+	double      Bprime2[3][numdofs+3];
+	double      D[4][4]={0.0};            // material matrix, simple scalar matrix.
+	double      D2[3][3]={0.0};            // material matrix, simple scalar matrix.
+	double      D_scalar;
+	double      Ke_gg[numdofs][numdofm]={0.0}; //local element stiffness matrix 
+	double      Ke_gg2[numdofm][numdofs]={0.0}; //local element stiffness matrix 
+	double      Ke_gg_gaussian[numdofs+3][numdofm]; //stiffness matrix evaluated at the gaussian point.
+	double      Ke_gg_gaussian2[numdofm][numdofs+3]; //stiffness matrix evaluated at the gaussian point.
+	GaussPenta *gauss=NULL;
+	GaussTria  *gauss_tria=NULL;
+	Node       *node_list[numnodes];
+	int         cs_list[numnodes];
+
+	/*Find penta on bed as stokes must be coupled to the dofs on the bed: */
+	Penta* pentabase=GetBasalElement();
+	Tria* tria=pentabase->SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+
+	/*Prepare node list*/
+	for(i=0;i<NUMVERTICES;i++){
+		node_list[i+0*NUMVERTICES] = pentabase->nodes[i];
+		node_list[i+1*NUMVERTICES] = this->nodes[i];
+		cs_list[i+0*NUMVERTICES] = XYEnum;
+		cs_list[i+1*NUMVERTICES] = XYZPEnum;
+	}
+
+	/*Initialize Element matrix and return if necessary*/
+	ElementMatrix* Ke1=new ElementMatrix(pentabase->nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
+	ElementMatrix* Ke2=new ElementMatrix(this->nodes     ,NUMVERTICES,this->parameters,StokesApproximationEnum);
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+	delete Ke1; delete Ke2;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);       _assert_(vz_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	gauss_tria=new GaussTria();
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussTria(gauss_tria);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetBMacAyealStokes(&B[0][0], &xyz_list[0][0], gauss);
+		tria->GetBprimeMacAyealStokes(&Bprime[0][0], &xyz_list[0][0], gauss_tria);
+		tria->GetBMacAyealStokes(&B2[0][0], &xyz_list[0][0], gauss_tria);
+		GetBprimeMacAyealStokes(&Bprime2[0][0], &xyz_list[0][0], gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3dStokes(&viscosity, &epsilon[0]);
+
+		D_scalar=2*viscosity*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+		D[3][3]=-gauss->weight*Jdet*stokesreconditioning;
+		for (i=0;i<3;i++) D2[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],4,numdofs+3,1,
+					&D[0][0],4,4,0,
+					&Bprime[0][0],4,numdofm,0,
+					&Ke_gg_gaussian[0][0],0);
+
+		TripleMultiply( &B2[0][0],3,numdofm,1,
+					&D2[0][0],3,3,0,
+					&Bprime2[0][0],3,numdofs+3,0,
+					&Ke_gg_gaussian2[0][0],0);
+
+		for( i=0; i<numdofs; i++) for(j=0;j<numdofm; j++) Ke_gg[i][j]+=Ke_gg_gaussian[i][j];
+		for( i=0; i<numdofm; i++) for(j=0;j<numdofs; j++) Ke_gg2[i][j]+=Ke_gg_gaussian2[i][j];
+	} 
+	for(i=0;i<numdofs;i++) for(j=0;j<numdofm;j++) Ke->values[(i+2*numdofm)*numdoftotal+j]+=Ke_gg[i][j];
+	for(i=0;i<numdofm;i++) for(j=0;j<numdofs;j++) Ke->values[i*numdoftotal+(j+2*numdofm)]+=Ke_gg2[i][j];
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*Clean-up and return*/
+	delete tria->matice; delete tria;
+	delete gauss;
+	delete gauss_tria;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealStokesFriction {{{1*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealStokesFriction(void){
+
+	/*Constants*/
+	const int numnodes  = 2 *NUMVERTICES;
+	const int numdof    = NUMVERTICES *NDOF4;
+	const int numdofm   = NUMVERTICES *NDOF2;
+	const int numdof2d  = NUMVERTICES2D *NDOF4;
+	const int numdof2dm = NUMVERTICES2D *NDOF2;
+	const int numdoftot = numdof+numdofm;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	int        analysis_type,approximation;
+	double     stokesreconditioning;
+	double     viscosity,alpha2_gauss,Jdet2d;
+	double	  bed_normal[3];
+	double     epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	double     xyz_list[NUMVERTICES][3];
+	double	  xyz_list_tria[NUMVERTICES2D][3];
+	double     LMacAyealStokes[8][numdof2dm];
+	double     LprimeMacAyealStokes[8][numdof2d];
+	double     DLMacAyealStokes[8][8]={0.0};
+	double     LStokesMacAyeal[4][numdof2d];
+	double     LprimeStokesMacAyeal[4][numdof2dm];
+	double     DLStokesMacAyeal[4][4]={0.0};
+	double     Ke_drag_gaussian[numdof2dm][numdof2d];
+	double     Ke_drag_gaussian2[numdof2d][numdof2dm];
+	Friction*  friction=NULL;
+	GaussPenta *gauss=NULL;
+	Node       *node_list[numnodes];
+	int         cs_list[numnodes];
+
+	/*If on water or not Stokes, skip stiffness: */
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(IsFloating() || !IsOnBed()) return NULL;
+	ElementMatrix* Ke1=new ElementMatrix(this->nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
+	ElementMatrix* Ke2=new ElementMatrix(this->nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+	delete Ke1; delete Ke2;
+
+	/*Prepare node list*/
+	for(i=0;i<NUMVERTICES;i++){
+		node_list[i+0*NUMVERTICES] = this->nodes[i];
+		node_list[i+1*NUMVERTICES] = this->nodes[i];
+		cs_list[i+0*NUMVERTICES] = XYEnum;
+		cs_list[i+1*NUMVERTICES] = XYZPEnum;
+	}
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum); _assert_(vz_input);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*build friction object, used later on: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(0,1,2,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		GetLMacAyealStokes(&LMacAyealStokes[0][0], gauss);
+		GetLprimeMacAyealStokes(&LprimeMacAyealStokes[0][0], &xyz_list[0][0], gauss);
+		GetLStokesMacAyeal(&LStokesMacAyeal[0][0], gauss);
+		GetLprimeStokesMacAyeal(&LprimeStokesMacAyeal[0][0], &xyz_list[0][0], gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+
+		BedNormal(&bed_normal[0],xyz_list_tria);
+		friction->GetAlpha2(&alpha2_gauss, gauss,VxEnum,VyEnum,VzEnum);
+
+		DLMacAyealStokes[0][0]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLMacAyealStokes[1][1]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLMacAyealStokes[2][2]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[0]*bed_normal[2];
+		DLMacAyealStokes[3][3]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[1]*bed_normal[2];
+		DLMacAyealStokes[4][4]=-2*viscosity*gauss->weight*Jdet2d*bed_normal[0];
+		DLMacAyealStokes[5][5]=-2*viscosity*gauss->weight*Jdet2d*bed_normal[1];
+		DLMacAyealStokes[6][6]=stokesreconditioning*gauss->weight*Jdet2d*bed_normal[0];
+		DLMacAyealStokes[7][7]=stokesreconditioning*gauss->weight*Jdet2d*bed_normal[1];
+
+		DLStokesMacAyeal[0][0]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLStokesMacAyeal[1][1]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLStokesMacAyeal[2][2]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[0]*bed_normal[2];
+		DLStokesMacAyeal[3][3]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[1]*bed_normal[2];
+		
+		TripleMultiply( &LMacAyealStokes[0][0],8,numdof2dm,1,
+					&DLMacAyealStokes[0][0],8,8,0,
+					&LprimeMacAyealStokes[0][0],8,numdof2d,0,
+					&Ke_drag_gaussian[0][0],0);
+
+		TripleMultiply( &LStokesMacAyeal[0][0],4,numdof2d,1,
+					&DLStokesMacAyeal[0][0],4,4,0,
+					&LprimeStokesMacAyeal[0][0],4,numdof2dm,0,
+					&Ke_drag_gaussian2[0][0],0);
+
+		for(i=0;i<numdof2dm;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdoftot+j+numdofm]+=Ke_drag_gaussian[i][j];
+		for(i=0;i<numdof2d;i++) for(j=0;j<numdof2dm;j++) Ke->values[(i+numdofm)*numdoftot+j]+=Ke_drag_gaussian2[i][j];
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingPattynStokes{{{1*/
+ElementMatrix* Penta::CreateKMatrixCouplingPattynStokes(void){
+
+	/*Constants*/
+	const int numnodes  = 2 *NUMVERTICES;
+	const int numdofp     = NDOF2 *NUMVERTICES;
+	const int numdofs     = NDOF4 *NUMVERTICES;
+	const int numdoftotal = (NDOF2+NDOF4) *NUMVERTICES;
+
+	/*Intermediaries*/
+	Node     *node_list[numnodes];
+	int       cs_list[numnodes];
+	int       i,j;
+
+	/*Prepare node list*/
+	for(i=0;i<NUMVERTICES;i++){
+		node_list[i+0*NUMVERTICES] = this->nodes[i];
+		node_list[i+1*NUMVERTICES] = this->nodes[i];
+		cs_list[i+0*NUMVERTICES] = XYEnum;
+		cs_list[i+1*NUMVERTICES] = XYZPEnum;
+	}
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=new ElementMatrix(this->nodes,NUMVERTICES,this->parameters,PattynApproximationEnum);
+	ElementMatrix* Ke2=new ElementMatrix(this->nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+	delete Ke1;
+	delete Ke2;
+	Ke1=CreateKMatrixDiagnosticPattyn(); TransformInvStiffnessMatrixCoord(Ke1,this->nodes,NUMVERTICES,XYEnum);
+	Ke2=CreateKMatrixDiagnosticStokes(); TransformInvStiffnessMatrixCoord(Ke2,this->nodes,NUMVERTICES,XYZPEnum);
+
+	for(i=0;i<numdofs;i++) for(j=0;j<NUMVERTICES;j++){
+		Ke->values[(i+numdofp)*numdoftotal+NDOF2*j+0]+=Ke2->values[i*numdofs+NDOF4*j+0];
+		Ke->values[(i+numdofp)*numdoftotal+NDOF2*j+1]+=Ke2->values[i*numdofs+NDOF4*j+1];
+	}
+	for(i=0;i<numdofp;i++) for(j=0;j<NUMVERTICES;j++){
+		Ke->values[i*numdoftotal+numdofp+NDOF4*j+0]+=Ke1->values[i*numdofp+NDOF2*j+0];
+		Ke->values[i*numdoftotal+numdofp+NDOF4*j+1]+=Ke1->values[i*numdofp+NDOF2*j+1];
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticHoriz {{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case MacAyealApproximationEnum:
+			return CreateKMatrixDiagnosticMacAyeal2d();
+		case PattynApproximationEnum:
+			return CreateKMatrixDiagnosticPattyn();
+		case StokesApproximationEnum:
+			return CreateKMatrixDiagnosticStokes();
+		case HutterApproximationEnum:
+			return NULL;
+		case NoneApproximationEnum:
+			return NULL;
+		case MacAyealPattynApproximationEnum:
+			return CreateKMatrixDiagnosticMacAyealPattyn();
+		case MacAyealStokesApproximationEnum:
+			return CreateKMatrixDiagnosticMacAyealStokes();
+		case PattynStokesApproximationEnum:
+			return CreateKMatrixDiagnosticPattynStokes();
+		default:
+			_error_("Approximation %s not supported yet",EnumToStringx(approximation));
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticHutter{{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticHutter(void){
+
+	/*Constants*/
+	const int numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries*/
+	int       connectivity[2];
+	int       i,i0,i1,j0,j1;
+	double    one0,one1;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Spawn 3 beam elements: */
+	for(i=0;i<3;i++){
+		/*2 dofs of first node*/
+		i0=2*i;
+		i1=2*i+1;
+		/*2 dofs of second node*/
+		j0=2*(i+3);
+		j1=2*(i+3)+1;
+
+		/*Find connectivity for the two nodes*/
+		connectivity[0]=nodes[i]->GetConnectivity();
+		connectivity[1]=nodes[i+3]->GetConnectivity();
+		one0=1/(double)connectivity[0];
+		one1=1/(double)connectivity[1];
+
+		/*Create matrix for these two nodes*/
+		if (IsOnBed() && IsOnSurface()){
+			Ke->values[i0*numdof+i0]=one0;
+			Ke->values[i1*numdof+i1]=one0;
+			Ke->values[j0*numdof+i0]=-one1;
+			Ke->values[j0*numdof+j0]=one1;
+			Ke->values[j1*numdof+i1]=-one1;
+			Ke->values[j1*numdof+j1]=one1;
+		}
+		else if (IsOnBed()){
+			Ke->values[i0*numdof+i0]=one0;
+			Ke->values[i1*numdof+i1]=one0;
+			Ke->values[j0*numdof+i0]=-2*one1;
+			Ke->values[j0*numdof+j0]=2*one1;
+			Ke->values[j1*numdof+i1]=-2*one1;
+			Ke->values[j1*numdof+j1]=2*one1;
+		}
+		else if (IsOnSurface()){
+			Ke->values[j0*numdof+i0]=-one1;
+			Ke->values[j0*numdof+j0]=one1;
+			Ke->values[j1*numdof+i1]=-one1;
+			Ke->values[j1*numdof+j1]=one1;
+		}
+		else{ //node is on two horizontal layers and beams include the values only once, so the have to use half of the connectivity
+			Ke->values[j0*numdof+i0]=-2*one1;
+			Ke->values[j0*numdof+j0]=2*one1;
+			Ke->values[j1*numdof+i1]=-2*one1;
+			Ke->values[j1*numdof+j1]=2*one1;
+		}
+	}
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal2d{{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal2d(void){
+
+	/*Figure out if this penta is collapsed. If so, then bailout, except if it is at the 
+	  bedrock, in which case we spawn a tria element using the 3 first nodes, and use it to build 
+	  the stiffness matrix. */
+	if (!IsOnBed()) return NULL;
+
+	/*Depth Averaging B*/
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixDiagnosticMacAyeal();
+	delete tria->matice; delete tria;
+
+	/*Delete B averaged*/
+	this->matice->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal3d{{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal3d(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyeal3dViscous();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticMacAyeal3dFriction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal3dViscous{{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal3dViscous(void){
+
+	/*Constants*/
+	const int    numdof2d=2*NUMVERTICES2D;
+
+	/*Intermediaries */
+	int         i,j,ig,approximation;
+	double      Jdet;
+	double      viscosity, oldviscosity, newviscosity, viscosity_overshoot;
+	double      epsilon[5],oldepsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	double      epsilons[6]; //6 for stokes
+	double      xyz_list[NUMVERTICES][3];
+	double      B[3][numdof2d];
+	double      Bprime[3][numdof2d];
+	double      D[3][3]={0.0};            // material matrix, simple scalar matrix.
+	double      D_scalar;
+	double      Ke_gg_gaussian[numdof2d][numdof2d]; //stiffness matrix evaluated at the gaussian point.
+	Tria*       tria=NULL;
+	Penta*      pentabase=NULL;
+	GaussPenta *gauss=NULL;
+	GaussTria  *gauss_tria=NULL;
+
+	/*Find penta on bed as this is a macayeal elements: */
+	pentabase=GetBasalElement();
+	tria=pentabase->SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(tria->nodes,NUMVERTICES2D,this->parameters,MacAyealApproximationEnum);
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes,NUMVERTICES);
+	this->parameters->FindParam(&viscosity_overshoot,DiagnosticViscosityOvershootEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vxold_input=inputs->GetInput(VxPicardEnum); _assert_(vxold_input);
+	Input* vyold_input=inputs->GetInput(VyPicardEnum); _assert_(vyold_input);
+	Input* vz_input=inputs->GetInput(VzEnum);       _assert_(vz_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	gauss_tria=new GaussTria();
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussTria(gauss_tria);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		tria->GetBMacAyeal(&B[0][0], &xyz_list[0][0], gauss_tria);
+		tria->GetBprimeMacAyeal(&Bprime[0][0], &xyz_list[0][0], gauss_tria);
+
+		if(approximation==MacAyealPattynApproximationEnum){
+			this->GetStrainRate3dPattyn(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+			this->GetStrainRate3dPattyn(&oldepsilon[0],&xyz_list[0][0],gauss,vxold_input,vyold_input);
+			matice->GetViscosity3d(&viscosity, &epsilon[0]);
+			matice->GetViscosity3d(&oldviscosity, &oldepsilon[0]);
+
+			newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		}
+		else if (approximation==MacAyealStokesApproximationEnum){
+			this->GetStrainRate3d(&epsilons[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+			matice->GetViscosity3dStokes(&newviscosity,&epsilons[0]);
+		}
+		else _error_("approximation %i (%s) not supported yet",approximation,EnumToStringx(approximation));
+
+		D_scalar=2*newviscosity*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],3,numdof2d,1,
+					&D[0][0],3,3,0,
+					&Bprime[0][0],3,numdof2d,0,
+					&Ke_gg_gaussian[0][0],0);
+
+		for(i=0;i<numdof2d;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdof2d+j]+=Ke_gg_gaussian[i][j];
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,tria->nodes,NUMVERTICES2D,XYEnum);
+
+	/*Clean up and return*/
+	delete tria->matice;
+	delete tria;
+	delete gauss_tria;
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal3dFriction{{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal3dFriction(void){
+
+	/*Initialize Element matrix and return if necessary*/
+	if(IsFloating() || !IsOnBed()) return NULL;
+
+	/*Build a tria element using the 3 nodes of the base of the penta. Then use 
+	 * the tria functionality to build a friction stiffness matrix on these 3
+	 * nodes: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixDiagnosticMacAyealFriction();
+	delete tria->matice; delete tria;
+
+	/*clean-up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyealPattyn{{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyealPattyn(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyeal3d();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticPattyn();
+	ElementMatrix* Ke3=CreateKMatrixCouplingMacAyealPattyn();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyealStokes{{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyealStokes(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyeal3d();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticStokes();
+	ElementMatrix* Ke3=CreateKMatrixCouplingMacAyealStokes();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticPattyn{{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticPattyn(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticPattynViscous();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticPattynFriction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticPattynViscous{{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticPattynViscous(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	int        approximation;
+	double     xyz_list[NUMVERTICES][3];
+	double     Jdet;
+	double     viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
+	double     epsilon[5],oldepsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	double     D_scalar;
+	double     D[5][5]={0.0};            // material matrix, simple scalar matrix.
+	double     B[5][numdof];
+	double     Bprime[5][numdof];
+	Tria*      tria=NULL;
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,PattynApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&viscosity_overshoot,DiagnosticViscosityOvershootEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vxold_input=inputs->GetInput(VxPicardEnum); _assert_(vxold_input);
+	Input* vyold_input=inputs->GetInput(VyPicardEnum); _assert_(vyold_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetBPattyn(&B[0][0], &xyz_list[0][0], gauss);
+		GetBprimePattyn(&Bprime[0][0], &xyz_list[0][0], gauss);
+
+		this->GetStrainRate3dPattyn(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		this->GetStrainRate3dPattyn(&oldepsilon[0],&xyz_list[0][0],gauss,vxold_input,vyold_input);
+		matice->GetViscosity3d(&viscosity, &epsilon[0]);
+		matice->GetViscosity3d(&oldviscosity, &oldepsilon[0]);
+		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+
+		D_scalar=2*newviscosity*gauss->weight*Jdet;
+		for (i=0;i<5;i++) D[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],5,numdof,1,
+					&D[0][0],5,5,0,
+					&Bprime[0][0],5,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticPattynFriction{{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticPattynFriction(void){
+
+	/*Constants*/
+	const int numdof   = NDOF2*NUMVERTICES;
+	
+	/*Intermediaries */
+	int       i,j,ig;
+	int       analysis_type;
+	double    xyz_list[NUMVERTICES][3];
+	double    xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	double    slope_magnitude,alpha2,Jdet;
+	double    slope[3]={0.0,0.0,0.0};
+	double    MAXSLOPE=.06; // 6 %
+	double    MOUNTAINKEXPONENT=10;
+	double    L[2][numdof];
+	double    DL[2][2]={{ 0,0 },{0,0}}; //for basal drag
+	double    DL_scalar;
+	Friction  *friction = NULL;
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(IsFloating() || !IsOnBed()) return NULL;
+
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,PattynApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	Input* surface_input=inputs->GetInput(SurfaceEnum); _assert_(surface_input);
+	Input* vx_input=inputs->GetInput(VxEnum);           _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);           _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);           _assert_(vz_input);
+
+	/*build friction object, used later on: */
+	friction=new Friction("2d",inputs,matpar,analysis_type);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(0,1,2,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet, &xyz_list_tria[0][0],gauss);
+		GetL(&L[0][0], gauss,NDOF2);
+
+		surface_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
+		friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum); 
+		slope_magnitude=sqrt(pow(slope[0],2)+pow(slope[1],2));
+
+		// If we have a slope > 6% for this element,  it means  we are on a mountain. In this particular case, 
+		//velocity should be = 0. To achieve this result, we set alpha2_list to a very high value: */
+		if (slope_magnitude>MAXSLOPE){
+			alpha2=pow((double)10,MOUNTAINKEXPONENT);
+		}
+		
+		DL_scalar=alpha2*gauss->weight*Jdet;
+		for (i=0;i<2;i++) DL[i][i]=DL_scalar;
+		
+		TripleMultiply( &L[0][0],2,numdof,1,
+					&DL[0][0],2,2,0,
+					&L[0][0],2,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticPattynStokes{{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticPattynStokes(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticPattyn();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticStokes();
+	ElementMatrix* Ke3=CreateKMatrixCouplingPattynStokes();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticStokes{{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticStokes(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticStokesViscous();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticStokesFriction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticStokesViscous {{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticStokesViscous(void){
+
+	/*Intermediaries */
+	int        i,j,ig,approximation;
+	double     Jdet,viscosity,stokesreconditioning;
+	double     xyz_list[NUMVERTICES][3];
+	double     epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	double     B[8][27];
+	double     B_prime[8][27];
+	double     D_scalar;
+	double     D[8][8]={0.0};
+	double     Ke_temp[27][27]={0.0}; //for the six nodes and the bubble 
+	GaussPenta *gauss=NULL;
+
+	/*If on water or not Stokes, skip stiffness: */
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=StokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum && approximation!=PattynStokesApproximationEnum) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum); _assert_(vz_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetBStokes(&B[0][0],&xyz_list[0][0],gauss); 
+		GetBprimeStokes(&B_prime[0][0],&xyz_list[0][0],gauss); 
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+
+		D_scalar=gauss->weight*Jdet;
+		for (i=0;i<6;i++) D[i][i]=D_scalar*2*viscosity;
+		for (i=6;i<8;i++) D[i][i]=-D_scalar*stokesreconditioning;
+
+		TripleMultiply( &B[0][0],8,27,1,
+					&D[0][0],8,8,0,
+					&B_prime[0][0],8,27,0,
+					&Ke_temp[0][0],1);
+	}
+
+	/*Condensation*/
+	ReduceMatrixStokes(Ke->values, &Ke_temp[0][0]);
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticStokesFriction{{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticStokesFriction(void){
+
+	/*Constants*/
+	const int numdof=NUMVERTICES*NDOF4;
+	const int numdof2d=NUMVERTICES2D*NDOF4;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	int        analysis_type,approximation;
+	double     alpha2,Jdet2d;
+	double     stokesreconditioning,viscosity;
+	double     epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	double     xyz_list[NUMVERTICES][3];
+	double	  xyz_list_tria[NUMVERTICES2D][3];
+	double     LStokes[2][numdof2d];
+	double     DLStokes[2][2]={0.0};
+	double     Ke_drag_gaussian[numdof2d][numdof2d];
+	Friction*  friction=NULL;
+	GaussPenta *gauss=NULL;
+
+	/*If on water or not Stokes, skip stiffness: */
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(IsFloating() || !IsOnBed() || (approximation!=StokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum &&  approximation!=PattynStokesApproximationEnum)) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum); _assert_(vz_input);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*build friction object, used later on: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(0,1,2,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		GetLStokes(&LStokes[0][0], gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+
+		friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum);
+
+		DLStokes[0][0] = +alpha2*gauss->weight*Jdet2d; //taub_x = -alpha2 vx
+		DLStokes[1][1] = +alpha2*gauss->weight*Jdet2d; //taub_y = -alpha2 vy
+
+		TripleMultiply( &LStokes[0][0],2,numdof2d,1,
+					&DLStokes[0][0],2,2,0,
+					&LStokes[0][0],2,numdof2d,0,
+					&Ke_drag_gaussian[0][0],0);
+
+		for(i=0;i<numdof2d;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdof+j]+=Ke_drag_gaussian[i][j];
+	}
+
+	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
+	//TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+	
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticVert {{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticVert(void){
+	
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticVertVolume();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticVertSurface();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticVertVolume {{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticVertVolume(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int         i,j,ig;
+	double      Jdet;
+	double      xyz_list[NUMVERTICES][3];
+	double      B[NDOF1][NUMVERTICES];
+	double      Bprime[NDOF1][NUMVERTICES];
+	double      DL_scalar;
+	GaussPenta  *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetBVert(&B[0][0], &xyz_list[0][0], gauss);
+		GetBprimeVert(&Bprime[0][0], &xyz_list[0][0], gauss);
+
+		DL_scalar=gauss->weight*Jdet;
+
+		TripleMultiply( &B[0][0],1,NUMVERTICES,1,
+					&DL_scalar,1,1,0,
+					&Bprime[0][0],1,NUMVERTICES,0,
+					&Ke->values[0],1);
+	} 
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticVertSurface {{{1*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticVertSurface(void){
+
+	if (!IsOnSurface()) return NULL;
+
+	/*Constants*/
+	const int numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int       i,j,ig;
+	double    xyz_list[NUMVERTICES][3];
+	double    xyz_list_tria[NUMVERTICES2D][3];
+	double    surface_normal[3];
+	double    Jdet2d,DL_scalar;
+	double    basis[NUMVERTICES];
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i+3][j];
+	SurfaceNormal(&surface_normal[0],xyz_list_tria);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(3,4,5,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+		DL_scalar= - gauss->weight*Jdet2d*surface_normal[2]; 
+
+		TripleMultiply( basis,1,numdof,1,
+					&DL_scalar,1,1,0,
+					basis,1,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingMacAyealStokes {{{1*/
+ElementVector* Penta::CreatePVectorCouplingMacAyealStokes(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorCouplingMacAyealStokesViscous();
+	ElementVector* pe2=CreatePVectorCouplingMacAyealStokesFriction();
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingMacAyealStokesViscous {{{1*/
+ElementVector* Penta::CreatePVectorCouplingMacAyealStokesViscous(void){
+
+	/*Constants*/
+	const int   numdof=NUMVERTICES*NDOF4;
+
+	/*Intermediaries */
+	int         i,j,ig;
+	int         approximation;
+	double      viscosity,Jdet;
+	double      stokesreconditioning;
+	double      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	double      dw[3];
+	double      xyz_list[NUMVERTICES][3];
+	double      basis[6]; //for the six nodes of the penta
+	double      dbasis[3][6]; //for the six nodes of the penta
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element vector and return if necessary*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=MacAyealStokesApproximationEnum) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);               _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);               _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);               _assert_(vz_input);
+	Input* vzmacayeal_input=inputs->GetInput(VzMacAyealEnum);   _assert_(vzmacayeal_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+		GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+
+		vzmacayeal_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+
+		for(i=0;i<NUMVERTICES;i++){
+			pe->values[i*NDOF4+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
+			pe->values[i*NDOF4+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
+			pe->values[i*NDOF4+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
+			pe->values[i*NDOF4+3]+=Jdet*gauss->weight*stokesreconditioning*dw[2]*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingMacAyealStokesFriction{{{1*/
+ElementVector* Penta::CreatePVectorCouplingMacAyealStokesFriction(void){
+
+	/*Constants*/
+	const int numdof=NUMVERTICES*NDOF4;
+
+	/*Intermediaries*/
+	int         i,j,ig;
+	int         approximation,analysis_type;
+	double      Jdet,Jdet2d;
+	double      stokesreconditioning;
+	double	   bed_normal[3];
+	double      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	double      viscosity, w, alpha2_gauss;
+	double      dw[3];
+	double	   xyz_list_tria[NUMVERTICES2D][3];
+	double      xyz_list[NUMVERTICES][3];
+	double      basis[6]; //for the six nodes of the penta
+	Tria*       tria=NULL;
+	Friction*   friction=NULL;
+	GaussPenta  *gauss=NULL;
+
+	/*Initialize Element vector and return if necessary*/
+	if(!IsOnBed() || IsFloating()) return NULL;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=MacAyealStokesApproximationEnum) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);               _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);               _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);               _assert_(vz_input);
+	Input* vzmacayeal_input=inputs->GetInput(VzMacAyealEnum);   _assert_(vzmacayeal_input);
+
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*build friction object, used later on: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		vzmacayeal_input->GetInputValue(&w, gauss);
+		vzmacayeal_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
+
+		BedNormal(&bed_normal[0],xyz_list_tria);
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		friction->GetAlpha2(&alpha2_gauss, gauss,VxEnum,VyEnum,VzEnum);
+
+		for(i=0;i<NUMVERTICES2D;i++){
+			pe->values[i*NDOF4+0]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[0]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[0])*basis[i];
+			pe->values[i*NDOF4+1]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[1]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[1])*basis[i];
+			pe->values[i*NDOF4+2]+=Jdet2d*gauss->weight*2*viscosity*(dw[0]*bed_normal[0]+dw[1]*bed_normal[1]+dw[2]*bed_normal[2])*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingPattynStokes {{{1*/
+ElementVector* Penta::CreatePVectorCouplingPattynStokes(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorCouplingPattynStokesViscous();
+	ElementVector* pe2=CreatePVectorCouplingPattynStokesFriction();
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingPattynStokesViscous {{{1*/
+ElementVector* Penta::CreatePVectorCouplingPattynStokesViscous(void){
+
+	/*Constants*/
+	const int   numdof=NUMVERTICES*NDOF4;
+
+	/*Intermediaries */
+	int         i,j,ig;
+	int         approximation;
+	double      viscosity,Jdet;
+	double      stokesreconditioning;
+	double      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	double      dw[3];
+	double      xyz_list[NUMVERTICES][3];
+	double      basis[6]; //for the six nodes of the penta
+	double      dbasis[3][6]; //for the six nodes of the penta
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element vector and return if necessary*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=PattynStokesApproximationEnum) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);               _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);               _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);               _assert_(vz_input);
+	Input* vzpattyn_input=inputs->GetInput(VzPattynEnum);   _assert_(vzpattyn_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+		GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+
+		vzpattyn_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+
+		for(i=0;i<NUMVERTICES;i++){
+			pe->values[i*NDOF4+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
+			pe->values[i*NDOF4+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
+			pe->values[i*NDOF4+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
+			pe->values[i*NDOF4+3]+=Jdet*gauss->weight*stokesreconditioning*dw[2]*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingPattynStokesFriction{{{1*/
+ElementVector* Penta::CreatePVectorCouplingPattynStokesFriction(void){
+
+	/*Constants*/
+	const int numdof=NUMVERTICES*NDOF4;
+
+	/*Intermediaries*/
+	int         i,j,ig;
+	int         approximation,analysis_type;
+	double      Jdet,Jdet2d;
+	double      stokesreconditioning;
+	double	   bed_normal[3];
+	double      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	double      viscosity, w, alpha2_gauss;
+	double      dw[3];
+	double	   xyz_list_tria[NUMVERTICES2D][3];
+	double      xyz_list[NUMVERTICES][3];
+	double      basis[6]; //for the six nodes of the penta
+	Tria*       tria=NULL;
+	Friction*   friction=NULL;
+	GaussPenta  *gauss=NULL;
+
+	/*Initialize Element vector and return if necessary*/
+	if(!IsOnBed() || IsFloating()) return NULL;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=PattynStokesApproximationEnum) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);               _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);               _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);               _assert_(vz_input);
+	Input* vzpattyn_input=inputs->GetInput(VzPattynEnum);   _assert_(vzpattyn_input);
+
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*build friction object, used later on: */
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		vzpattyn_input->GetInputValue(&w, gauss);
+		vzpattyn_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
+
+		BedNormal(&bed_normal[0],xyz_list_tria);
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		friction->GetAlpha2(&alpha2_gauss, gauss,VxEnum,VyEnum,VzEnum);
+
+		for(i=0;i<NUMVERTICES2D;i++){
+			pe->values[i*NDOF4+0]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[0]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[0])*basis[i];
+			pe->values[i*NDOF4+1]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[1]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[1])*basis[i];
+			pe->values[i*NDOF4+2]+=Jdet2d*gauss->weight*2*viscosity*(dw[0]*bed_normal[0]+dw[1]*bed_normal[1]+dw[2]*bed_normal[2])*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticHoriz{{{1*/
+ElementVector* Penta::CreatePVectorDiagnosticHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case MacAyealApproximationEnum:
+			return CreatePVectorDiagnosticMacAyeal();
+		case PattynApproximationEnum:
+			return CreatePVectorDiagnosticPattyn();
+		case HutterApproximationEnum:
+			return NULL;
+		case NoneApproximationEnum:
+			return NULL;
+		case StokesApproximationEnum:
+			return CreatePVectorDiagnosticStokes();
+		case MacAyealPattynApproximationEnum:
+			return CreatePVectorDiagnosticMacAyealPattyn();
+		case MacAyealStokesApproximationEnum:
+			return CreatePVectorDiagnosticMacAyealStokes();
+		case PattynStokesApproximationEnum:
+			return CreatePVectorDiagnosticPattynStokes();
+		default:
+			_error_("Approximation %s not supported yet",EnumToStringx(approximation));
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticMacAyealPattyn{{{1*/
+ElementVector* Penta::CreatePVectorDiagnosticMacAyealPattyn(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorDiagnosticMacAyeal();
+	ElementVector* pe2=CreatePVectorDiagnosticPattyn();
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticMacAyealStokes{{{1*/
+ElementVector* Penta::CreatePVectorDiagnosticMacAyealStokes(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorDiagnosticMacAyeal();
+	ElementVector* pe2=CreatePVectorDiagnosticStokes();
+	ElementVector* pe3=CreatePVectorCouplingMacAyealStokes();
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticPattynStokes{{{1*/
+ElementVector* Penta::CreatePVectorDiagnosticPattynStokes(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorDiagnosticPattyn();
+	ElementVector* pe2=CreatePVectorDiagnosticStokes();
+	ElementVector* pe3=CreatePVectorCouplingPattynStokes();
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticHutter{{{1*/
+ElementVector* Penta::CreatePVectorDiagnosticHutter(void){
+
+	/*Constants*/
+	const int numdofs=NDOF2*NUMVERTICES;
+
+	/*Intermediaries*/
+	int          i,j,k,ig;
+	int          node0,node1;
+	int          connectivity[2];
+	double       Jdet;
+	double       xyz_list[NUMVERTICES][3];
+	double       xyz_list_segment[2][3];
+	double       z_list[NUMVERTICES];
+	double       z_segment[2],slope[2];
+	double       slope2,constant_part;
+	double       rho_ice,gravity,n,B;
+	double       ub,vb,z_g,surface,thickness;
+	GaussPenta*  gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+	n=matice->GetN();
+	B=matice->GetB();
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);  _assert_(thickness_input);
+	Input* surface_input=inputs->GetInput(SurfaceEnum);      _assert_(surface_input);
+	Input* slopex_input=inputs->GetInput(SurfaceSlopeXEnum); _assert_(slopex_input);
+	Input* slopey_input=inputs->GetInput(SurfaceSlopeYEnum); _assert_(slopey_input);
+	for(i=0;i<NUMVERTICES;i++)z_list[i]=xyz_list[i][2];
+
+	/*Loop on the three segments*/
+	for(i=0;i<3;i++){
+		node0=i;
+		node1=i+3;
+
+		for(j=0;j<3;j++){
+			xyz_list_segment[0][j]=xyz_list[node0][j];
+			xyz_list_segment[1][j]=xyz_list[node1][j];
+		}
+
+		connectivity[0]=nodes[node0]->GetConnectivity();
+		connectivity[1]=nodes[node1]->GetConnectivity();
+
+		/*Loop on the Gauss points: */
+		gauss=new GaussPenta(node0,node1,3);
+		for(ig=gauss->begin();ig<gauss->end();ig++){
+			gauss->GaussPoint(ig);
+
+			slopex_input->GetInputValue(&slope[0],gauss);
+			slopey_input->GetInputValue(&slope[1],gauss);
+			surface_input->GetInputValue(&surface,gauss);
+			thickness_input->GetInputValue(&thickness,gauss);
+
+			slope2=pow(slope[0],2)+pow(slope[1],2);
+			constant_part=-2*pow(rho_ice*gravity,n)*pow(slope2,((n-1)/2));
+
+			PentaRef::GetInputValue(&z_g,&z_list[0],gauss);
+			GetSegmentJacobianDeterminant(&Jdet,&xyz_list_segment[0][0],gauss);
+
+			if (IsOnSurface()){
+				for(j=0;j<NDOF2;j++) pe->values[2*node1+j]+=constant_part*pow((surface-z_g)/B,n)*slope[j]*Jdet*gauss->weight/(double)connectivity[1];
+			}
+			else{//connectivity is too large, should take only half on it
+				for(j=0;j<NDOF2;j++) pe->values[2*node1+j]+=constant_part*pow((surface-z_g)/B,n)*slope[j]*Jdet*gauss->weight*2/(double)connectivity[1];
+			}
+		}
+		delete gauss;
+
+		//Deal with lower surface
+		if (IsOnBed()){
+			constant_part=-1.58*pow((double)10.0,-(double)10.0)*rho_ice*gravity*thickness;
+			ub=constant_part*slope[0];
+			vb=constant_part*slope[1];
+
+			pe->values[2*node0]+=ub/(double)connectivity[0];
+			pe->values[2*node0+1]+=vb/(double)connectivity[0];
+		}
+	}
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticMacAyeal{{{1*/
+ElementVector* Penta::CreatePVectorDiagnosticMacAyeal(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorDiagnosticMacAyeal();
+	delete tria->matice; delete tria;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticPattyn{{{1*/
+ElementVector* Penta::CreatePVectorDiagnosticPattyn(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries*/
+	int         i,j,ig;
+	double      Jdet;
+	double      slope[3]; //do not put 2! this goes into GetInputDerivativeValue, which addresses slope[3] also!
+	double      driving_stress_baseline,thickness;
+	double      xyz_list[NUMVERTICES][3];
+	double      basis[6];
+	GaussPenta  *gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,PattynApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* surface_input=inputs->GetInput(SurfaceEnum);     _assert_(surface_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,3);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		thickness_input->GetInputValue(&thickness, gauss);
+		surface_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
+
+		driving_stress_baseline=matpar->GetRhoIce()*matpar->GetG();
+
+		for(i=0;i<NUMVERTICES;i++) for(j=0;j<NDOF2;j++) pe->values[i*NDOF2+j]+= -driving_stress_baseline*slope[j]*Jdet*gauss->weight*basis[i];
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticStokes {{{1*/
+ElementVector* Penta::CreatePVectorDiagnosticStokes(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorDiagnosticStokesViscous();
+	ElementVector* pe2=CreatePVectorDiagnosticStokesShelf();
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticStokesViscous {{{1*/
+ElementVector* Penta::CreatePVectorDiagnosticStokesViscous(void){
+
+	/*Constants*/
+	const int numdofbubble=NDOF4*NUMVERTICES+NDOF3*1;
+
+	/*Intermediaries*/
+	int        i,j,ig;
+	int        approximation;
+	double     Jdet,viscosity;
+	double     gravity,rho_ice,stokesreconditioning;
+	double     xyz_list[NUMVERTICES][3];
+	double     epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	double     l1l7[7]; //for the six nodes and the bubble 
+	double     B[8][numdofbubble];
+	double     B_prime[8][numdofbubble];
+	double     B_prime_bubble[8][3];
+	double     D[8][8]={0.0};
+	double     D_scalar;
+	double     Pe_gaussian[numdofbubble]={0.0}; //for the six nodes and the bubble 
+	double     Ke_temp[numdofbubble][3]={0.0}; //for the six nodes and the bubble 
+	double     Ke_gaussian[numdofbubble][3];
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element vector and return if necessary*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=StokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum && approximation!=PattynStokesApproximationEnum) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* vx_input=inputs->GetInput(VxEnum);   _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);   _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);   _assert_(vz_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetBStokes(&B[0][0],&xyz_list[0][0],gauss); 
+		GetBprimeStokes(&B_prime[0][0],&xyz_list[0][0], gauss); 
+		GetNodalFunctionsMINI(&l1l7[0], gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+
+		for(i=0;i<NUMVERTICES+1;i++){
+			Pe_gaussian[i*NDOF4+2]+=-rho_ice*gravity*Jdet*gauss->weight*l1l7[i];
+		}
+
+		/*Get bubble part of Bprime */
+		for(i=0;i<8;i++) for(j=0;j<3;j++) B_prime_bubble[i][j]=B_prime[i][j+24];
+
+		D_scalar=gauss->weight*Jdet;
+		for (i=0;i<6;i++) D[i][i]=D_scalar*2*viscosity;
+		for (i=6;i<8;i++) D[i][i]=-D_scalar*stokesreconditioning;
+
+		TripleMultiply(&B[0][0],8,numdofbubble,1,
+					&D[0][0],8,8,0,
+					&B_prime_bubble[0][0],8,3,0,
+					&Ke_temp[0][0],1);
+	}
+
+	/*Condensation*/
+	ReduceVectorStokes(pe->values, &Ke_temp[0][0], &Pe_gaussian[0]);
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticStokesShelf{{{1*/
+ElementVector* Penta::CreatePVectorDiagnosticStokesShelf(void){
+
+	/*Intermediaries*/
+	int         i,j,ig;
+	int         approximation,shelf_dampening;
+	double      gravity,rho_water,bed,water_pressure;
+	double      damper,normal_vel,vx,vy,vz,dt;
+	double		xyz_list_tria[NUMVERTICES2D][3];
+	double      xyz_list[NUMVERTICES][3];
+	double		bed_normal[3];
+	double      dz[3];
+	double      basis[6]; //for the six nodes of the penta
+	double      Jdet2d;
+	GaussPenta  *gauss=NULL;
+
+	/*Initialize Element vector and return if necessary*/
+	if(!IsOnBed() || !IsFloating()) return NULL;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	this->parameters->FindParam(&shelf_dampening,DiagnosticShelfDampeningEnum);
+	if(approximation!=StokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum && approximation!=PattynStokesApproximationEnum) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	rho_water=matpar->GetRhoWater();
+	gravity=matpar->GetG();
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* bed_input=inputs->GetInput(BedEnum); _assert_(bed_input);
+	Input* vx_input=inputs->GetInput(VxEnum);   _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);   _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);   _assert_(vz_input);
+
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	gauss=new GaussPenta(0,1,2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		BedNormal(&bed_normal[0],xyz_list_tria);
+		bed_input->GetInputValue(&bed, gauss);
+		if(shelf_dampening){ //add dampening to avoid too high vertical velocities when not in hydrostatic equilibrium
+			bed_input->GetInputDerivativeValue(&dz[0],&xyz_list[0][0],gauss);
+			vx_input->GetInputValue(&vx, gauss);
+			vy_input->GetInputValue(&vy, gauss);
+			vz_input->GetInputValue(&vz, gauss);
+			dt=0;
+			normal_vel=bed_normal[0]*vx+bed_normal[1]*vy+bed_normal[2]*vz;
+			damper=gravity*rho_water*pow(1+pow(dz[0],2)+pow(dz[1],2),0.5)*normal_vel*dt;
+		}
+		else damper=0;
+		water_pressure=gravity*rho_water*bed;
+
+		for(i=0;i<NUMVERTICES;i++) for(j=0;j<3;j++) pe->values[i*NDOF4+j]+=(water_pressure+damper)*gauss->weight*Jdet2d*basis[i]*bed_normal[j];
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticVert {{{1*/
+ElementVector* Penta::CreatePVectorDiagnosticVert(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorDiagnosticVertVolume();
+	ElementVector* pe2=CreatePVectorDiagnosticVertBase();
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticVertVolume {{{1*/
+ElementVector* Penta::CreatePVectorDiagnosticVertVolume(void){
+
+	/*Constants*/
+	const int  numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries*/
+	int        i,ig;
+	int        approximation;
+	double     Jdet;
+	double     xyz_list[NUMVERTICES][3];
+	double     dudx,dvdy,dwdz;
+	double     du[3],dv[3],dw[3];
+	double     basis[6];
+	GaussPenta *gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	Input* vzstokes_input=NULL;
+	if(approximation==PattynStokesApproximationEnum || approximation==MacAyealStokesApproximationEnum){
+		vzstokes_input=inputs->GetInput(VzStokesEnum); _assert_(vzstokes_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsP1(basis, gauss);
+
+		vx_input->GetInputDerivativeValue(&du[0],&xyz_list[0][0],gauss);
+		vy_input->GetInputDerivativeValue(&dv[0],&xyz_list[0][0],gauss);
+		if(approximation==PattynStokesApproximationEnum || approximation==MacAyealStokesApproximationEnum){
+			vzstokes_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
+			dwdz=dw[2];
+		}
+		else dwdz=0;
+		dudx=du[0];
+		dvdy=dv[1];
+
+		for (i=0;i<numdof;i++) pe->values[i] += (dudx+dvdy+dwdz)*Jdet*gauss->weight*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticVertBase {{{1*/
+ElementVector* Penta::CreatePVectorDiagnosticVertBase(void){
+
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	int        approximation;
+	double     xyz_list[NUMVERTICES][3];
+	double     xyz_list_tria[NUMVERTICES2D][3];
+	double     Jdet2d;
+	double     vx,vy,vz,dbdx,dbdy,basalmeltingvalue;
+	double     slope[3];
+	double     basis[NUMVERTICES];
+	GaussPenta* gauss=NULL;
+
+	if (!IsOnBed()) return NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	Input* bed_input=inputs->GetInput(BedEnum);                                _assert_(bed_input);
+	Input* basal_melting_input=inputs->GetInput(BasalforcingsMeltingRateEnum); _assert_(basal_melting_input);
+	Input* vx_input=inputs->GetInput(VxEnum);                                  _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                                  _assert_(vy_input);
+	Input* vzstokes_input=NULL;
+	if(approximation==PattynStokesApproximationEnum || approximation==MacAyealStokesApproximationEnum){
+		vzstokes_input=inputs->GetInput(VzStokesEnum);       _assert_(vzstokes_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(0,1,2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		basal_melting_input->GetInputValue(&basalmeltingvalue, gauss);
+		bed_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
+		vx_input->GetInputValue(&vx, gauss);
+		vy_input->GetInputValue(&vy, gauss);
+		if(approximation==PattynStokesApproximationEnum || approximation==MacAyealStokesApproximationEnum){
+			vzstokes_input->GetInputValue(&vz, gauss);
+		}
+		else vz=0;
+
+		dbdx=slope[0];
+		dbdy=slope[1];
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		GetNodalFunctionsP1(&basis[0], gauss);
+
+		for(i=0;i<numdof;i++) pe->values[i]+=-Jdet2d*gauss->weight*(vx*dbdx+vy*dbdy-vz-basalmeltingvalue)*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsDiagnosticHoriz{{{1*/
+void  Penta::GetSolutionFromInputsDiagnosticHoriz(Vec solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int          i;
+	int          approximation;
+	int*         doflist=NULL;
+	double       vx,vy;
+	double       values[numdof];
+	GaussPenta*  gauss;
+
+	/*Get approximation enum and dof list: */
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+
+	/*If the element is a coupling, do nothing: every node is also on an other elements 
+	 * (as coupling is between MacAyeal and Pattyn) so the other element will take care of it*/
+	GetDofList(&doflist,approximation,GsetEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	/*P1 element only for now*/
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+
+		/*Recover vx and vy*/
+		gauss->GaussVertex(i);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		values[i*NDOF2+0]=vx;
+		values[i*NDOF2+1]=vy;
+	}
+
+	/*Add value to global vector*/
+	VecSetValues(solution,numdof,doflist,(const double*)values,INSERT_VALUES);
+
+	/*Free ressources:*/
+	delete gauss;
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsDiagnosticHutter{{{1*/
+void  Penta::GetSolutionFromInputsDiagnosticHutter(Vec solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	double       vx,vy;
+	double       values[numdof];
+	GaussPenta*  gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	/*P1 element only for now*/
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		/*Recover vx and vy*/
+		gauss->GaussVertex(i);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		values[i*NDOF2+0]=vx;
+		values[i*NDOF2+1]=vy;
+	}
+
+	/*Add value to global vector*/
+	VecSetValues(solution,numdof,doflist,(const double*)values,INSERT_VALUES);
+
+	/*Free ressources:*/
+	delete gauss;
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsDiagnosticVert{{{1*/
+void  Penta::GetSolutionFromInputsDiagnosticVert(Vec solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	double       vz;
+	double       values[numdof];
+	GaussPenta*  gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* vz_input=inputs->GetInput(VzEnum); _assert_(vz_input);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	/*P1 element only for now*/
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		/*Recover vz */
+		gauss->GaussVertex(i);
+		vz_input->GetInputValue(&vz,gauss);
+		values[i]=vz;
+	}
+
+	/*Add value to global vector*/
+	VecSetValues(solution,numdof,doflist,(const double*)values,INSERT_VALUES);
+
+	/*Free ressources:*/
+	delete gauss;
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsDiagnosticStokes{{{1*/
+void  Penta::GetSolutionFromInputsDiagnosticStokes(Vec solution){
+
+	const int    numdof=NDOF4*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	double       vx,vy,vz,p;
+	double       stokesreconditioning;
+	double       values[numdof];
+	GaussPenta   *gauss;
+
+	/*Get dof list: */
+	GetDofList(&doflist,StokesApproximationEnum,GsetEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);       _assert_(vz_input);
+	Input* p_input =inputs->GetInput(PressureEnum); _assert_(p_input);
+
+	/*Recondition pressure: */
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+
+	/*Ok, we have vx vy vz and P in values, fill in vx vy vz P arrays: */
+	/*P1 element only for now*/
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		gauss->GaussVertex(i);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vz_input->GetInputValue(&vz,gauss);
+		p_input ->GetInputValue(&p ,gauss);
+		values[i*NDOF4+0]=vx;
+		values[i*NDOF4+1]=vy;
+		values[i*NDOF4+2]=vz;
+		values[i*NDOF4+3]=p/stokesreconditioning;
+	}
+
+	/*Add value to global vector*/
+	VecSetValues(solution,numdof,doflist,(const double*)values,INSERT_VALUES);
+
+	/*Free ressources:*/
+	delete gauss;
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticHoriz {{{1*/
+void  Penta::InputUpdateFromSolutionDiagnosticHoriz(double* solution){
+
+	int  approximation;
+
+	/*Recover inputs*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*MacAyeal, everything is done by the element on bed*/
+	if (approximation==MacAyealApproximationEnum){
+		if (!IsOnBed()){
+			/*Do nothing. Element on bed will take care of it*/
+			return;
+		}
+		else{
+			InputUpdateFromSolutionDiagnosticMacAyeal(solution);
+			return;
+		}
+	}
+	else if (approximation==PattynApproximationEnum){
+		InputUpdateFromSolutionDiagnosticPattyn(solution);
+	}
+	else if (approximation==PattynStokesApproximationEnum){
+		InputUpdateFromSolutionDiagnosticPattynStokes(solution);
+	}
+	else if (approximation==MacAyealStokesApproximationEnum){
+		InputUpdateFromSolutionDiagnosticMacAyealStokes(solution);
+	}
+	else if (approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
+		InputUpdateFromSolutionDiagnosticStokes(solution);
+	}
+	else if (approximation==MacAyealPattynApproximationEnum){
+		InputUpdateFromSolutionDiagnosticMacAyealPattyn(solution);
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticMacAyeal {{{1*/
+void  Penta::InputUpdateFromSolutionDiagnosticMacAyeal(double* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int     i;
+	double  rho_ice,g;
+	double  values[numdof];
+	double  vx[NUMVERTICES];
+	double  vy[NUMVERTICES];
+	double  vz[NUMVERTICES];
+	double  vel[NUMVERTICES];
+	double  pressure[NUMVERTICES];
+	double  surface[NUMVERTICES];
+	double  xyz_list[NUMVERTICES][3];
+	int    *doflist = NULL;
+	Penta  *penta   = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,MacAyealApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&values[0],nodes,NUMVERTICES2D,XYEnum); /*2D: only the first 3 nodes are taken*/
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays and extrude */
+	for(i=0;i<3;i++){
+		vx[i]  =values[i*NDOF2+0];
+		vy[i]  =values[i*NDOF2+1];
+		vx[i+3]=vx[i];
+		vy[i+3]=vy[i];
+
+		/*Check solution*/
+		if(isnan(vx[i])) _error_("NaN found in solution vector");
+		if(isnan(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get parameters fro pressure computation*/
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+
+	/*Start looping over all elements above current element and update all inputs*/
+	penta=this;
+	for(;;){
+
+		/*Get node data: */
+		GetVerticesCoordinates(&xyz_list[0][0],penta->nodes,NUMVERTICES);
+
+		/*Now Compute vel*/
+		GetInputListOnVertices(&vz[0],VzEnum,0.0); //default is 0
+		for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+		/*Now compute pressure*/
+		GetInputListOnVertices(&surface[0],SurfaceEnum);
+		for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
+
+		/*Now, we have to move the previous Vx and Vy inputs  to old 
+		 * status, otherwise, we'll wipe them off: */
+		penta->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+		penta->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+		penta->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+		/*Add vx and vy as inputs to the tria element: */
+		penta->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+		penta->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+		penta->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+		penta->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+		/*Stop if we have reached the surface*/
+		if (penta->IsOnSurface()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
+	}
+	
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticMacAyealPattyn {{{1*/
+void  Penta::InputUpdateFromSolutionDiagnosticMacAyealPattyn(double* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+	const int    numdof2d=NDOF2*NUMVERTICES2D;
+
+	int     i;
+	double  rho_ice,g;
+	double  macayeal_values[numdof];
+	double  pattyn_values[numdof];
+	double  vx[NUMVERTICES];
+	double  vy[NUMVERTICES];
+	double  vz[NUMVERTICES];
+	double  vel[NUMVERTICES];
+	double  pressure[NUMVERTICES];
+	double  surface[NUMVERTICES];
+	double  xyz_list[NUMVERTICES][3];
+	int*    doflistp = NULL;
+	int*    doflistm = NULL;
+	Penta   *penta   = NULL;
+
+	/*OK, we have to add results of this element for pattyn 
+	 * and results from the penta at base for macayeal. Now recover results*/
+	penta=GetBasalElement();
+
+	/*Get dof listof this element (pattyn dofs) and of the penta at base (macayeal dofs): */
+	GetDofList(&doflistp,PattynApproximationEnum,GsetEnum);
+	penta->GetDofList(&doflistm,MacAyealApproximationEnum,GsetEnum);
+
+	/*Get node data: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof2d;i++){
+		pattyn_values[i]=solution[doflistp[i]];
+		macayeal_values[i]=solution[doflistm[i]];
+	}
+	for(i=numdof2d;i<numdof;i++){
+		pattyn_values[i]=solution[doflistp[i]];
+		macayeal_values[i]=macayeal_values[i-numdof2d];
+	}
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&macayeal_values[0],penta->nodes,NUMVERTICES,XYEnum);
+	TransformSolutionCoord(&pattyn_values[0],   this->nodes,NUMVERTICES,XYEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		vx[i]=macayeal_values[i*NDOF2+0]+pattyn_values[i*NDOF2+0];
+		vy[i]=macayeal_values[i*NDOF2+1]+pattyn_values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(isnan(vx[i])) _error_("NaN found in solution vector");
+		if(isnan(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Now Compute vel*/
+	GetInputListOnVertices(&vz[0],VzEnum,0.0); //default is 0
+	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 3D, 
+	 *so the pressure is just the pressure at the z elevation: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	GetInputListOnVertices(&surface[0],SurfaceEnum);
+	for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xfree((void**)&doflistp);
+	xfree((void**)&doflistm);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticMacAyealStokes {{{1*/
+void  Penta::InputUpdateFromSolutionDiagnosticMacAyealStokes(double* solution){
+
+	const int    numdofm=NDOF2*NUMVERTICES;
+	const int    numdofs=NDOF4*NUMVERTICES;
+	const int    numdof2d=NDOF2*NUMVERTICES2D;
+
+	int     i;
+	double  stokesreconditioning;
+	double  macayeal_values[numdofm];
+	double  stokes_values[numdofs];
+	double  vx[NUMVERTICES];
+	double  vy[NUMVERTICES];
+	double  vz[NUMVERTICES];
+	double  vzmacayeal[NUMVERTICES];
+	double  vzstokes[NUMVERTICES];
+	double  vel[NUMVERTICES];
+	double  pressure[NUMVERTICES];
+	double  xyz_list[NUMVERTICES][3];
+	int*    doflistm        = NULL;
+	int*    doflists        = NULL;
+	Penta   *penta          = NULL;
+
+	/*OK, we have to add results of this element for macayeal 
+	 * and results from the penta at base for macayeal. Now recover results*/
+	penta=GetBasalElement();
+
+	/*Get dof listof this element (macayeal dofs) and of the penta at base (macayeal dofs): */
+	penta->GetDofList(&doflistm,MacAyealApproximationEnum,GsetEnum);
+	GetDofList(&doflists,StokesApproximationEnum,GsetEnum);
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+
+	/*Get node data: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof2d;i++){
+		macayeal_values[i]=solution[doflistm[i]];
+		macayeal_values[i+numdof2d]=solution[doflistm[i]];
+	}
+	for(i=0;i<numdofs;i++){
+		stokes_values[i]=solution[doflists[i]];
+	}
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&macayeal_values[0],this->nodes,NUMVERTICES,XYEnum);
+	TransformSolutionCoord(&stokes_values[0],this->nodes,NUMVERTICES,XYZPEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		vx[i]=stokes_values[i*NDOF4+0]+macayeal_values[i*NDOF2+0];
+		vy[i]=stokes_values[i*NDOF4+1]+macayeal_values[i*NDOF2+1];
+		vzstokes[i]=stokes_values[i*NDOF4+2];
+		pressure[i]=stokes_values[i*NDOF4+3]*stokesreconditioning;
+
+		/*Check solution*/
+		if(isnan(vx[i]))       _error_("NaN found in solution vector");
+		if(isnan(vy[i]))       _error_("NaN found in solution vector");
+		if(isnan(vzstokes[i])) _error_("NaN found in solution vector");
+		if(isnan(pressure[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz*/
+	Input* vzmacayeal_input=inputs->GetInput(VzMacAyealEnum);
+	if (vzmacayeal_input){
+		if (vzmacayeal_input->ObjectEnum()!=PentaP1InputEnum){
+			_error_("Cannot compute Vel as VzMacAyeal is of type %s",EnumToStringx(vzmacayeal_input->ObjectEnum()));
+		}
+		GetInputListOnVertices(&vzmacayeal[0],VzMacAyealEnum);
+	}
+	else{
+		_error_("Cannot update solution as VzMacAyeal is not present");
+	}
+
+	/*Now Compute vel*/
+	for(i=0;i<NUMVERTICES;i++) {
+		vz[i]=vzmacayeal[i]+vzstokes[i];
+		vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+	}
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(VzEnum,VzPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new PentaP1Input(VzEnum,vz));
+	this->inputs->AddInput(new PentaP1Input(VzStokesEnum,vzstokes));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xfree((void**)&doflistm);
+	xfree((void**)&doflists);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticPattyn {{{1*/
+void  Penta::InputUpdateFromSolutionDiagnosticPattyn(double* solution){
+	
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int    i;
+	double rho_ice,g;
+	double values[numdof];
+	double vx[NUMVERTICES];
+	double vy[NUMVERTICES];
+	double vz[NUMVERTICES];
+	double vel[NUMVERTICES];
+	double pressure[NUMVERTICES];
+	double surface[NUMVERTICES];
+	double xyz_list[NUMVERTICES][3];
+	int*   doflist = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,PattynApproximationEnum,GsetEnum);
+
+	/*Get node data: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&values[0],nodes,NUMVERTICES,XYEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		vx[i]=values[i*NDOF2+0];
+		vy[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(isnan(vx[i])) _error_("NaN found in solution vector");
+		if(isnan(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz*/
+	Input* vz_input=inputs->GetInput(VzEnum);
+	if (vz_input){
+		GetInputListOnVertices(&vz[0],VzEnum);
+	}
+	else{
+		for(i=0;i<NUMVERTICES;i++) vz[i]=0.0;
+	}
+
+	/*Now Compute vel*/
+	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 3D, 
+	 *so the pressure is just the pressure at the z elevation: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	GetInputListOnVertices(&surface[0],SurfaceEnum);
+	for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticPattynStokes {{{1*/
+void  Penta::InputUpdateFromSolutionDiagnosticPattynStokes(double* solution){
+
+	const int    numdofp=NDOF2*NUMVERTICES;
+	const int    numdofs=NDOF4*NUMVERTICES;
+
+	int    i;
+	double pattyn_values[numdofp];
+	double stokes_values[numdofs];
+	double vx[NUMVERTICES];
+	double vy[NUMVERTICES];
+	double vz[NUMVERTICES];
+	double vzpattyn[NUMVERTICES];
+	double vzstokes[NUMVERTICES];
+	double vel[NUMVERTICES];
+	double pressure[NUMVERTICES];
+	double xyz_list[NUMVERTICES][3];
+	double stokesreconditioning;
+	int*   doflistp      = NULL;
+	int*   doflists      = NULL;
+	Penta  *penta        = NULL;
+
+	/*OK, we have to add results of this element for pattyn 
+	 * and results from the penta at base for macayeal. Now recover results*/
+	penta=GetBasalElement();
+
+	/*Get dof listof this element (pattyn dofs) and of the penta at base (macayeal dofs): */
+	GetDofList(&doflistp,PattynApproximationEnum,GsetEnum);
+	GetDofList(&doflists,StokesApproximationEnum,GsetEnum);
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+
+	/*Get node data: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdofp;i++) pattyn_values[i]=solution[doflistp[i]];
+	for(i=0;i<numdofs;i++) stokes_values[i]=solution[doflists[i]];
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&pattyn_values[0],this->nodes,NUMVERTICES,XYEnum);
+	TransformSolutionCoord(&stokes_values[0],this->nodes,NUMVERTICES,XYZPEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		vx[i]=stokes_values[i*NDOF4+0]+pattyn_values[i*NDOF2+0];
+		vy[i]=stokes_values[i*NDOF4+1]+pattyn_values[i*NDOF2+1];
+		vzstokes[i]=stokes_values[i*NDOF4+2];
+		pressure[i]=stokes_values[i*NDOF4+3]*stokesreconditioning;
+
+		/*Check solution*/
+		if(isnan(vx[i]))       _error_("NaN found in solution vector");
+		if(isnan(vy[i]))       _error_("NaN found in solution vector");
+		if(isnan(vzstokes[i])) _error_("NaN found in solution vector");
+		if(isnan(pressure[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz*/
+	Input* vzpattyn_input=inputs->GetInput(VzPattynEnum);
+	if (vzpattyn_input){
+		if (vzpattyn_input->ObjectEnum()!=PentaP1InputEnum){
+			_error_("Cannot compute Vel as VzPattyn is of type %s",EnumToStringx(vzpattyn_input->ObjectEnum()));
+		}
+		GetInputListOnVertices(&vzpattyn[0],VzPattynEnum);
+	}
+	else{
+		_error_("Cannot update solution as VzPattyn is not present");
+	}
+
+	/*Now Compute vel*/
+	for(i=0;i<NUMVERTICES;i++) {
+		vz[i]=vzpattyn[i]+vzstokes[i];
+		vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+	}
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(VzEnum,VzPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new PentaP1Input(VzEnum,vz));
+	this->inputs->AddInput(new PentaP1Input(VzStokesEnum,vzstokes));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xfree((void**)&doflistp);
+	xfree((void**)&doflists);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticHutter {{{1*/
+void  Penta::InputUpdateFromSolutionDiagnosticHutter(double* solution){
+	
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int     i;
+	double  rho_ice,g;
+	double  values[numdof];
+	double  vx[NUMVERTICES];
+	double  vy[NUMVERTICES];
+	double  vz[NUMVERTICES];
+	double  vel[NUMVERTICES];
+	double  pressure[NUMVERTICES];
+	double  surface[NUMVERTICES];
+	double  xyz_list[NUMVERTICES][3];
+	int*    doflist = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Get node data: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		vx[i]=values[i*NDOF2+0];
+		vy[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(isnan(vx[i])) _error_("NaN found in solution vector");
+		if(isnan(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Now Compute vel*/
+	GetInputListOnVertices(&vz[0],VzEnum,0.0); //default is 0
+	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 3D, 
+	 *so the pressure is just the pressure at the z elevation: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	GetInputListOnVertices(&surface[0],SurfaceEnum);
+	for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticVert {{{1*/
+void  Penta::InputUpdateFromSolutionDiagnosticVert(double* solution){
+
+	const int numdof=NDOF1*NUMVERTICES;
+	
+	int      i;
+	int      approximation;
+	double   rho_ice,g;
+	double   values[numdof];
+	double   vx[NUMVERTICES];
+	double   vy[NUMVERTICES];
+	double   vz[NUMVERTICES];
+	double   vzmacayeal[NUMVERTICES];
+	double   vzpattyn[NUMVERTICES];
+	double   vzstokes[NUMVERTICES];
+	double   vel[NUMVERTICES];
+	double   pressure[NUMVERTICES];
+	double   surface[NUMVERTICES];
+	double   xyz_list[NUMVERTICES][3];
+	int*     doflist      = NULL;
+
+
+	/*Get the approximation and do nothing if the element in Stokes or None*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
+		return;
+	}
+
+	/*Get dof list and vertices coordinates: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*Use the dof list to index into the solution vector vz: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+	for(i=0;i<NUMVERTICES;i++){
+		vz[i]=values[i*NDOF1+0];
+
+		/*Check solution*/
+		if(isnan(vz[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vx and Vy*/
+	GetInputListOnVertices(&vx[0],VxEnum,0.0); //default is 0
+	GetInputListOnVertices(&vy[0],VyEnum,0.0); //default is 0
+
+	/*Do some modifications if we actually have a PattynStokes or MacAyealStokes element*/
+	if(approximation==PattynStokesApproximationEnum){
+		Input* vzstokes_input=inputs->GetInput(VzStokesEnum);
+		if (vzstokes_input){
+			if (vzstokes_input->ObjectEnum()!=PentaP1InputEnum) _error_("Cannot compute Vel as VzStokes is of type %s",EnumToStringx(vzstokes_input->ObjectEnum()));
+			GetInputListOnVertices(&vzstokes[0],VzStokesEnum);
+		}
+		else _error_("Cannot compute Vz as VzStokes in not present in PattynStokes element");
+		for(i=0;i<NUMVERTICES;i++){
+			vzpattyn[i]=vz[i];
+			vz[i]=vzpattyn[i]+vzstokes[i];
+		}
+	}
+	else if(approximation==MacAyealStokesApproximationEnum){
+		Input* vzstokes_input=inputs->GetInput(VzStokesEnum);
+		if (vzstokes_input){
+			if (vzstokes_input->ObjectEnum()!=PentaP1InputEnum) _error_("Cannot compute Vel as VzStokes is of type %s",EnumToStringx(vzstokes_input->ObjectEnum()));
+			GetInputListOnVertices(&vzstokes[0],VzStokesEnum);
+		}
+		else _error_("Cannot compute Vz as VzStokes in not present in MacAyealStokes element");
+		for(i=0;i<NUMVERTICES;i++){
+			vzmacayeal[i]=vz[i];
+			vz[i]=vzmacayeal[i]+vzstokes[i];
+		}
+	}
+
+	/*Now Compute vel*/
+	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 3D, 
+	 *so the pressure is just the pressure at the z elevation: except it this is a PattynStokes element */
+	if(approximation!=PattynStokesApproximationEnum &&  approximation!=MacAyealStokesApproximationEnum){
+		rho_ice=matpar->GetRhoIce();
+		g=matpar->GetG();
+		GetInputListOnVertices(&surface[0],SurfaceEnum);
+		for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
+	}
+
+	/*Now, we have to move the previous Vz inputs to old 
+	 * status, otherwise, we'll wipe them off and add the new inputs: */
+	this->inputs->ChangeEnum(VzEnum,VzPicardEnum);
+
+	if(approximation!=PattynStokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum){
+		this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+		this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+	}
+	else if(approximation==PattynStokesApproximationEnum){
+		this->inputs->AddInput(new PentaP1Input(VzPattynEnum,vzpattyn));
+	}
+	else if(approximation==MacAyealStokesApproximationEnum){
+		this->inputs->AddInput(new PentaP1Input(VzMacAyealEnum,vzmacayeal));
+	}
+	this->inputs->AddInput(new PentaP1Input(VzEnum,vz));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticStokes {{{1*/
+void  Penta::InputUpdateFromSolutionDiagnosticStokes(double* solution){
+	
+	const int numdof=NDOF4*NUMVERTICES;
+
+	int     i;
+	double  values[numdof];
+	double  vx[NUMVERTICES];
+	double  vy[NUMVERTICES];
+	double  vz[NUMVERTICES];
+	double  vel[NUMVERTICES];
+	double  pressure[NUMVERTICES];
+	double  stokesreconditioning;
+	int*    doflist=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,StokesApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&values[0],nodes,NUMVERTICES,XYZPEnum);
+
+	/*Ok, we have vx and vy in values, fill in all arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		vx[i]=values[i*NDOF4+0];
+		vy[i]=values[i*NDOF4+1];
+		vz[i]=values[i*NDOF4+2];
+		pressure[i]=values[i*NDOF4+3];
+
+		/*Check solution*/
+		if(isnan(vx[i]))       _error_("NaN found in solution vector");
+		if(isnan(vy[i]))       _error_("NaN found in solution vector");
+		if(isnan(vz[i]))       _error_("NaN found in solution vector");
+		if(isnan(pressure[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Recondition pressure and compute vel: */
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	for(i=0;i<NUMVERTICES;i++) pressure[i]=pressure[i]*stokesreconditioning;
+	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+	
+	/*Now, we have to move the previous inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(VzEnum,VzPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new PentaP1Input(VzEnum,vz));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_BALANCED_
+/*FUNCTION Penta::CreateKMatrixBalancethickness {{{1*/
+ElementMatrix* Penta::CreateKMatrixBalancethickness(void){
+
+	/*Figure out if this penta is collapsed. If so, then bailout, except if it is at the 
+	  bedrock, in which case we spawn a tria element using the 3 first nodes, and use it to build 
+	  the stiffness matrix. */
+	if (!IsOnBed()) return NULL;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Spawn Tria element from the base of the Penta: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixBalancethickness();
+	delete tria->matice; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorBalancethickness {{{1*/
+ElementVector* Penta::CreatePVectorBalancethickness(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorBalancethickness();
+	delete tria->matice; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+#endif
+
Index: /issm/trunk-jpl-damage/src/c/objects/Elements/Penta.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Elements/Penta.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Elements/Penta.h	(revision 11330)
@@ -0,0 +1,306 @@
+/*! \file Penta.h 
+ *  \brief: header file for penta object
+ */
+
+#ifndef _PENTA_H_
+#define _PENTA_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Element.h"
+#include "./PentaHook.h"
+#include "./PentaRef.h"
+class  Object;
+class Parameters;
+class Inputs;
+class IoModel;
+class Node;
+class Matice;
+class Matpar;
+class Tria;
+class ElementMatrix;
+class ElementVector;
+
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+/*}}}*/
+
+class Penta: public Element,public PentaHook,public PentaRef{
+
+	public:
+
+		int          id;
+		int          sid;
+
+		Node       **nodes;        // 6 nodes
+		Matice      *matice;       // 1 material ice
+		Matpar      *matpar;       // 1 material parameter
+		Penta      **verticalneighbors;   // 2 neighbors: first one under, second one above
+		int          horizontalneighborsids[3];
+
+		Parameters  *parameters;   //pointer to solution parameters
+		Inputs      *inputs;
+		Results      *results;
+
+		/*Penta constructors and destructor: {{{1*/
+		Penta();
+		Penta(int penta_id,int penta_sid,int i, IoModel* iomodel,int nummodels);
+		~Penta();
+		/*}}}*/
+		/*Object virtual functions definitions: {{{1*/
+		Object*   copy();
+		void	  DeepEcho();
+		void	  Echo();
+		int		  ObjectEnum();
+		int		  Id(); 
+		#ifdef _SERIAL_
+		void	  Marshall(char** pmarshalled_dataset);
+		int		  MarshallSize();
+		void	  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int		  MyRank();
+		/*}}}*/
+		/*Update virtual functions definitions: {{{1*/
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromConstant(double constant, int name);
+		void  InputUpdateFromConstant(int constant, int name);
+		void  InputUpdateFromSolution(double* solutiong);
+		void  InputUpdateFromVector(bool* vector, int name, int type);
+		void  InputUpdateFromVector(double* vector, int name, int type);
+		void  InputUpdateFromVector(int* vector, int name, int type);
+		#ifdef _HAVE_DAKOTA_
+		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(double* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
+		void  InputUpdateFromMatrixDakota(double* matrix, int nows, int ncols, int name, int type);
+		#endif
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
+		/*}}}*/
+		/*Element virtual functions definitions: {{{1*/
+		void   AverageOntoPartition(Vec partition_contributions,Vec partition_areas,double* vertex_response,double* qmu_part);
+		void   BasalFrictionCreateInput(void);
+		void   ComputeBasalStress(Vec sigma_b);
+		void   ComputeStrainRate(Vec eps);
+		void   ComputeStressTensor();
+		void   Configure(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters);
+		void   SetCurrentConfiguration(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters);
+		void   CreateKMatrix(Mat Kff, Mat Kfs,Vec df);
+		void   CreatePVector(Vec pf);
+		void   DeleteResults(void);
+		int    GetNodeIndex(Node* node);
+		void   GetSolutionFromInputs(Vec solution);
+		double GetZcoord(GaussPenta* gauss);
+		void   GetVectorFromInputs(Vec vector,int name_enum);
+		void   GetVectorFromResults(Vec vector,int offset,int interp);
+		
+		int    Sid();
+		void   InputArtificialNoise(int enum_type,double min, double max);
+		bool   InputConvergence(double* eps, int* enums,int num_enums,int* criterionenums,double* criterionvalues,int num_criterionenums);
+		void   InputCreate(double scalar,int name,int code);
+		void   InputCreate(double* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code);
+		void   InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum=MeshElementsEnum);
+		void   InputDuplicate(int original_enum,int new_enum);
+		void   InputScale(int enum_type,double scale_factor);
+		
+		void   InputToResult(int enum_type,int step,double time);
+		void   MigrateGroundingLine(double* old_floating_ice,double* sheet_ungrounding);
+		void   PotentialSheetUngrounding(Vec potential_sheet_ungrounding);
+		void   RequestedOutput(int output_enum,int step,double time);
+		void   ListResultsInfo(int** results_enums,int** results_size,double** results_times,int** results_steps,int* num_results);
+		void   PatchFill(int* pcount, Patch* patch);
+		void   PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes);
+		void   ProcessResultsUnits(void);
+		void   ResetCoordinateSystem(void);
+		double SurfaceArea(void);
+		void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type);
+		int    UpdatePotentialSheetUngrounding(double* potential_sheet_ungrounding,Vec vec_nodes_on_iceshelf,double* nodes_on_iceshelf);
+		double TimeAdapt();
+		int*   GetHorizontalNeighboorSids(void);
+		void   ViscousHeatingCreateInput(void);
+		void   SmearFunction(Vec smearedvector,double (*WeightFunction)(double distance,double radius),double radius);
+
+		 #ifdef _HAVE_RESPONSES_
+		double IceVolume(void);
+		void   MinVel(double* pminvel, bool process_units);
+		void   MinVx(double* pminvx, bool process_units);
+		void   MinVy(double* pminvy, bool process_units);
+		void   MinVz(double* pminvz, bool process_units);
+		int    NodalValue(double* pvalue, int index, int natureofdataenum,bool process_units);
+		double MassFlux(double* segment,bool process_units);
+		void   MaxAbsVx(double* pmaxabsvx, bool process_units);
+		void   MaxAbsVy(double* pmaxabsvy, bool process_units);
+		void   MaxAbsVz(double* pmaxabsvz, bool process_units);
+		void   MaxVel(double* pmaxvel, bool process_units);
+		void   ElementResponse(double* presponse,int response_enum,bool process_units);
+		void   MaxVx(double* pmaxvx, bool process_units);
+		void   MaxVy(double* pmaxvy, bool process_units);
+		void   MaxVz(double* pmaxvz, bool process_units);
+		#endif
+
+		#ifdef _HAVE_CONTROL_
+		double DragCoefficientAbsGradient(bool process_units,int weight_index);
+		void   Gradj(Vec gradient,int control_type);
+		void   GradjDragMacAyeal(Vec gradient);
+		void   GradjDragPattyn(Vec gradient);
+		void   GradjDragStokes(Vec gradient);
+		void   GradjBbarMacAyeal(Vec gradient);
+		void   GradjBbarPattyn(Vec gradient);
+		void   GradjBbarStokes(Vec gradient);
+		void   ControlInputGetGradient(Vec gradient,int enum_type);
+		void   ControlInputScaleGradient(int enum_type,double scale);
+		void   ControlInputSetGradient(double* gradient,int enum_type);
+		double RheologyBbarAbsGradient(bool process_units,int weight_index);
+		double ThicknessAbsMisfit(     bool process_units,int weight_index);
+		double SurfaceAbsVelMisfit(    bool process_units,int weight_index);
+		double SurfaceRelVelMisfit(    bool process_units,int weight_index);
+		double SurfaceLogVelMisfit(    bool process_units,int weight_index);
+		double SurfaceLogVxVyMisfit(   bool process_units,int weight_index);
+		double SurfaceAverageVelMisfit(bool process_units,int weight_index);
+		double ThicknessAbsGradient(bool process_units,int weight_index);
+		void   InputControlUpdate(double scalar,bool save_parameter);
+		#endif
+		/*}}}*/
+		/*Penta specific routines:{{{1*/
+		void	  BedNormal(double* bed_normal, double xyz_list[3][3]);
+		ElementMatrix* CreateKMatrixPrognostic(void);
+		ElementMatrix* CreateKMatrixSlope(void);
+		ElementVector* CreatePVectorPrognostic(void);
+		ElementVector* CreatePVectorSlope(void);
+		void	  GetDofList(int** pdoflist,int approximation_enum,int setenum);
+		void	  GetDofList1(int* doflist);
+		void    GetSidList(int* sidlist);
+		void    GetConnectivityList(int* connectivity);
+		int     GetElementType(void);
+		void    GetElementSizes(double* hx,double* hy,double* hz);
+		void    GetInputListOnVertices(double* pvalue,int enumtype);
+		void    GetInputListOnVertices(double* pvalue,int enumtype,double defaultvalue);
+		void    GetInputValue(double* pvalue,Node* node,int enumtype);
+		void	  GetPhi(double* phi, double*  epsilon, double viscosity);
+		void	  GetSolutionFromInputsEnthalpy(Vec solutiong);
+		double  GetStabilizationParameter(double u, double v, double w, double diameter, double rho_ice, double heatcapacity, double thermalconductivity);
+		void    GetStrainRate3dPattyn(double* epsilon,double* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input);
+		void    GetStrainRate3d(double* epsilon,double* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input, Input* vz_input);
+		Penta*  GetUpperElement(void);
+		Penta*  GetLowerElement(void);
+		Penta*  GetBasalElement(void);
+		void	  InputExtrude(int enum_type,int object_type);
+		void    InputUpdateFromSolutionPrognostic(double* solutiong);
+		void    InputUpdateFromSolutionOneDof(double* solutiong,int enum_type);
+		void    InputUpdateFromSolutionOneDofCollapsed(double* solutiong,int enum_type);
+		bool	  IsInput(int name);
+		bool	  IsOnSurface(void);
+		bool	  IsOnBed(void);
+		bool    IsFloating(void); 
+		bool    IsNodeOnShelf(); 
+		bool    IsNodeOnShelfFromFlags(double* flags);
+		bool    IsOnWater(void); 
+		double  MinEdgeLength(double xyz_list[6][3]);
+		void	  ReduceMatrixStokes(double* Ke_reduced, double* Ke_temp);
+		void	  ReduceVectorStokes(double* Pe_reduced, double* Ke_temp, double* Pe_temp);
+		void	  SetClone(int* minranks);
+		Tria*	  SpawnTria(int g0, int g1, int g2);
+		void	  SurfaceNormal(double* surface_normal, double xyz_list[3][3]);
+
+		#ifdef _HAVE_DIAGNOSTIC_
+		ElementMatrix* CreateKMatrixCouplingMacAyealPattyn(void);
+		ElementMatrix* CreateKMatrixCouplingMacAyealPattynViscous(void);
+		ElementMatrix* CreateKMatrixCouplingMacAyealPattynFriction(void);
+		ElementMatrix* CreateKMatrixCouplingMacAyealStokes(void);
+		ElementMatrix* CreateKMatrixCouplingMacAyealStokesViscous(void);
+		ElementMatrix* CreateKMatrixCouplingMacAyealStokesFriction(void);
+		ElementMatrix* CreateKMatrixCouplingPattynStokes(void);
+		ElementMatrix* CreateKMatrixDiagnosticHoriz(void);
+		ElementVector* CreateDVectorDiagnosticHoriz(void);
+		ElementVector* CreateDVectorDiagnosticStokes(void);
+		ElementMatrix* CreateKMatrixDiagnosticHutter(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyeal2d(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyeal3d(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyeal3dViscous(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyeal3dFriction(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyealPattyn(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyealStokes(void);
+		ElementMatrix* CreateKMatrixDiagnosticPattyn(void);
+		ElementMatrix* CreateKMatrixDiagnosticPattynViscous(void);
+		ElementMatrix* CreateKMatrixDiagnosticPattynFriction(void);
+		ElementMatrix* CreateKMatrixDiagnosticPattynStokes(void);
+		ElementMatrix* CreateKMatrixDiagnosticStokes(void);
+		ElementMatrix* CreateKMatrixDiagnosticStokesViscous(void);
+		ElementMatrix* CreateKMatrixDiagnosticStokesFriction(void);
+		ElementMatrix* CreateKMatrixDiagnosticVert(void);
+		ElementMatrix* CreateKMatrixDiagnosticVertVolume(void);
+		ElementMatrix* CreateKMatrixDiagnosticVertSurface(void);
+		void           InputUpdateFromSolutionDiagnosticHoriz( double* solutiong);
+		void           InputUpdateFromSolutionDiagnosticMacAyeal( double* solutiong);
+		void           InputUpdateFromSolutionDiagnosticMacAyealPattyn( double* solutiong);
+		void           InputUpdateFromSolutionDiagnosticMacAyealStokes( double* solutiong);
+		void           InputUpdateFromSolutionDiagnosticPattyn( double* solutiong);
+		void           InputUpdateFromSolutionDiagnosticPattynStokes( double* solutiong);
+		void           InputUpdateFromSolutionDiagnosticHutter( double* solutiong);
+		void           InputUpdateFromSolutionDiagnosticVert( double* solutiong);
+		void           InputUpdateFromSolutionDiagnosticStokes( double* solutiong);
+		void	         GetSolutionFromInputsDiagnosticHoriz(Vec solutiong);
+		void	         GetSolutionFromInputsDiagnosticHutter(Vec solutiong);
+		void	         GetSolutionFromInputsDiagnosticStokes(Vec solutiong);
+		void	         GetSolutionFromInputsDiagnosticVert(Vec solutiong);
+		ElementVector* CreatePVectorCouplingMacAyealStokes(void);
+		ElementVector* CreatePVectorCouplingMacAyealStokesViscous(void);
+		ElementVector* CreatePVectorCouplingMacAyealStokesFriction(void);
+		ElementVector* CreatePVectorCouplingPattynStokes(void);
+		ElementVector* CreatePVectorCouplingPattynStokesViscous(void);
+		ElementVector* CreatePVectorCouplingPattynStokesFriction(void);
+		ElementVector* CreatePVectorDiagnosticHoriz(void);
+		ElementVector* CreatePVectorDiagnosticHutter(void);
+		ElementVector* CreatePVectorDiagnosticMacAyeal(void);
+		ElementVector* CreatePVectorDiagnosticMacAyealPattyn(void);
+		ElementVector* CreatePVectorDiagnosticMacAyealStokes(void);
+		ElementVector* CreatePVectorDiagnosticPattyn(void);
+		ElementVector* CreatePVectorDiagnosticPattynStokes(void);
+		ElementVector* CreatePVectorDiagnosticStokes(void);
+		ElementVector* CreatePVectorDiagnosticStokesViscous(void);
+		ElementVector* CreatePVectorDiagnosticStokesShelf(void);
+		ElementVector* CreatePVectorDiagnosticVert(void);
+		ElementVector* CreatePVectorDiagnosticVertVolume(void);
+		ElementVector* CreatePVectorDiagnosticVertBase(void);
+		#endif
+
+		#ifdef _HAVE_CONTROL_
+		ElementVector* CreatePVectorAdjointHoriz(void);
+		ElementVector* CreatePVectorAdjointMacAyeal(void);
+		ElementVector* CreatePVectorAdjointPattyn(void);
+		ElementVector* CreatePVectorAdjointStokes(void);
+		void    InputUpdateFromSolutionAdjointHoriz( double* solutiong);
+		void    InputUpdateFromSolutionAdjointStokes( double* solutiong);
+		#endif
+
+		#ifdef _HAVE_HYDROLOGY_
+		void    CreateHydrologyWaterVelocityInput(void);
+		#endif
+		#ifdef _HAVE_THERMAL_
+		ElementMatrix* CreateKMatrixEnthalpy(void);
+		ElementMatrix* CreateKMatrixEnthalpyVolume(void);
+		ElementMatrix* CreateKMatrixEnthalpyShelf(void);
+		ElementMatrix* CreateKMatrixThermal(void);
+		ElementMatrix* CreateKMatrixMelting(void);
+		ElementMatrix* CreateKMatrixThermalVolume(void);
+		ElementMatrix* CreateKMatrixThermalShelf(void);
+		ElementVector* CreatePVectorEnthalpy(void);
+		ElementVector* CreatePVectorEnthalpyVolume(void);
+		ElementVector* CreatePVectorEnthalpyShelf(void);
+		ElementVector* CreatePVectorEnthalpySheet(void);
+		ElementVector* CreatePVectorMelting(void);
+		ElementVector* CreatePVectorThermal(void);
+		ElementVector* CreatePVectorThermalVolume(void);
+		ElementVector* CreatePVectorThermalShelf(void);
+		ElementVector* CreatePVectorThermalSheet(void);
+		void	       GetSolutionFromInputsThermal(Vec solutiong);
+		void           InputUpdateFromSolutionThermal( double* solutiong);
+		void           InputUpdateFromSolutionEnthalpy( double* solutiong);
+		#endif
+		#ifdef _HAVE_BALANCED_
+		ElementMatrix* CreateKMatrixBalancethickness(void);
+		ElementVector* CreatePVectorBalancethickness(void);
+		#endif
+		/*}}}*/
+};
+#endif  /* _PENTA_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Elements/PentaHook.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Elements/PentaHook.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Elements/PentaHook.cpp	(revision 11330)
@@ -0,0 +1,104 @@
+/*!\file PentaHook.c
+ * \brief: implementation of the PentaHook object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION PentaHook::PentaHook(){{{1*/
+PentaHook::PentaHook(){
+	numanalyses=UNDEF;
+	this->hnodes=NULL;
+	this->hmatice=NULL;
+	this->hmatpar=NULL;
+	this->hneighbors=NULL;
+}
+/*}}}*/
+/*FUNCTION PentaHook::~PentaHook(){{{1*/
+PentaHook::~PentaHook(){
+
+	int i;
+
+	for(i=0;i<this->numanalyses;i++){
+		if (this->hnodes[i]) delete this->hnodes[i];
+	}
+	delete [] this->hnodes;
+	delete hmatice;
+	delete hmatpar;
+	delete hneighbors;
+}
+/*}}}*/
+/*FUNCTION PentaHook::PentaHook(int in_numanalyses,int matice_id, int matpar_id){{{1*/
+PentaHook::PentaHook(int in_numanalyses,int matice_id, IoModel* iomodel){
+
+	/*intermediary: */
+	int matpar_id;
+	
+	/*retrieve parameters: */
+	iomodel->Constant(&matpar_id,MeshNumberofelementsEnum); matpar_id++;
+
+	this->numanalyses=in_numanalyses;
+	this->hnodes=new Hook*[in_numanalyses];
+	this->hmatice=new Hook(&matice_id,1);
+	this->hmatpar=new Hook(&matpar_id,1);
+	this->hneighbors=NULL; 
+
+	//Initialize hnodes as NULL
+	for(int i=0;i<this->numanalyses;i++){
+		this->hnodes[i]=NULL;
+	}
+
+}
+/*}}}*/
+
+/*FUNCTION PentaHook::SetHookNodes{{{1*/
+void PentaHook::SetHookNodes(int* node_ids,int analysis_counter){
+	this->hnodes[analysis_counter]= new Hook(node_ids,6);
+
+}
+/*}}}*/
+/*FUNCTION PentaHook::InitHookNeighbors{{{1*/
+void PentaHook::InitHookNeighbors(int* element_ids){
+	this->hneighbors=new Hook(element_ids,2);
+
+}
+/*}}}*/
+/*FUNCTION PentaHook::SpawnTriaHook{{{1*/
+void PentaHook::SpawnTriaHook(TriaHook* triahook,int* indices){
+
+	int i;
+	int zero=0;
+
+	triahook->numanalyses=this->numanalyses;
+	triahook->hnodes=new Hook*[this->numanalyses];
+
+	for(i=0;i<this->numanalyses;i++){
+		/*Do not do anything if Hook is empty*/
+		if (!this->hnodes[i] || this->hnodes[i]->GetNum()==0){
+			triahook->hnodes[i]=NULL;
+		}
+		else{
+			/*Else, spawn Hook*/
+			triahook->hnodes[i]=this->hnodes[i]->Spawn(indices,3);
+		}
+	}
+	// do not spawn hmatice. matice will be taken care of by Penta
+	triahook->hmatice=NULL;
+	triahook->hmatpar=(Hook*)this->hmatpar->copy();
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Elements/PentaHook.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Elements/PentaHook.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Elements/PentaHook.h	(revision 11330)
@@ -0,0 +1,33 @@
+/*!\file: PentaHook.h
+ * \brief prototypes for PentaHook.h
+ */ 
+
+#ifndef _PENTAHOOK_H_
+#define  _PENTAHOOK_H_
+
+class Hook;
+class TriaHook;
+class IoModel;
+
+class PentaHook{
+
+	public: 
+		int   numanalyses; //number of analysis types
+		Hook** hnodes; // 6 nodes for each analysis type
+		Hook*  hmatice; // 1 ice material
+		Hook*  hmatpar; // 1 material parameter
+		Hook*  hneighbors; // 2 elements, first down, second up
+
+		/*FUNCTION constructors, destructors {{{1*/
+		PentaHook();
+		PentaHook(int in_numanalyses,int matice_id, IoModel* iomodel);
+		~PentaHook();
+		void SetHookNodes(int* node_ids,int analysis_counter);
+		void SpawnTriaHook(TriaHook* triahook,int* indices);
+		void InitHookNeighbors(int* element_ids);
+		/*}}}*/
+};
+
+
+#endif //ifndef _PENTAHOOK_H_
+
Index: /issm/trunk-jpl-damage/src/c/objects/Elements/PentaRef.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Elements/PentaRef.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Elements/PentaRef.cpp	(revision 11330)
@@ -0,0 +1,1267 @@
+/*!\file PentaRef.c
+ * \brief: implementation of the PentaRef object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMNODESP1    6
+#define NUMNODESP1_2d 3
+#define NUMNODESMINI  7
+
+/*Object constructors and destructor*/
+/*FUNCTION PentaRef::PentaRef(){{{1*/
+PentaRef::PentaRef(){
+	this->element_type_list=NULL;
+}
+/*}}}*/
+/*FUNCTION PentaRef::PentaRef(int* types,int nummodels){{{1*/
+PentaRef::PentaRef(const int nummodels){
+
+	/*Only allocate pointer*/
+	element_type_list=(int*)xmalloc(nummodels*sizeof(int));
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::~PentaRef(){{{1*/
+PentaRef::~PentaRef(){
+	xfree((void**)&element_type_list);
+}
+/*}}}*/
+
+/*Management*/
+/*FUNCTION PentaRef::SetElementType{{{1*/
+void PentaRef::SetElementType(int type,int type_counter){
+
+	_assert_(type==P1Enum || type==P1DGEnum);
+
+	/*initialize element type*/
+	this->element_type_list[type_counter]=type;
+}
+/*}}}*/
+
+/*Reference Element numerics*/
+/*FUNCTION PentaRef::GetBMacAyealPattyn {{{1*/
+void PentaRef::GetBMacAyealPattyn(double* B, double* xyz_list, GaussPenta* gauss){
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ dh/dx          0      ]
+	 *          [   0           dh/dy   ]
+	 *          [ 1/2*dh/dy  1/2*dh/dx  ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
+	 */
+
+	double dbasis[3][NUMNODESP1];
+
+	/*Get dbasis in actual coordinate system: */
+	GetNodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list, gauss);
+
+	/*Build B: */
+	for (int i=0;i<NUMNODESP1;i++){
+		*(B+NDOF2*NUMNODESP1*0+NDOF2*i)=dbasis[0][i]; 
+		*(B+NDOF2*NUMNODESP1*0+NDOF2*i+1)=0.0;
+
+		*(B+NDOF2*NUMNODESP1*1+NDOF2*i)=0.0;
+		*(B+NDOF2*NUMNODESP1*1+NDOF2*i+1)=dbasis[1][i];
+
+		*(B+NDOF2*NUMNODESP1*2+NDOF2*i)=(float).5*dbasis[1][i]; 
+		*(B+NDOF2*NUMNODESP1*2+NDOF2*i+1)=(float).5*dbasis[0][i]; 
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBMacAyealStokes{{{1*/
+void PentaRef::GetBMacAyealStokes(double* B, double* xyz_list, GaussPenta* gauss){
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ dh/dx          0       0   0 ]
+	 *          [   0           dh/dy    0   0 ]
+	 *          [ 1/2*dh/dy  1/2*dh/dx   0   0 ]
+	 *          [   0            0       0   h ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
+	 */
+
+	int    i;
+	double dh1dh7[3][NUMNODESMINI];
+	double l1l6[NUMNODESP1];
+
+	/*Get dh1dh6 in actual coordinate system: */
+	GetNodalFunctionsMINIDerivatives(&dh1dh7[0][0],xyz_list, gauss);
+	GetNodalFunctionsP1(l1l6, gauss);
+
+	/*Build B: */
+	for (i=0;i<NUMNODESMINI;i++){
+		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i)=dh1dh7[0][i]; //B[0][NDOF4*i]=dh1dh6[0][i];
+		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+1)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+2)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+1)=dh1dh7[1][i];
+		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+2)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i)=0.5*dh1dh7[1][i];
+		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+1)=0.5*dh1dh7[0][i];
+		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+2)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+1)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+2)=0;
+	}
+
+	for (i=0;i<NUMNODESP1;i++){ //last column not for the bubble function
+		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+3)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+3)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+3)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+3)=l1l6[i];
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBPattyn {{{1*/
+void PentaRef::GetBPattyn(double* B, double* xyz_list, GaussPenta* gauss){
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ dh/dx          0      ]
+	 *          [   0           dh/dy   ]
+	 *          [ 1/2*dh/dy  1/2*dh/dx  ]
+	 *          [ 1/2*dh/dz      0      ]
+	 *          [  0         1/2*dh/dz  ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
+	 */
+
+	double dbasis[3][NUMNODESP1];
+
+	/*Get dbasis in actual coordinate system: */
+	GetNodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list, gauss);
+
+	/*Build B: */
+	for (int i=0;i<NUMNODESP1;i++){
+		*(B+NDOF2*NUMNODESP1*0+NDOF2*i)=dbasis[0][i]; 
+		*(B+NDOF2*NUMNODESP1*0+NDOF2*i+1)=0.0;
+
+		*(B+NDOF2*NUMNODESP1*1+NDOF2*i)=0.0;
+		*(B+NDOF2*NUMNODESP1*1+NDOF2*i+1)=dbasis[1][i];
+
+		*(B+NDOF2*NUMNODESP1*2+NDOF2*i)=(float).5*dbasis[1][i]; 
+		*(B+NDOF2*NUMNODESP1*2+NDOF2*i+1)=(float).5*dbasis[0][i]; 
+
+		*(B+NDOF2*NUMNODESP1*3+NDOF2*i)=(float).5*dbasis[2][i]; 
+		*(B+NDOF2*NUMNODESP1*3+NDOF2*i+1)=0.0;
+
+		*(B+NDOF2*NUMNODESP1*4+NDOF2*i)=0.0;
+		*(B+NDOF2*NUMNODESP1*4+NDOF2*i+1)=(float).5*dbasis[2][i]; 
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBprimePattyn {{{1*/
+void PentaRef::GetBprimePattyn(double* B, double* xyz_list, GaussPenta* gauss_coord){
+	/*Compute B  prime matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ 2*dh/dx     dh/dy   ]
+	 *                [   dh/dx    2*dh/dy  ]
+	 *                [ dh/dy      dh/dx    ]
+	 *                [ dh/dz         0     ]
+	 *                [  0         dh/dz    ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
+	 */
+	double dbasis[3][NUMNODESP1];
+
+	/*Get dbasis in actual coordinate system: */
+	GetNodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list, gauss_coord);
+
+	/*Build BPrime: */
+	for (int i=0;i<NUMNODESP1;i++){
+		*(B+NDOF2*NUMNODESP1*0+NDOF2*i)=2.0*dbasis[0][i]; 
+		*(B+NDOF2*NUMNODESP1*0+NDOF2*i+1)=dbasis[1][i];
+
+		*(B+NDOF2*NUMNODESP1*1+NDOF2*i)=dbasis[0][i];
+		*(B+NDOF2*NUMNODESP1*1+NDOF2*i+1)=2.0*dbasis[1][i];
+
+		*(B+NDOF2*NUMNODESP1*2+NDOF2*i)=dbasis[1][i]; 
+		*(B+NDOF2*NUMNODESP1*2+NDOF2*i+1)=dbasis[0][i]; 
+
+		*(B+NDOF2*NUMNODESP1*3+NDOF2*i)=dbasis[2][i]; 
+		*(B+NDOF2*NUMNODESP1*3+NDOF2*i+1)=0.0;
+
+		*(B+NDOF2*NUMNODESP1*4+NDOF2*i)=0.0;
+		*(B+NDOF2*NUMNODESP1*4+NDOF2*i+1)=dbasis[2][i]; 
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBprimeMacAyealStokes{{{1*/
+void PentaRef::GetBprimeMacAyealStokes(double* Bprime, double* xyz_list, GaussPenta* gauss){
+	/*Compute Bprime  matrix. Bprime=[Bprime1 Bprime2 Bprime3 Bprime4 Bprime5 Bprime6] where Bprimei is of size 5*NDOF2. 
+	 * For node i, Bprimei can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bprimei=[ 2*dh/dx    dh/dy   0   0 ]
+	 *               [  dh/dx    2*dh/dy  0   0 ]
+	 *               [  dh/dy     dh/dx   0   0 ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume Bprime has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
+	 */
+
+	int    i;
+	double dh1dh7[3][NUMNODESMINI];
+
+	/*Get dh1dh6 in actual coordinate system: */
+	GetNodalFunctionsMINIDerivatives(&dh1dh7[0][0],xyz_list, gauss);
+
+	/*Build Bprime: */
+	for (i=0;i<NUMNODESMINI;i++){
+		*(Bprime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i)=2*dh1dh7[0][i]; //Bprime[0][NDOF4*i]=dh1dh6[0][i];
+		*(Bprime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+1)=dh1dh7[1][i];
+		*(Bprime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+2)=0;
+		*(Bprime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i)=dh1dh7[0][i];
+		*(Bprime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+1)=2*dh1dh7[1][i];
+		*(Bprime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+2)=0;
+		*(Bprime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i)=dh1dh7[1][i];
+		*(Bprime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+1)=dh1dh7[0][i];
+		*(Bprime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+2)=0;
+	}
+
+	for (i=0;i<NUMNODESP1;i++){ //last column not for the bubble function
+		*(Bprime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+3)=0;
+		*(Bprime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+3)=0;
+		*(Bprime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+3)=0;
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBStokes {{{1*/
+void PentaRef::GetBStokes(double* B, double* xyz_list, GaussPenta* gauss){
+
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 3*NDOF4. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 		Bi=[ dh/dx          0              0       0  ]
+	 *					[   0           dh/dy           0       0  ]
+	 *					[   0             0           dh/dy     0  ]
+	 *					[ 1/2*dh/dy    1/2*dh/dx        0       0  ]
+	 *					[ 1/2*dh/dz       0         1/2*dh/dx   0  ]
+	 *					[   0          1/2*dh/dz    1/2*dh/dy   0  ]
+	 *					[   0             0             0       h  ]
+	 *					[ dh/dx         dh/dy         dh/dz     0  ]
+	 *	where h is the interpolation function for node i.
+	 *	Same thing for Bb except the last column that does not exist.
+	 */
+
+	int i;
+
+	double dh1dh7[3][NUMNODESMINI];
+	double l1l6[NUMNODESP1];
+
+	/*Get dh1dh7 in actual coordinate system: */
+	GetNodalFunctionsMINIDerivatives(&dh1dh7[0][0],xyz_list, gauss);
+	GetNodalFunctionsP1(l1l6, gauss);
+
+	/*Build B: */
+	for (i=0;i<NUMNODESMINI;i++){
+		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i)=dh1dh7[0][i]; //B[0][NDOF4*i]=dh1dh6[0][i];
+		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+1)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+2)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+1)=dh1dh7[1][i];
+		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+2)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+1)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+2)=dh1dh7[2][i];
+		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i)=(float).5*dh1dh7[1][i]; 
+		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+1)=(float).5*dh1dh7[0][i]; 
+		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+2)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*4+NDOF4*i)=(float).5*dh1dh7[2][i];
+		*(B+(NDOF4*NUMNODESP1+3)*4+NDOF4*i+1)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*4+NDOF4*i+2)=(float).5*dh1dh7[0][i];
+		*(B+(NDOF4*NUMNODESP1+3)*5+NDOF4*i)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*5+NDOF4*i+1)=(float).5*dh1dh7[2][i];
+		*(B+(NDOF4*NUMNODESP1+3)*5+NDOF4*i+2)=(float).5*dh1dh7[1][i];
+		*(B+(NDOF4*NUMNODESP1+3)*6+NDOF4*i)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*6+NDOF4*i+1)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*6+NDOF4*i+2)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*7+NDOF4*i)=dh1dh7[0][i];
+		*(B+(NDOF4*NUMNODESP1+3)*7+NDOF4*i+1)=dh1dh7[1][i];
+		*(B+(NDOF4*NUMNODESP1+3)*7+NDOF4*i+2)=dh1dh7[2][i];
+	}
+
+	for (i=0;i<NUMNODESP1;i++){ //last column not for the bubble function
+		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+3)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+3)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+3)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+3)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*4+NDOF4*i+3)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*5+NDOF4*i+3)=0;
+		*(B+(NDOF4*NUMNODESP1+3)*6+NDOF4*i+3)=l1l6[i];
+		*(B+(NDOF4*NUMNODESP1+3)*7+NDOF4*i+3)=0;
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBprimeStokes {{{1*/
+void PentaRef::GetBprimeStokes(double* B_prime, double* xyz_list, GaussPenta* gauss){
+	/*	Compute B'  matrix. B'=[B1' B2' B3' B4' B5' B6' Bb'] where Bi' is of size 3*NDOF2. 
+	 *	For node i, Bi' can be expressed in the actual coordinate system
+	 *	by: 
+	 *				Bi'=[  dh/dx   0          0       0]
+	 *					 [   0      dh/dy      0       0]
+	 *					 [   0      0         dh/dz    0]
+	 *					 [  dh/dy   dh/dx      0       0]
+	 *					 [  dh/dz   0        dh/dx     0]
+	 *					 [   0      dh/dz    dh/dy     0]
+	 *					 [  dh/dx   dh/dy    dh/dz     0]
+	 *					 [   0      0          0       h]
+	 *	where h is the interpolation function for node i.
+	 *
+	 * 	Same thing for the bubble fonction except that there is no fourth column
+	 */
+
+	int i;
+	double dh1dh7[3][NUMNODESMINI];
+	double l1l6[NUMNODESP1];
+
+	/*Get dh1dh7 in actual coordinate system: */
+	GetNodalFunctionsMINIDerivatives(&dh1dh7[0][0],xyz_list, gauss);
+	GetNodalFunctionsP1(l1l6, gauss);
+
+	/*B_primeuild B_prime: */
+	for (i=0;i<NUMNODESMINI;i++){
+		*(B_prime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i)=dh1dh7[0][i]; //B_prime[0][NDOF4*i]=dh1dh6[0][i];
+		*(B_prime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+1)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+2)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+1)=dh1dh7[1][i];
+		*(B_prime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+2)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+1)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+2)=dh1dh7[2][i];
+		*(B_prime+(NDOF4*NUMNODESP1+3)*3+NDOF4*i)=dh1dh7[1][i]; 
+		*(B_prime+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+1)=dh1dh7[0][i]; 
+		*(B_prime+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+2)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*4+NDOF4*i)=dh1dh7[2][i];
+		*(B_prime+(NDOF4*NUMNODESP1+3)*4+NDOF4*i+1)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*4+NDOF4*i+2)=dh1dh7[0][i];
+		*(B_prime+(NDOF4*NUMNODESP1+3)*5+NDOF4*i)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*5+NDOF4*i+1)=dh1dh7[2][i];
+		*(B_prime+(NDOF4*NUMNODESP1+3)*5+NDOF4*i+2)=dh1dh7[1][i];
+		*(B_prime+(NDOF4*NUMNODESP1+3)*6+NDOF4*i)=dh1dh7[0][i];
+		*(B_prime+(NDOF4*NUMNODESP1+3)*6+NDOF4*i+1)=dh1dh7[1][i];
+		*(B_prime+(NDOF4*NUMNODESP1+3)*6+NDOF4*i+2)=dh1dh7[2][i];
+		*(B_prime+(NDOF4*NUMNODESP1+3)*7+NDOF4*i)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*7+NDOF4*i+1)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*7+NDOF4*i+2)=0;
+	}
+
+	for (i=0;i<NUMNODESP1;i++){ //last column not for the bubble function
+		*(B_prime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+3)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+3)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+3)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+3)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*4+NDOF4*i+3)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*5+NDOF4*i+3)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*6+NDOF4*i+3)=0;
+		*(B_prime+(NDOF4*NUMNODESP1+3)*7+NDOF4*i+3)=l1l6[i];
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBAdvec{{{1*/
+void PentaRef::GetBAdvec(double* B_advec, double* xyz_list, GaussPenta* gauss){
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_advec =[ h ]
+	 *                 [ h ]
+	 *                 [ h ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*NUMNODESP1)
+	 */
+
+	/*Same thing in the actual coordinate system: */
+	double l1l6[6];
+
+	/*Get dh1dh2dh3 in actual coordinates system : */
+	GetNodalFunctionsP1(l1l6, gauss);
+
+	/*Build B': */
+	for (int i=0;i<NUMNODESP1;i++){
+		*(B_advec+NDOF1*NUMNODESP1*0+NDOF1*i)=l1l6[i]; 
+		*(B_advec+NDOF1*NUMNODESP1*1+NDOF1*i)=l1l6[i]; 
+		*(B_advec+NDOF1*NUMNODESP1*2+NDOF1*i)=l1l6[i]; 
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBConduct{{{1*/
+void PentaRef::GetBConduct(double* B_conduct, double* xyz_list, GaussPenta* gauss){
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_conduct=[ dh/dx ]
+	 *                  [ dh/dy ]
+	 *                  [ dh/dz ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*NUMNODESP1)
+	 */
+
+	/*Same thing in the actual coordinate system: */
+	double dh1dh6[3][NUMNODESP1];
+
+	/*Get dh1dh2dh3 in actual coordinates system : */
+	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list,gauss);
+
+	/*Build B': */
+	for (int i=0;i<NUMNODESP1;i++){
+		*(B_conduct+NDOF1*NUMNODESP1*0+NDOF1*i)=dh1dh6[0][i]; 
+		*(B_conduct+NDOF1*NUMNODESP1*1+NDOF1*i)=dh1dh6[1][i]; 
+		*(B_conduct+NDOF1*NUMNODESP1*2+NDOF1*i)=dh1dh6[2][i]; 
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBVert{{{1*/
+void PentaRef::GetBVert(double* B, double* xyz_list, GaussPenta* gauss){
+	/*	Compute B  matrix. B=[dh1/dz dh2/dz dh3/dz dh4/dz dh5/dz dh6/dz];
+		where hi is the interpolation function for node i.*/
+
+	int i;
+	double dh1dh6[3][NUMNODESP1];
+
+	/*Get dh1dh6 in actual coordinate system: */
+	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list, gauss);
+
+	/*Build B: */
+	for (i=0;i<NUMNODESP1;i++){
+		B[i]=dh1dh6[2][i];  
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBprimeAdvec{{{1*/
+void PentaRef::GetBprimeAdvec(double* Bprime_advec, double* xyz_list, GaussPenta* gauss){
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Biprime_advec=[ dh/dx ]
+	 *                     [ dh/dy ]
+	 *                     [ dh/dz ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*NUMNODESP1)
+	 */
+
+	/*Same thing in the actual coordinate system: */
+	double dh1dh6[3][NUMNODESP1];
+
+	/*Get dh1dh2dh3 in actual coordinates system : */
+	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list,gauss);
+
+	/*Build B': */
+	for (int i=0;i<NUMNODESP1;i++){
+		*(Bprime_advec+NDOF1*NUMNODESP1*0+NDOF1*i)=dh1dh6[0][i]; 
+		*(Bprime_advec+NDOF1*NUMNODESP1*1+NDOF1*i)=dh1dh6[1][i]; 
+		*(Bprime_advec+NDOF1*NUMNODESP1*2+NDOF1*i)=dh1dh6[2][i]; 
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBprimeVert{{{1*/
+void PentaRef::GetBprimeVert(double* B, double* xyz_list, GaussPenta* gauss){
+	/* Compute Bprime  matrix. Bprime=[L1 L2 L3 L4 L5 L6] where Li is the nodal function for node i*/
+
+	GetNodalFunctionsP1(B, gauss);
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetL{{{1*/
+void PentaRef::GetL(double* L, GaussPenta* gauss, int numdof){
+	/*Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
+	 ** For node i, Li can be expressed in the actual coordinate system
+	 ** by: 
+	 **       numdof=1: 
+	 **                 Li=h;
+	 **       numdof=2:
+	 **                 Li=[ h   0 ]
+	 **                    [ 0   h ]
+	 ** where h is the interpolation function for node i.
+	 **
+	 ** We assume L has been allocated already, of size: NUMNODESP1 (numdof=1), or numdofx(numdof*NUMNODESP1) (numdof=2)
+	 **/
+
+	int i;
+	double l1l6[6];
+
+	/*Get l1l6 in actual coordinate system: */
+	GetNodalFunctionsP1(l1l6,gauss);
+
+	/*Build L: */
+	if(numdof==1){
+		for (i=0;i<NUMNODESP1;i++){
+			L[i]=l1l6[i]; 
+		}
+	}
+	else{
+		for (i=0;i<NUMNODESP1;i++){
+			*(L+numdof*NUMNODESP1*0+numdof*i)=l1l6[i]; 
+			*(L+numdof*NUMNODESP1*0+numdof*i+1)=0;
+			*(L+numdof*NUMNODESP1*1+numdof*i)=0;
+			*(L+numdof*NUMNODESP1*1+numdof*i+1)=l1l6[i];
+		}
+	}
+} 
+/*}}}*/
+/*FUNCTION PentaRef::GetLStokes{{{1*/
+void PentaRef::GetLStokes(double* LStokes, GaussPenta* gauss){
+	/*
+	 * Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
+	 * For node i, Li can be expressed in the actual coordinate system
+	 * by: 
+	 *       Li=[ h 0 ]
+	 *	 	      [ 0 h ]
+	 *		      [ 0 0 ]
+	 *		      [ 0 0 ]
+	 * where h is the interpolation function for node i.
+	 */
+
+	const int num_dof=4;
+	double l1l2l3[NUMNODESP1_2d];
+
+	/*Get l1l2l3 in actual coordinate system: */
+	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	l1l2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	l1l2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	/*Build LStokes: */
+	for (int i=0;i<3;i++){
+		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+0)=l1l2l3[i];
+		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+1)=0.;
+		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+2)=0.;
+		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+3)=0.;
+
+		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+0)=0.;
+		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+1)=l1l2l3[i];
+		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+2)=0.;
+		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+3)=0.;
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetLprimeStokes {{{1*/
+void PentaRef::GetLprimeStokes(double* LprimeStokes, double* xyz_list, GaussPenta* gauss){
+
+	/*
+	 * Compute Lprime  matrix. Lprime=[Lp1 Lp2 Lp3] where Lpi is square and of size numdof. 
+	 * For node i, Lpi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Lpi=[ h    0    0   0]1
+	 *		       [ 0    h    0   0]2
+	 *		       [ h    0    0   0]3
+	 *		       [ 0    h    0   0]4
+	 *		       [ 0    0    h   0]5
+	 *		       [ 0    0    h   0]6
+	 *		       [ 0    0  dh/dz 0]7
+	 *		       [ 0    0  dh/dz 0]8
+	 *		       [ 0    0  dh/dz 0]9
+	 *		       [dh/dz 0  dh/dx 0]0
+	 *		       [ 0 dh/dz dh/dy 0]1
+	 *           [ 0    0    0   h]2
+	 *           [ 0    0    0   h]3
+	 *           [ 0    0    0   h]4
+	 *
+	 *       Li=[ h    0    0   0]1
+	 *	 	      [ 0    h    0   0]2
+	 *		      [ 0    0    h   0]3
+	 *		      [ 0    0    h   0]4
+	 *	 	      [ h    0    0   0]5
+	 *	 	      [ 0    h    0   0]6
+	 *	 	      [ h    0    0   0]7
+	 *	 	      [ 0    h    0   0]8
+	 *		      [ 0    0    h   0]9
+	 *		      [ 0    0    h   0]0
+	 *		      [ 0    0    h   0]1
+	 *	 	      [ h    0    0   0]2
+	 *	 	      [ 0    h    0   0]3
+	 *		      [ 0    0    h   0]4
+	 * where h is the interpolation function for node i.
+	 */
+	int i;
+	int num_dof=4;
+
+	double l1l2l3[NUMNODESP1_2d];
+	double dh1dh6[3][NUMNODESP1];
+
+	/*Get l1l2l3 in actual coordinate system: */
+	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	l1l2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	l1l2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list,gauss);
+
+	/*Build LprimeStokes: */
+	for (i=0;i<3;i++){
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i)=l1l2l3[i]; //LprimeStokes[0][NDOF2*i]=dh1dh3[0][i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+2)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+1)=l1l2l3[i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+2)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i)=l1l2l3[i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+2)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+1)=l1l2l3[i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+2)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+2)=l1l2l3[i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+2)=l1l2l3[i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+2)=dh1dh6[2][i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+2)=dh1dh6[2][i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*8+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*8+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*8+num_dof*i+2)=dh1dh6[2][i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*8+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*9+num_dof*i)=dh1dh6[2][i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*9+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*9+num_dof*i+2)=dh1dh6[0][i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*9+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*10+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*10+num_dof*i+1)=dh1dh6[2][i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*10+num_dof*i+2)=dh1dh6[1][i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*10+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*11+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*11+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*11+num_dof*i+2)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*11+num_dof*i+3)=l1l2l3[i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*12+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*12+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*12+num_dof*i+2)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*12+num_dof*i+3)=l1l2l3[i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*13+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*13+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*13+num_dof*i+2)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*13+num_dof*i+3)=l1l2l3[i];
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetLMacAyealStokes {{{1*/
+void PentaRef::GetLMacAyealStokes(double* LStokes, GaussPenta* gauss){
+	/*
+	 * Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
+	 * For node i, Li can be expressed in the actual coordinate system
+	 * by: 
+	 *       Li=[ h    0 ]
+	 *	 	      [ 0    h ]
+	 *	 	      [ h    0 ]
+	 *	 	      [ 0    h ]
+	 *	 	      [ h    0 ]
+	 *	 	      [ 0    h ]
+	 *	 	      [ h    0 ]
+	 *	 	      [ 0    h ]
+	 * where h is the interpolation function for node i.
+	 */
+
+	int i;
+	int num_dof=2;
+
+	double l1l2l3[NUMNODESP1_2d];
+
+
+	/*Get l1l2l3 in actual coordinate system: */
+	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	l1l2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	l1l2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	/*Build LStokes: */
+	for (i=0;i<3;i++){
+		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i)=l1l2l3[i]; //LStokes[0][NDOF2*i]=dh1dh3[0][i];
+		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+1)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+1)=l1l2l3[i];
+		*(LStokes+num_dof*NUMNODESP1_2d*2+num_dof*i)=l1l2l3[i];
+		*(LStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+1)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*3+num_dof*i)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+1)=l1l2l3[i];
+		*(LStokes+num_dof*NUMNODESP1_2d*4+num_dof*i)=l1l2l3[i];
+		*(LStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+1)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*5+num_dof*i)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+1)=l1l2l3[i];
+		*(LStokes+num_dof*NUMNODESP1_2d*6+num_dof*i)=l1l2l3[i];
+		*(LStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+1)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*7+num_dof*i)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+1)=l1l2l3[i];
+
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetLprimeMacAyealStokes {{{1*/
+void PentaRef::GetLprimeMacAyealStokes(double* LprimeStokes, double* xyz_list, GaussPenta* gauss){
+
+	/*
+	 * Compute Lprime  matrix. Lprime=[Lp1 Lp2 Lp3] where Lpi is square and of size numdof. 
+	 * For node i, Lpi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Lpi=[ h    0    0   0]
+	 *		       [ 0    h    0   0]
+	 *		       [ 0    0    h   0]
+	 *		       [ 0    0    h   0]
+	 *		       [ 0    0  dh/dz 0]
+	 *		       [ 0    0  dh/dz 0]
+	 *           [ 0    0    0   h]
+	 *           [ 0    0    0   h]
+	 * where h is the interpolation function for node i.
+	 */
+	int i;
+	int num_dof=4;
+
+	double l1l2l3[NUMNODESP1_2d];
+	double dh1dh6[3][NUMNODESP1];
+
+	/*Get l1l2l3 in actual coordinate system: */
+	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	l1l2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	l1l2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list,gauss);
+
+	/*Build LprimeStokes: */
+	for (i=0;i<3;i++){
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i)=l1l2l3[i]; //LprimeStokes[0][NDOF2*i]=dh1dh3[0][i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+2)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+1)=l1l2l3[i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+2)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+2)=l1l2l3[i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+2)=l1l2l3[i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+2)=dh1dh6[2][i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+2)=dh1dh6[2][i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+3)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+2)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+3)=l1l2l3[i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+2)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+3)=l1l2l3[i];
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetLStokesMacAyeal {{{1*/
+void PentaRef::GetLStokesMacAyeal(double* LStokes, GaussPenta* gauss){
+	/*
+	 * Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
+	 * For node i, Li can be expressed in the actual coordinate system
+	 * by: 
+	 *       Li=[ h    0    0   0]
+	 *	 	      [ 0    h    0   0]
+	 *		      [ 0    0    h   0]
+	 *		      [ 0    0    h   0]
+	 * where h is the interpolation function for node i.
+	 */
+
+	int i;
+	int num_dof=4;
+
+	double l1l2l3[NUMNODESP1_2d];
+
+
+	/*Get l1l2l3 in actual coordinate system: */
+	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	l1l2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	l1l2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	/*Build LStokes: */
+	for (i=0;i<3;i++){
+		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i)=l1l2l3[i]; //LStokes[0][NDOF2*i]=dh1dh3[0][i];
+		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+1)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+2)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+3)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+1)=l1l2l3[i];
+		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+2)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+3)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*2+num_dof*i)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+1)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+2)=l1l2l3[i];
+		*(LStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+3)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*3+num_dof*i)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+1)=0;
+		*(LStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+2)=l1l2l3[i];
+		*(LStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+3)=0;
+
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetLprimeStokesMacAyeal {{{1*/
+void PentaRef::GetLprimeStokesMacAyeal(double* LprimeStokes, double* xyz_list, GaussPenta* gauss){
+
+	/*
+	 * Compute Lprime  matrix. Lprime=[Lp1 Lp2 Lp3] where Lpi is square and of size numdof. 
+	 * For node i, Lpi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Lpi=[ h    0 ]
+	 *		       [ 0    h ]
+	 *		       [ h    0 ]
+	 *		       [ 0    h ]
+	 * where h is the interpolation function for node i.
+	 */
+	int i;
+	int num_dof=2;
+
+	double l1l2l3[NUMNODESP1_2d];
+	double dh1dh6[3][NUMNODESP1];
+
+	/*Get l1l2l3 in actual coordinate system: */
+	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	l1l2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	l1l2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list,gauss);
+
+	/*Build LprimeStokes: */
+	for (i=0;i<3;i++){
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i)=l1l2l3[i]; //LprimeStokes[0][NDOF2*i]=dh1dh3[0][i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+1)=l1l2l3[i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i)=l1l2l3[i];
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+1)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i)=0;
+		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+1)=l1l2l3[i];
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetJacobian {{{1*/
+void PentaRef::GetJacobian(double* J, double* xyz_list,GaussPenta* gauss){
+
+	int i,j;
+
+	/*The Jacobian is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	double A1,A2,A3; //area coordinates
+	double xi,eta,zi; //parametric coordinates
+
+	double x1,x2,x3,x4,x5,x6;
+	double y1,y2,y3,y4,y5,y6;
+	double z1,z2,z3,z4,z5,z6;
+
+	/*Figure out xi,eta and zi (parametric coordinates), for this gaussian point: */
+	A1=gauss->coord1;
+	A2=gauss->coord2;
+	A3=gauss->coord3;
+
+	xi=A2-A1;
+	eta=SQRT3*A3;
+	zi=gauss->coord4;
+
+	x1=*(xyz_list+3*0+0);
+	x2=*(xyz_list+3*1+0);
+	x3=*(xyz_list+3*2+0);
+	x4=*(xyz_list+3*3+0);
+	x5=*(xyz_list+3*4+0);
+	x6=*(xyz_list+3*5+0);
+
+	y1=*(xyz_list+3*0+1);
+	y2=*(xyz_list+3*1+1);
+	y3=*(xyz_list+3*2+1);
+	y4=*(xyz_list+3*3+1);
+	y5=*(xyz_list+3*4+1);
+	y6=*(xyz_list+3*5+1);
+
+	z1=*(xyz_list+3*0+2);
+	z2=*(xyz_list+3*1+2);
+	z3=*(xyz_list+3*2+2);
+	z4=*(xyz_list+3*3+2);
+	z5=*(xyz_list+3*4+2);
+	z6=*(xyz_list+3*5+2);
+
+	*(J+NDOF3*0+0)=0.25*(x1-x2-x4+x5)*zi+0.25*(-x1+x2-x4+x5);
+	*(J+NDOF3*1+0)=SQRT3/12.0*(x1+x2-2*x3-x4-x5+2*x6)*zi+SQRT3/12.0*(-x1-x2+2*x3-x4-x5+2*x6);
+	*(J+NDOF3*2+0)=SQRT3/12.0*(x1+x2-2*x3-x4-x5+2*x6)*eta+1/4*(x1-x2-x4+x5)*xi +0.25*(-x1+x5-x2+x4);
+
+	*(J+NDOF3*0+1)=0.25*(y1-y2-y4+y5)*zi+0.25*(-y1+y2-y4+y5);
+	*(J+NDOF3*1+1)=SQRT3/12.0*(y1+y2-2*y3-y4-y5+2*y6)*zi+SQRT3/12.0*(-y1-y2+2*y3-y4-y5+2*y6);
+	*(J+NDOF3*2+1)=SQRT3/12.0*(y1+y2-2*y3-y4-y5+2*y6)*eta+0.25*(y1-y2-y4+y5)*xi+0.25*(y4-y1+y5-y2);
+
+	*(J+NDOF3*0+2)=0.25*(z1-z2-z4+z5)*zi+0.25*(-z1+z2-z4+z5);
+	*(J+NDOF3*1+2)=SQRT3/12.0*(z1+z2-2*z3-z4-z5+2*z6)*zi+SQRT3/12.0*(-z1-z2+2*z3-z4-z5+2*z6);
+	*(J+NDOF3*2+2)=SQRT3/12.0*(z1+z2-2*z3-z4-z5+2*z6)*eta+0.25*(z1-z2-z4+z5)*xi+0.25*(-z1+z5-z2+z4);
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetJacobianDeterminant {{{1*/
+void PentaRef::GetJacobianDeterminant(double*  Jdet, double* xyz_list,GaussPenta* gauss){
+	/*On a penta, Jacobian varies according to coordinates. We need to get the Jacobian, and take 
+	 * the determinant of it: */
+	double J[3][3];
+
+	/*Get Jacobian*/
+	GetJacobian(&J[0][0],xyz_list,gauss);
+
+	/*Get Determinant*/
+	Matrix3x3Determinant(Jdet,&J[0][0]);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetTriaJacobianDeterminant{{{1*/
+void PentaRef::GetTriaJacobianDeterminant(double*  Jdet, double* xyz_list,GaussPenta* gauss){
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	double x1,x2,x3,y1,y2,y3,z1,z2,z3;
+
+	x1=*(xyz_list+3*0+0);
+	y1=*(xyz_list+3*0+1);
+	z1=*(xyz_list+3*0+2);
+	x2=*(xyz_list+3*1+0);
+	y2=*(xyz_list+3*1+1);
+	z2=*(xyz_list+3*1+2);
+	x3=*(xyz_list+3*2+0);
+	y3=*(xyz_list+3*2+1);
+	z3=*(xyz_list+3*2+2);
+
+	/*Jdet = norm( AB ^ AC ) / (2 * area of the reference triangle), with areaRef=sqrt(3) */
+	*Jdet=SQRT3/6.0*pow(pow(((y2-y1)*(z3-z1)-(z2-z1)*(y3-y1)),2.0)+pow(((z2-z1)*(x3-x1)-(x2-x1)*(z3-z1)),2.0)+pow(((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)),2.0),0.5);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetSegmentJacobianDeterminant{{{1*/
+void PentaRef::GetSegmentJacobianDeterminant(double*  Jdet, double* xyz_list,GaussPenta* gauss){
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	double x1,x2,y1,y2,z1,z2;
+
+	x1=*(xyz_list+3*0+0);
+	y1=*(xyz_list+3*0+1);
+	z1=*(xyz_list+3*0+2);
+	x2=*(xyz_list+3*1+0);
+	y2=*(xyz_list+3*1+1);
+	z2=*(xyz_list+3*1+2);
+
+	*Jdet=1.0/2.0*sqrt(pow(x2-x1,2.) + pow(y2-y1,2.) + pow(z2-z1,2.));
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetJacobianInvert {{{1*/
+void PentaRef::GetJacobianInvert(double* Jinv, double* xyz_list,GaussPenta* gauss){
+
+	/*Jacobian*/
+	double J[3][3];
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J[0][0], xyz_list, gauss);
+
+	/*Invert Jacobian matrix: */
+	Matrix3x3Invert(Jinv,&J[0][0]);
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsMINI{{{1*/
+void PentaRef::GetNodalFunctionsMINI(double* l1l7, GaussPenta* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	l1l7[0]=gauss->coord1*(1.0-gauss->coord4)/2.0;
+	l1l7[1]=gauss->coord2*(1.0-gauss->coord4)/2.0;
+	l1l7[2]=gauss->coord3*(1.0-gauss->coord4)/2.0;
+	l1l7[3]=gauss->coord1*(1.0+gauss->coord4)/2.0;
+	l1l7[4]=gauss->coord2*(1.0+gauss->coord4)/2.0;
+	l1l7[5]=gauss->coord3*(1.0+gauss->coord4)/2.0;
+	l1l7[6]=27*gauss->coord1*gauss->coord2*gauss->coord3*(1.0+gauss->coord4)*(1.0-gauss->coord4);
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsMINIDerivatives{{{1*/
+void PentaRef::GetNodalFunctionsMINIDerivatives(double* dh1dh7,double* xyz_list, GaussPenta* gauss){
+
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * actual coordinate system): */
+
+	int       i;
+	double    dh1dh7_ref[3][NUMNODESMINI];
+	double    Jinv[3][3];
+
+	/*Get derivative values with respect to parametric coordinate system: */
+	GetNodalFunctionsMINIDerivativesReference(&dh1dh7_ref[0][0], gauss); 
+
+	/*Get Jacobian invert: */
+	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
+
+	/*Build dh1dh6: 
+	 *
+	 * [dhi/dx]= Jinv'*[dhi/dr]
+	 * [dhi/dy]        [dhi/ds]
+	 * [dhi/dz]        [dhi/dzeta]
+	 */
+
+	for (i=0;i<NUMNODESMINI;i++){
+		*(dh1dh7+NUMNODESMINI*0+i)=Jinv[0][0]*dh1dh7_ref[0][i]+Jinv[0][1]*dh1dh7_ref[1][i]+Jinv[0][2]*dh1dh7_ref[2][i];
+		*(dh1dh7+NUMNODESMINI*1+i)=Jinv[1][0]*dh1dh7_ref[0][i]+Jinv[1][1]*dh1dh7_ref[1][i]+Jinv[1][2]*dh1dh7_ref[2][i];
+		*(dh1dh7+NUMNODESMINI*2+i)=Jinv[2][0]*dh1dh7_ref[0][i]+Jinv[2][1]*dh1dh7_ref[1][i]+Jinv[2][2]*dh1dh7_ref[2][i];
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsMINIDerivativesReference{{{1*/
+void PentaRef::GetNodalFunctionsMINIDerivativesReference(double* dl1dl7,GaussPenta* gauss){
+
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * natural coordinate system) at the gaussian point. */
+	double r=gauss->coord2-gauss->coord1;
+	double s=-3.0/SQRT3*(gauss->coord1+gauss->coord2-2.0/3.0);
+	double zeta=gauss->coord4;
+
+	/*First nodal function: */
+	*(dl1dl7+NUMNODESMINI*0+0)=-0.5*(1.0-zeta)/2.0;
+	*(dl1dl7+NUMNODESMINI*1+0)=-SQRT3/6.0*(1.0-zeta)/2.0;
+	*(dl1dl7+NUMNODESMINI*2+0)=-0.5*(-0.5*r-SQRT3/6.0*s+ONETHIRD);
+
+	/*Second nodal function: */
+	*(dl1dl7+NUMNODESMINI*0+1)=0.5*(1.0-zeta)/2.0;
+	*(dl1dl7+NUMNODESMINI*1+1)=-SQRT3/6.0*(1.0-zeta)/2.0;
+	*(dl1dl7+NUMNODESMINI*2+1)=-0.5*(0.5*r-SQRT3/6.0*s+ONETHIRD);
+
+	/*Third nodal function: */
+	*(dl1dl7+NUMNODESMINI*0+2)=0;
+	*(dl1dl7+NUMNODESMINI*1+2)=SQRT3/3.0*(1.0-zeta)/2.0;
+	*(dl1dl7+NUMNODESMINI*2+2)=-0.5*(SQRT3/3.0*s+ONETHIRD);
+
+	/*Fourth nodal function: */
+	*(dl1dl7+NUMNODESMINI*0+3)=-0.5*(1.0+zeta)/2.0;
+	*(dl1dl7+NUMNODESMINI*1+3)=-SQRT3/6.0*(1.0+zeta)/2.0;
+	*(dl1dl7+NUMNODESMINI*2+3)=0.5*(-0.5*r-SQRT3/6.0*s+ONETHIRD);
+
+	/*Fith nodal function: */
+	*(dl1dl7+NUMNODESMINI*0+4)=0.5*(1.0+zeta)/2.0;
+	*(dl1dl7+NUMNODESMINI*1+4)=-SQRT3/6.0*(1.0+zeta)/2.0;
+	*(dl1dl7+NUMNODESMINI*2+4)=0.5*(0.5*r-SQRT3/6.0*s+ONETHIRD);
+
+	/*Sixth nodal function: */
+	*(dl1dl7+NUMNODESMINI*0+5)=0;
+	*(dl1dl7+NUMNODESMINI*1+5)=SQRT3/3.0*(1.0+zeta)/2.0;
+	*(dl1dl7+NUMNODESMINI*2+5)=0.5*(SQRT3/3.0*s+ONETHIRD);
+
+	/*Seventh nodal function: */
+	*(dl1dl7+NUMNODESMINI*0+6)=9.0/2.0*r*(1.0+zeta)*(zeta-1.0)*(SQRT3*s+1.0);
+	*(dl1dl7+NUMNODESMINI*1+6)=9.0/4.0*(1+zeta)*(1-zeta)*(SQRT3*pow(s,2.0)-2.0*s-SQRT3*pow(r,2.0));
+	*(dl1dl7+NUMNODESMINI*2+6)=27*gauss->coord1*gauss->coord2*gauss->coord3*(-2.0*zeta);
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsP1 {{{1*/
+void PentaRef::GetNodalFunctionsP1(double* l1l6, GaussPenta* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	l1l6[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	l1l6[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	l1l6[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+	l1l6[3]=gauss->coord1*(1+gauss->coord4)/2.0;
+	l1l6[4]=gauss->coord2*(1+gauss->coord4)/2.0;
+	l1l6[5]=gauss->coord3*(1+gauss->coord4)/2.0;
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsP1Derivatives {{{1*/
+void PentaRef::GetNodalFunctionsP1Derivatives(double* dh1dh6,double* xyz_list, GaussPenta* gauss){
+
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * actual coordinate system): */
+	double    dh1dh6_ref[NDOF3][NUMNODESP1];
+	double    Jinv[NDOF3][NDOF3];
+
+	/*Get derivative values with respect to parametric coordinate system: */
+	GetNodalFunctionsP1DerivativesReference(&dh1dh6_ref[0][0], gauss); 
+
+	/*Get Jacobian invert: */
+	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
+
+	/*Build dh1dh3: 
+	 *
+	 * [dhi/dx]= Jinv*[dhi/dr]
+	 * [dhi/dy]       [dhi/ds]
+	 * [dhi/dz]       [dhi/dn]
+	 */
+
+	for (int i=0;i<NUMNODESP1;i++){
+		*(dh1dh6+NUMNODESP1*0+i)=Jinv[0][0]*dh1dh6_ref[0][i]+Jinv[0][1]*dh1dh6_ref[1][i]+Jinv[0][2]*dh1dh6_ref[2][i];
+		*(dh1dh6+NUMNODESP1*1+i)=Jinv[1][0]*dh1dh6_ref[0][i]+Jinv[1][1]*dh1dh6_ref[1][i]+Jinv[1][2]*dh1dh6_ref[2][i];
+		*(dh1dh6+NUMNODESP1*2+i)=Jinv[2][0]*dh1dh6_ref[0][i]+Jinv[2][1]*dh1dh6_ref[1][i]+Jinv[2][2]*dh1dh6_ref[2][i];
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsP1DerivativesReference {{{1*/
+void PentaRef::GetNodalFunctionsP1DerivativesReference(double* dl1dl6,GaussPenta* gauss){
+
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * natural coordinate system) at the gaussian point. Those values vary along xi,eta,z */
+
+	double A1,A2,A3,z;
+
+	A1=gauss->coord1; _assert_(A1>=0 && A1<=1);//first area coordinate value. In term of xi and eta: A1=(1-xi)/2-eta/(2*SQRT3);
+	A2=gauss->coord2; _assert_(A2>=0 && A2<=1);//second area coordinate value In term of xi and eta: A2=(1+xi)/2-eta/(2*SQRT3);
+	A3=gauss->coord3; _assert_(A3>=0 && A3<=1);//third area coordinate value  In term of xi and eta: A3=y/SQRT3;
+	z =gauss->coord4; _assert_(z>=-1 &&  z<=1);//fourth vertical coordinate value. Corresponding nodal function: (1-z)/2 and (1+z)/2
+
+	/*First nodal function derivatives. The corresponding nodal function is N=A1*(1-z)/2. Its derivatives follow*/
+	*(dl1dl6+NUMNODESP1*0+0)=-0.5*(1.0-z)/2.0;
+	*(dl1dl6+NUMNODESP1*1+0)=-0.5/SQRT3*(1.0-z)/2.0;
+	*(dl1dl6+NUMNODESP1*2+0)=-0.5*A1;
+
+	/*Second nodal function: The corresponding nodal function is N=A2*(1-z)/2. Its derivatives follow*/
+	*(dl1dl6+NUMNODESP1*0+1)=0.5*(1.0-z)/2.0;
+	*(dl1dl6+NUMNODESP1*1+1)=-0.5/SQRT3*(1.0-z)/2.0;
+	*(dl1dl6+NUMNODESP1*2+1)=-0.5*A2;
+
+	/*Third nodal function: The corresponding nodal function is N=A3*(1-z)/2. Its derivatives follow*/
+	*(dl1dl6+NUMNODESP1*0+2)=0.0;
+	*(dl1dl6+NUMNODESP1*1+2)=1.0/SQRT3*(1.0-z)/2.0;
+	*(dl1dl6+NUMNODESP1*2+2)=-0.5*A3;
+
+	/*Fourth nodal function: The corresponding nodal function is N=A1*(1+z)/2. Its derivatives follow*/
+	*(dl1dl6+NUMNODESP1*0+3)=-0.5*(1.0+z)/2.0;
+	*(dl1dl6+NUMNODESP1*1+3)=-0.5/SQRT3*(1.0+z)/2.0;
+	*(dl1dl6+NUMNODESP1*2+3)=0.5*A1;
+
+	/*Fifth nodal function: The corresponding nodal function is N=A2*(1+z)/2. Its derivatives follow*/
+	*(dl1dl6+NUMNODESP1*0+4)=0.5*(1.0+z)/2.0;
+	*(dl1dl6+NUMNODESP1*1+4)=-0.5/SQRT3*(1.0+z)/2.0;
+	*(dl1dl6+NUMNODESP1*2+4)=0.5*A2;
+
+	/*Sixth nodal function: The corresponding nodal function is N=A3*(1+z)/2. Its derivatives follow*/
+	*(dl1dl6+NUMNODESP1*0+5)=0.0;
+	*(dl1dl6+NUMNODESP1*1+5)=1.0/SQRT3*(1.0+z)/2.0;
+	*(dl1dl6+NUMNODESP1*2+5)=0.5*A3;
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetQuadNodalFunctions {{{1*/
+void PentaRef::GetQuadNodalFunctions(double* l1l4,GaussPenta* gauss,int index1,int index2,int index3,int index4){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	double BasisFunctions[6];
+
+	GetNodalFunctionsP1(&BasisFunctions[0],gauss);
+
+	_assert_(index1>=0 && index1<6);
+	_assert_(index2>=0 && index2<6);
+	_assert_(index3>=0 && index3<6);
+	_assert_(index4>=0 && index4<6);
+
+	l1l4[0]=BasisFunctions[index1];
+	l1l4[1]=BasisFunctions[index2];
+	l1l4[2]=BasisFunctions[index3];
+	l1l4[3]=BasisFunctions[index4];
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetQuadJacobianDeterminant{{{1*/
+void PentaRef::GetQuadJacobianDeterminant(double* Jdet,double xyz_list[4][3],GaussPenta* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	double x1,x2,x3,x4,y1,y2,y3,y4,z1,z2,z3,z4;
+
+	x1=xyz_list[0][0];
+	y1=xyz_list[0][1];
+	z1=xyz_list[0][2];
+	x2=xyz_list[1][0];
+	y2=xyz_list[1][1];
+	z2=xyz_list[1][2];
+	x3=xyz_list[2][0];
+	y3=xyz_list[2][1];
+	z3=xyz_list[2][2];
+	x4=xyz_list[3][0];
+	y4=xyz_list[3][1];
+	z4=xyz_list[3][2];
+
+	/*Jdet = (Area of the trapezoid)/(Area trapezoid ref) with AreaRef = 4*/
+	/*Area of a trabezoid = altitude * (base1 + base2)/2 */
+	*Jdet= pow(pow(x2-x1,2.) + pow(y2-y1,2.),0.5) * (z4-z1 + z3-z2)/8;
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetInputValue{{{1*/
+void PentaRef::GetInputValue(double* pvalue,double* plist,GaussPenta* gauss){
+	/*P1 interpolation on Gauss point*/
+
+	/*intermediary*/
+	double l1l6[6];
+
+	/*nodal functions: */
+	GetNodalFunctionsP1(&l1l6[0],gauss);
+
+	/*Assign output pointers:*/
+	*pvalue=l1l6[0]*plist[0]+l1l6[1]*plist[1]+l1l6[2]*plist[2]+l1l6[3]*plist[3]+l1l6[4]*plist[4]+l1l6[5]*plist[5];
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetInputDerivativeValue{{{1*/
+void PentaRef::GetInputDerivativeValue(double* p, double* plist,double* xyz_list, GaussPenta* gauss){
+	/*From node values of parameter p (p_list[0], p_list[1], p_list[2], p_list[3], p_list[4] and p_list[4]), return parameter derivative value at gaussian point specified by gauss_coord:
+	 *   dp/dx=p_list[0]*dh1/dx+p_list[1]*dh2/dx+p_list[2]*dh3/dx+p_list[3]*dh4/dx+p_list[4]*dh5/dx+p_list[5]*dh6/dx;
+	 *   dp/dy=p_list[0]*dh1/dy+p_list[1]*dh2/dy+p_list[2]*dh3/dy+p_list[3]*dh4/dy+p_list[4]*dh5/dy+p_list[5]*dh6/dy;
+	 *   dp/dz=p_list[0]*dh1/dz+p_list[1]*dh2/dz+p_list[2]*dh3/dz+p_list[3]*dh4/dz+p_list[4]*dh5/dz+p_list[5]*dh6/dz;
+	 *
+	 *   p is a vector of size 3x1 already allocated.
+	 */
+	double dh1dh6[3][NUMNODESP1];
+
+	/*Get nodal funnctions derivatives in actual coordinate system: */
+	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list, gauss);
+
+	/*Assign output*/
+	p[0]=plist[0]*dh1dh6[0][0]+plist[1]*dh1dh6[0][1]+plist[2]*dh1dh6[0][2]+plist[3]*dh1dh6[0][3]+plist[4]*dh1dh6[0][4]+plist[5]*dh1dh6[0][5];
+	p[1]=plist[0]*dh1dh6[1][0]+plist[1]*dh1dh6[1][1]+plist[2]*dh1dh6[1][2]+plist[3]*dh1dh6[1][3]+plist[4]*dh1dh6[1][4]+plist[5]*dh1dh6[1][5];
+	p[2]=plist[0]*dh1dh6[2][0]+plist[1]*dh1dh6[2][1]+plist[2]*dh1dh6[2][2]+plist[3]*dh1dh6[2][3]+plist[4]*dh1dh6[2][4]+plist[5]*dh1dh6[2][5];
+
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Elements/PentaRef.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Elements/PentaRef.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Elements/PentaRef.h	(revision 11330)
@@ -0,0 +1,63 @@
+/*!\file:  PentaRef.h
+ * \brief abstract class for handling Penta oriented routines, like nodal functions, 
+ * strain rate generation, etc ...
+ */ 
+
+
+#ifndef _PENTAREF_H_
+#define _PENTAREF_H_
+
+class PentaRef{
+	
+
+	public: 
+		int* element_type_list; //P1CG, P1DG, MINI, P2...
+		int  element_type;
+		
+		PentaRef();
+		PentaRef(const int nummodels);
+		~PentaRef();
+
+		/*Management*/
+		void SetElementType(int type,int type_counter);
+
+		/*Numerics*/
+		void GetNodalFunctionsP1(double* l1l6, GaussPenta* gauss);
+		void GetNodalFunctionsMINI(double* l1l7, GaussPenta* gauss);
+		void GetNodalFunctionsP1Derivatives(double* dh1dh6,double* xyz_list, GaussPenta* gauss);
+		void GetNodalFunctionsMINIDerivatives(double* dh1dh7,double* xyz_list, GaussPenta* gauss);
+		void GetNodalFunctionsP1DerivativesReference(double* dl1dl6,GaussPenta* gauss);
+		void GetNodalFunctionsMINIDerivativesReference(double* dl1dl7,GaussPenta* gauss);
+		void GetQuadNodalFunctions(double* l1l4,GaussPenta* gauss,int index1,int index2,int index3,int index4);
+		void GetQuadJacobianDeterminant(double*  Jdet, double xyz_list[4][3],GaussPenta* gauss);
+		void GetJacobian(double* J, double* xyz_list,GaussPenta* gauss);
+		void GetJacobianDeterminant(double*  Jdet, double* xyz_list,GaussPenta* gauss);
+		void GetTriaJacobianDeterminant(double*  Jdet, double* xyz_list,GaussPenta* gauss);
+		void GetSegmentJacobianDeterminant(double*  Jdet, double* xyz_list,GaussPenta* gauss);
+		void GetJacobianInvert(double*  Jinv, double* xyz_list,GaussPenta* gauss);
+		void GetBMacAyealPattyn(double* B, double* xyz_list, GaussPenta* gauss);
+		void GetBMacAyealStokes(double* B, double* xyz_list, GaussPenta* gauss);
+		void GetBPattyn(double* B, double* xyz_list, GaussPenta* gauss);
+		void GetBStokes(double* B, double* xyz_list, GaussPenta* gauss);
+		void GetBprimeMacAyealStokes(double* Bprime, double* xyz_list, GaussPenta* gauss);
+		void GetBprimePattyn(double* B, double* xyz_list, GaussPenta* gauss);
+		void GetBprimeStokes(double* B_prime, double* xyz_list, GaussPenta* gauss);
+		void GetBprimeVert(double* B, double* xyz_list, GaussPenta* gauss);
+		void GetBAdvec(double* B_advec, double* xyz_list, GaussPenta* gauss);
+		void GetBConduct(double* B_conduct, double* xyz_list, GaussPenta* gauss);
+		void GetBVert(double* B, double* xyz_list, GaussPenta* gauss);
+		void GetBprimeAdvec(double* Bprime_advec, double* xyz_list, GaussPenta* gauss);
+		void GetL(double* L, GaussPenta* gauss,int numdof);
+		void GetLStokes(double* LStokes, GaussPenta* gauss);
+		void GetLprimeStokes(double* LprimeStokes, double* xyz_list, GaussPenta* gauss);
+		void GetLMacAyealStokes(double* LMacAyealStokes, GaussPenta* gauss);
+		void GetLprimeMacAyealStokes(double* LprimeMacAyealStokes, double* xyz_list, GaussPenta* gauss);
+		void GetLStokesMacAyeal(double* LStokesMacAyeal, GaussPenta* gauss);
+		void GetLprimeStokesMacAyeal(double* LprimeStokesMacAyeal, double* xyz_list, GaussPenta* gauss);
+		void GetInputValue(double* pvalue,double* plist, GaussPenta* gauss);
+		void GetInputValue(double* pvalue,double* plist,GaussTria* gauss){_error_("only PentaGauss are supported");};
+		void GetInputDerivativeValue(double* pvalues, double* plist,double* xyz_list, GaussPenta* gauss);
+		void GetInputDerivativeValue(double* pvalues, double* plist,double* xyz_list, GaussTria* gauss){_error_("only PentaGauss are supported");};
+
+};
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Elements/Tria.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Elements/Tria.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Elements/Tria.cpp	(revision 11330)
@@ -0,0 +1,5432 @@
+/*!\file Tria.cpp
+ * \brief: implementation of the Tria object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES 3
+
+/*Constructors/destructor/copy*/
+/*FUNCTION Tria::Tria(){{{1*/
+Tria::Tria(){
+
+	int i;
+
+	this->nodes=NULL;
+	this->matice=NULL;
+	this->matpar=NULL;
+	for(i=0;i<3;i++)this->horizontalneighborsids[i]=UNDEF;
+	this->inputs=NULL;
+	this->parameters=NULL;
+	this->results=NULL;
+
+}
+/*}}}*/
+/*FUNCTION Tria::Tria(int id, int sid,int index, IoModel* iomodel,int nummodels){{{1*/
+Tria::Tria(int tria_id, int tria_sid, int index, IoModel* iomodel,int nummodels)
+	:TriaRef(nummodels)
+	,TriaHook(nummodels,index+1,iomodel){
+		
+		int i;
+		/*id: */
+		this->id=tria_id;
+		this->sid=tria_sid;
+
+		//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+		this->parameters=NULL;
+
+		/*Build horizontalneighborsids list: */
+		_assert_(iomodel->Data(MeshElementconnectivityEnum));
+		//for (i=0;i<3;i++) this->horizontalneighborsids[i]=(int)iomodel->elementconnectivity[3*index+i]-1;
+
+		/*intialize inputs and results: */
+		this->inputs=new Inputs();
+		this->results=new Results();
+
+		/*initialize pointers:*/
+		this->nodes=NULL;
+		this->matice=NULL;
+		this->matpar=NULL;
+
+}
+/*}}}*/
+/*FUNCTION Tria::~Tria(){{{1*/
+Tria::~Tria(){
+	delete inputs;
+	delete results;
+	this->parameters=NULL;
+}
+/*}}}*/
+/*FUNCTION Tria::copy {{{1*/
+Object* Tria::copy() {
+
+	int i;
+	Tria* tria=NULL;
+
+	tria=new Tria();
+
+	//deal with TriaRef mother class
+	tria->element_type_list=(int*)xmalloc(this->numanalyses*sizeof(int));
+	for(i=0;i<this->numanalyses;i++) tria->element_type_list[i]=this->element_type_list[i];
+
+	//deal with TriaHook mother class
+	tria->numanalyses=this->numanalyses;
+	tria->hnodes=new Hook*[tria->numanalyses];
+	for(i=0;i<tria->numanalyses;i++)tria->hnodes[i]=(Hook*)this->hnodes[i]->copy();
+	tria->hmatice=(Hook*)this->hmatice->copy();
+	tria->hmatpar=(Hook*)this->hmatpar->copy();
+
+	/*deal with Tria fields: */
+	tria->id=this->id;
+	tria->sid=this->sid;
+	if(this->inputs){
+		tria->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		tria->inputs=new Inputs();
+	}
+	if(this->results){
+		tria->results=(Results*)this->results->Copy();
+	}
+	else{
+		tria->results=new Results();
+	}
+	/*point parameters: */
+	tria->parameters=this->parameters;
+
+	/*recover objects: */
+	tria->nodes=(Node**)xmalloc(3*sizeof(Node*)); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
+	for(i=0;i<3;i++)tria->nodes[i]=this->nodes[i];
+	tria->matice=(Matice*)tria->hmatice->delivers();
+	tria->matpar=(Matpar*)tria->hmatpar->delivers();
+
+	/*neighbors: */
+	for(i=0;i<3;i++)tria->horizontalneighborsids[i]=this->horizontalneighborsids[i];
+
+	return tria;
+}
+/*}}}*/
+
+/*Marshall*/
+#ifdef _SERIAL_
+/*FUNCTION Tria::Marshall {{{1*/
+void  Tria::Marshall(char** pmarshalled_dataset){
+
+	int   i;
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+	char* marshalled_inputs=NULL;
+	int   marshalled_inputs_size;
+	char* marshalled_results=NULL;
+	int   marshalled_results_size;
+	int   flaghook; //to indicate if hook is NULL or exists
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of Tria: */
+	enum_type=TriaEnum;
+
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+
+	/*marshall Tria data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&sid,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(marshalled_dataset,&numanalyses,sizeof(numanalyses));marshalled_dataset+=sizeof(numanalyses);
+
+	/*Mershall Ref: */
+	for(i=0;i<numanalyses;i++){
+		memcpy(marshalled_dataset,&element_type_list[i],sizeof(element_type_list[i]));marshalled_dataset+=sizeof(element_type_list[i]);
+	}
+
+	/*Marshall hooks: */
+	for(i=0;i<numanalyses;i++){
+		if(hnodes[i]){
+			/*Set flag to 1 as there is a hook */
+			flaghook=1;
+			memcpy(marshalled_dataset,&flaghook,sizeof(flaghook));marshalled_dataset+=sizeof(flaghook);
+			hnodes[i]->Marshall(&marshalled_dataset);
+		}
+		else{
+			/*Set flag to 0 and do not marshall flag as there is no Hook */
+			flaghook=0;
+			memcpy(marshalled_dataset,&flaghook,sizeof(flaghook));marshalled_dataset+=sizeof(flaghook);
+		}
+	}
+	hmatice->Marshall(&marshalled_dataset);
+	hmatpar->Marshall(&marshalled_dataset);
+
+	/*Marshall inputs: */
+	marshalled_inputs_size=inputs->MarshallSize();
+	marshalled_inputs=inputs->Marshall();
+	memcpy(marshalled_dataset,marshalled_inputs,marshalled_inputs_size*sizeof(char));
+	marshalled_dataset+=marshalled_inputs_size;
+
+	/*Marshall results: */
+	marshalled_results_size=results->MarshallSize();
+	marshalled_results=results->Marshall();
+	memcpy(marshalled_dataset,marshalled_results,marshalled_results_size*sizeof(char));
+	marshalled_dataset+=marshalled_results_size;
+
+	/*parameters: don't do anything about it. parameters are marshalled somewhere else!*/
+
+	xfree((void**)&marshalled_inputs);
+	xfree((void**)&marshalled_results);
+
+	/*marshall horizontal neighbors: */
+	memcpy(marshalled_dataset,horizontalneighborsids,3*sizeof(int));marshalled_dataset+=3*sizeof(int);
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+/*FUNCTION Tria::MarshallSize {{{1*/
+int   Tria::MarshallSize(){
+
+	int i;
+	int hnodes_size=0;;
+
+	for(i=0;i<numanalyses;i++){
+		hnodes_size+=sizeof(int); //Flag 0 or 1
+		if (hnodes[i]) hnodes_size+=hnodes[i]->MarshallSize();
+	}
+
+	return sizeof(id)
+	  +sizeof(sid)
+	  +hnodes_size
+	  +sizeof(numanalyses)
+	  +numanalyses*sizeof(int) //element_type_lists
+	  +hmatice->MarshallSize()
+	  +hmatpar->MarshallSize()
+	  +inputs->MarshallSize()
+	  +results->MarshallSize()
+	  +3*sizeof(int)
+	  +sizeof(int); //sizeof(int) for enum type
+}
+/*}}}*/
+/*FUNCTION Tria::Demarshall {{{1*/
+void  Tria::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int i;
+	int flaghook;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&sid,marshalled_dataset,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(&numanalyses,marshalled_dataset,sizeof(numanalyses));marshalled_dataset+=sizeof(numanalyses);
+
+	/*demarshall Ref: */
+	this->element_type_list=(int*)xmalloc(this->numanalyses*sizeof(int));
+	for(i=0;i<numanalyses;i++){ memcpy(&element_type_list[i],marshalled_dataset,sizeof(int));marshalled_dataset+=sizeof(int);}
+
+	/*allocate dynamic memory: */
+	this->hnodes=new Hook*[this->numanalyses];
+	/*demarshall hooks: */
+	for(i=0;i<numanalyses;i++){
+		memcpy(&flaghook,marshalled_dataset,sizeof(flaghook));marshalled_dataset+=sizeof(flaghook);
+		if(flaghook){ // there is a hook so demarshall it
+			hnodes[i]=new Hook();
+			hnodes[i]->Demarshall(&marshalled_dataset);
+		}
+		else hnodes[i]=NULL; //There is no hook so it is NULL
+	}
+	hmatice=new Hook(); hmatice->Demarshall(&marshalled_dataset);
+	hmatpar=new Hook(); hmatpar->Demarshall(&marshalled_dataset);
+
+	/*pointers are garbabe, until configuration is carried out: */
+	nodes=NULL;
+	matice=NULL;
+	matpar=NULL;
+	
+	/*demarshall inputs: */
+	inputs=(Inputs*)DataSetDemarshallRaw(&marshalled_dataset); 
+	results=(Results*)DataSetDemarshallRaw(&marshalled_dataset); 
+
+	/*parameters: may not exist even yet, so let Configure handle it: */
+	this->parameters=NULL;
+
+	/*neighbors: */
+	memcpy(&this->horizontalneighborsids,marshalled_dataset,3*sizeof(int));marshalled_dataset+=3*sizeof(int);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+
+/*Other*/
+/*FUNCTION Tria::AverageOntoPartition {{{1*/
+void  Tria::AverageOntoPartition(Vec partition_contributions,Vec partition_areas,double* vertex_response,double* qmu_part){
+
+	bool      already=false;
+	int       i,j;
+	int       partition[NUMVERTICES];
+	int       offsetsid[NUMVERTICES];
+	int       offsetdof[NUMVERTICES];
+	double    area;
+	double    mean;
+	double    values[3];
+
+	/*First, get the area: */
+	area=this->GetArea();
+
+	/*Figure out the average for this element: */
+	this->GetSidList(&offsetsid[0]);
+	this->GetDofList1(&offsetdof[0]);
+	mean=0;
+	for(i=0;i<NUMVERTICES;i++){
+		partition[i]=(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){
+			VecSetValue(partition_contributions,partition[i],mean*area,ADD_VALUES);
+			VecSetValue(partition_areas,partition[i],area,ADD_VALUES);
+		};
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrix {{{1*/
+void  Tria::CreateKMatrix(Mat Kff, Mat Kfs,Vec df){
+
+	/*retreive parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging mode{{{2*/
+	_assert_(this->nodes && this->matice && this->matpar && this->parameters && this->inputs);
+	/*}}}*/
+	
+	/*Skip if water element*/
+	if(IsOnWater()) return;
+
+	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum: case AdjointHorizAnalysisEnum:
+			Ke=CreateKMatrixDiagnosticMacAyeal();
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			Ke=CreateKMatrixDiagnosticHutter();
+			break;
+		 #endif
+		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
+			Ke=CreateKMatrixSlope();
+			break;
+		case PrognosticAnalysisEnum:
+			Ke=CreateKMatrixPrognostic();
+			break;
+		#ifdef _HAVE_HYDROLOGY_
+		case HydrologyAnalysisEnum:
+			Ke=CreateKMatrixHydrology();
+			break;
+		#endif
+		#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixBalancethickness();
+			break;
+		#endif
+		#ifdef _HAVE_CONTROL_
+		case AdjointBalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixAdjointBalancethickness();
+			break;
+		#endif
+		default:
+			_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixMelting {{{1*/
+ElementMatrix* Tria::CreateKMatrixMelting(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	double     heatcapacity,latentheat;
+	double     Jdet,D_scalar;
+	double     xyz_list[NUMVERTICES][3];
+	double     L[3];
+	GaussTria *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	latentheat=matpar->GetLatentHeat();
+	heatcapacity=matpar->GetHeatCapacity();
+
+	/* Start looping on the number of gauss  (nodes on the bedrock) */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0], gauss);
+
+		D_scalar=latentheat/heatcapacity*gauss->weight*Jdet;
+
+		TripleMultiply(&L[0],numdof,1,0,
+					&D_scalar,1,1,0,
+					&L[0],1,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixPrognostic {{{1*/
+ElementMatrix* Tria::CreateKMatrixPrognostic(void){
+
+	switch(GetElementType()){
+		case P1Enum:
+			return CreateKMatrixPrognostic_CG();
+		case P1DGEnum:
+			return CreateKMatrixPrognostic_DG();
+		default:
+			_error_("Element type %s not supported yet",EnumToStringx(GetElementType()));
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixPrognostic_CG {{{1*/
+ElementMatrix* Tria::CreateKMatrixPrognostic_CG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        stabilization;
+	int        i,j,ig,dim;
+	double     Jdettria,DL_scalar,dt,h;
+	double     vel,vx,vy,dvxdx,dvydy;
+	double     dvx[2],dvy[2];
+	double     v_gauss[2]={0.0};
+	double     xyz_list[NUMVERTICES][3];
+	double     L[NUMVERTICES];
+	double     B[2][NUMVERTICES];
+	double     Bprime[2][NUMVERTICES];
+	double     K[2][2]                        ={0.0};
+	double     KDL[2][2]                      ={0.0};
+	double     DL[2][2]                        ={0.0};
+	double     DLprime[2][2]                   ={0.0};
+	GaussTria *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	this->parameters->FindParam(&stabilization,PrognosticStabilizationEnum);
+	Input* vxaverage_input=NULL;
+	Input* vyaverage_input=NULL;
+	if(dim==2){
+		vxaverage_input=inputs->GetInput(VxEnum); _assert_(vxaverage_input);
+		vyaverage_input=inputs->GetInput(VyEnum); _assert_(vyaverage_input);
+	}
+	else{
+		vxaverage_input=inputs->GetInput(VxAverageEnum); _assert_(vxaverage_input);
+		vyaverage_input=inputs->GetInput(VyAverageEnum); _assert_(vyaverage_input);
+	}
+	h=sqrt(2*this->GetArea());
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		vxaverage_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
+		vyaverage_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
+
+		DL_scalar=gauss->weight*Jdettria;
+
+		TripleMultiply( &L[0],1,numdof,1,
+					&DL_scalar,1,1,0,
+					&L[0],1,numdof,0,
+					&Ke->values[0],1);
+
+		GetBPrognostic(&B[0][0], &xyz_list[0][0], gauss);
+		GetBprimePrognostic(&Bprime[0][0], &xyz_list[0][0], gauss);
+
+		dvxdx=dvx[0];
+		dvydy=dvy[1];
+		DL_scalar=dt*gauss->weight*Jdettria;
+
+		DL[0][0]=DL_scalar*dvxdx;
+		DL[1][1]=DL_scalar*dvydy;
+		DLprime[0][0]=DL_scalar*vx;
+		DLprime[1][1]=DL_scalar*vy;
+
+		TripleMultiply( &B[0][0],2,numdof,1,
+					&DL[0][0],2,2,0,
+					&B[0][0],2,numdof,0,
+					&Ke->values[0],1);
+
+		TripleMultiply( &B[0][0],2,numdof,1,
+					&DLprime[0][0],2,2,0,
+					&Bprime[0][0],2,numdof,0,
+					&Ke->values[0],1);
+
+		if(stabilization==2){
+			/*Streamline upwinding*/
+			vel=sqrt(pow(vx,2.)+pow(vy,2.));
+			K[0][0]=h/(2*vel)*vx*vx;
+			K[1][0]=h/(2*vel)*vy*vx;
+			K[0][1]=h/(2*vel)*vx*vy;
+			K[1][1]=h/(2*vel)*vy*vy;
+		}
+		else if(stabilization==1){
+			/*MacAyeal*/
+			vxaverage_input->GetInputAverage(&vx);
+			vyaverage_input->GetInputAverage(&vy);
+			K[0][0]=h/2.0*fabs(vx);
+			K[0][1]=0.;
+			K[1][0]=0.;
+			K[1][1]=h/2.0*fabs(vy);
+		}
+		if(stabilization==1 || stabilization==2){
+			KDL[0][0]=DL_scalar*K[0][0];
+			KDL[1][0]=DL_scalar*K[1][0];
+			KDL[0][1]=DL_scalar*K[0][1];
+			KDL[1][1]=DL_scalar*K[1][1];
+			TripleMultiply( &Bprime[0][0],2,numdof,1,
+						&KDL[0][0],2,2,0,
+						&Bprime[0][0],2,numdof,0,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixPrognostic_DG {{{1*/
+ElementMatrix* Tria::CreateKMatrixPrognostic_DG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,ig,dim;
+	double     xyz_list[NUMVERTICES][3];
+	double     Jdettria,dt,vx,vy;
+	double     L[NUMVERTICES];
+	double     B[2][NUMVERTICES];
+	double     Bprime[2][NUMVERTICES];
+	double     DL[2][2]={0.0};
+	double     DLprime[2][2]={0.0};
+	double     DL_scalar;
+	GaussTria  *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	Input* vxaverage_input=NULL;
+	Input* vyaverage_input=NULL;
+	if(dim==2){
+		vxaverage_input=inputs->GetInput(VxEnum); _assert_(vxaverage_input);
+		vyaverage_input=inputs->GetInput(VyEnum); _assert_(vyaverage_input);
+	}
+	else{
+		vxaverage_input=inputs->GetInput(VxAverageEnum); _assert_(vxaverage_input);
+		vyaverage_input=inputs->GetInput(VyAverageEnum); _assert_(vyaverage_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		DL_scalar=gauss->weight*Jdettria;
+
+		TripleMultiply( &L[0],1,numdof,1,
+					&DL_scalar,1,1,0,
+					&L[0],1,numdof,0,
+					&Ke->values[0],1);
+
+		/*WARNING: B and Bprime are inverted compared to usual prognostic!!!!*/
+		GetBPrognostic(&Bprime[0][0], &xyz_list[0][0], gauss);
+		GetBprimePrognostic(&B[0][0], &xyz_list[0][0], gauss);
+
+		DL_scalar=-dt*gauss->weight*Jdettria;
+
+		DLprime[0][0]=DL_scalar*vx;
+		DLprime[1][1]=DL_scalar*vy;
+
+		TripleMultiply( &B[0][0],2,numdof,1,
+					&DLprime[0][0],2,2,0,
+					&Bprime[0][0],2,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixSlope {{{1*/
+ElementMatrix* Tria::CreateKMatrixSlope(void){
+
+	/*constants: */
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/* Intermediaries */
+	int        i,j,ig;
+	double     DL_scalar,Jdet;
+	double     xyz_list[NUMVERTICES][3];
+	double     L[1][3];
+	GaussTria *gauss = NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	GetVerticesCoordinates(&xyz_list[0][0],nodes,NUMVERTICES);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		DL_scalar=gauss->weight*Jdet;
+
+		GetL(&L[0][0], &xyz_list[0][0], gauss,NDOF1);
+
+		TripleMultiply(&L[0][0],1,3,1,
+					&DL_scalar,1,1,0,
+					&L[0][0],1,3,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVector {{{1*/
+void  Tria::CreatePVector(Vec pf){
+
+	/*retrive parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*asserts: {{{*/
+	/*if debugging mode, check that all pointers exist*/
+	_assert_(this->nodes && this->matice && this->matpar && this->parameters && this->inputs);
+	/*}}}*/
+	
+	/*Skip if water element*/
+	if(IsOnWater()) return;
+
+	/*Just branch to the correct load generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum:
+			pe=CreatePVectorDiagnosticMacAyeal();
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			pe=CreatePVectorDiagnosticHutter();
+			break;
+		#endif
+		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
+			pe=CreatePVectorSlope();
+			break;
+		case PrognosticAnalysisEnum:
+			pe=CreatePVectorPrognostic();
+			break;
+		#ifdef _HAVE_HYDROLOGY_
+		case HydrologyAnalysisEnum:
+			pe=CreatePVectorHydrology();
+			break;
+		#endif
+		#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			pe=CreatePVectorBalancethickness();
+			break;
+		#endif
+		#ifdef _HAVE_CONTROL_
+		case AdjointBalancethicknessAnalysisEnum:
+			pe=CreatePVectorAdjointBalancethickness();
+			break;
+		case AdjointHorizAnalysisEnum:
+			pe=CreatePVectorAdjointHoriz();
+			break;
+		#endif
+		default:
+			_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+
+	/*Add to global Vector*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorPrognostic{{{1*/
+ElementVector* Tria::CreatePVectorPrognostic(void){
+
+	switch(GetElementType()){
+		case P1Enum:
+			return CreatePVectorPrognostic_CG();
+		case P1DGEnum:
+			return CreatePVectorPrognostic_DG();
+		default:
+			_error_("Element type %s not supported yet",EnumToStringx(GetElementType()));
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorPrognostic_CG {{{1*/
+ElementVector* Tria::CreatePVectorPrognostic_CG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	double     Jdettria,dt;
+	double     surface_mass_balance_g,basal_melting_g,basal_melting_correction_g,thickness_g;
+	double     xyz_list[NUMVERTICES][3];
+	double     L[NUMVERTICES];
+	GaussTria* gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* surface_mass_balance_input=inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(surface_mass_balance_input);
+	Input* basal_melting_input=inputs->GetInput(BasalforcingsMeltingRateEnum);          _assert_(basal_melting_input);
+	Input* basal_melting_correction_input=inputs->GetInput(BasalforcingsMeltingRateCorrectionEnum);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);                             _assert_(thickness_input);
+
+	/*Initialize basal_melting_correction_g to 0, do not forget!:*/
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		surface_mass_balance_input->GetInputValue(&surface_mass_balance_g,gauss);
+		basal_melting_input->GetInputValue(&basal_melting_g,gauss);
+		thickness_input->GetInputValue(&thickness_g,gauss);
+		if(basal_melting_correction_input) basal_melting_correction_input->GetInputValue(&basal_melting_correction_g,gauss);
+
+		for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(thickness_g+dt*(surface_mass_balance_g-basal_melting_g-basal_melting_correction_g))*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorPrognostic_DG {{{1*/
+ElementVector* Tria::CreatePVectorPrognostic_DG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	double     Jdettria,dt;
+	double     surface_mass_balance_g,basal_melting_g,thickness_g;
+	double     xyz_list[NUMVERTICES][3];
+	double     L[NUMVERTICES];
+	GaussTria* gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* surface_mass_balance_input=inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(surface_mass_balance_input);
+	Input* basal_melting_input=inputs->GetInput(BasalforcingsMeltingRateEnum);          _assert_(basal_melting_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);                             _assert_(thickness_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		surface_mass_balance_input->GetInputValue(&surface_mass_balance_g,gauss);
+		basal_melting_input->GetInputValue(&basal_melting_g,gauss);
+		thickness_input->GetInputValue(&thickness_g,gauss);
+
+		for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(thickness_g+dt*(surface_mass_balance_g-basal_melting_g))*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorSlope {{{1*/
+ElementVector* Tria::CreatePVectorSlope(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+	
+	/*Intermediaries */
+	int        i,j,ig;
+	int        analysis_type;
+	double     Jdet;
+	double     xyz_list[NUMVERTICES][3];
+	double     slope[2];
+	double     basis[3];
+	GaussTria* gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* slope_input=NULL;
+	if ( (analysis_type==SurfaceSlopeXAnalysisEnum) || (analysis_type==SurfaceSlopeYAnalysisEnum)){
+		slope_input=inputs->GetInput(SurfaceEnum); _assert_(slope_input);
+	}
+	if ( (analysis_type==BedSlopeXAnalysisEnum) || (analysis_type==BedSlopeYAnalysisEnum)){
+		slope_input=inputs->GetInput(BedEnum);     _assert_(slope_input);
+	}
+		
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+
+		slope_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
+
+		if ( (analysis_type==SurfaceSlopeXAnalysisEnum) || (analysis_type==BedSlopeXAnalysisEnum)){
+			for(i=0;i<numdof;i++) pe->values[i]+=Jdet*gauss->weight*slope[0]*basis[i];
+		}
+		if ( (analysis_type==SurfaceSlopeYAnalysisEnum) || (analysis_type==BedSlopeYAnalysisEnum)){
+			for(i=0;i<numdof;i++) pe->values[i]+=Jdet*gauss->weight*slope[1]*basis[i];
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::ComputeBasalStress {{{1*/
+void  Tria::ComputeBasalStress(Vec eps){
+	_error_("Not Implemented yet");
+}
+/*}}}*/
+/*FUNCTION Tria::ComputeStrainRate {{{1*/
+void  Tria::ComputeStrainRate(Vec eps){
+	_error_("Not Implemented yet");
+}
+/*}}}*/
+/*FUNCTION Tria::ComputeStressTensor {{{1*/
+void  Tria::ComputeStressTensor(){
+
+	int         iv;
+	double      xyz_list[NUMVERTICES][3];
+	double      pressure,viscosity;
+	double      epsilon[3]; /* epsilon=[exx,eyy,exy];*/
+	double      sigma_xx[NUMVERTICES];
+	double		sigma_yy[NUMVERTICES];
+	double		sigma_zz[NUMVERTICES]={0,0,0};
+	double      sigma_xy[NUMVERTICES];
+	double		sigma_xz[NUMVERTICES]={0,0,0};
+	double		sigma_yz[NUMVERTICES]={0,0,0};
+	GaussTria* gauss=NULL;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
+	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/*Compute strain rate viscosity and pressure: */
+		this->GetStrainRate2d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		matice->GetViscosity2d(&viscosity,&epsilon[0]);
+		pressure_input->GetInputValue(&pressure,gauss);
+
+		/*Compute Stress*/
+		sigma_xx[iv]=2*viscosity*epsilon[0]-pressure; // sigma = nu eps - pressure
+		sigma_yy[iv]=2*viscosity*epsilon[1]-pressure;
+		sigma_xy[iv]=2*viscosity*epsilon[2];
+	}
+	
+	/*Add Stress tensor components into inputs*/
+	this->inputs->AddInput(new TriaP1Input(StressTensorxxEnum,&sigma_xx[0]));
+	this->inputs->AddInput(new TriaP1Input(StressTensorxyEnum,&sigma_xy[0]));
+	this->inputs->AddInput(new TriaP1Input(StressTensorxzEnum,&sigma_xz[0]));
+	this->inputs->AddInput(new TriaP1Input(StressTensoryyEnum,&sigma_yy[0]));
+	this->inputs->AddInput(new TriaP1Input(StressTensoryzEnum,&sigma_yz[0]));
+	this->inputs->AddInput(new TriaP1Input(StressTensorzzEnum,&sigma_zz[0]));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::Configure {{{1*/
+void  Tria::Configure(Elements* elementsin, Loads* loadsin, DataSet* nodesin, Materials* materialsin, Parameters* parametersin){
+	
+	/*go into parameters and get the analysis_counter: */
+	int analysis_counter;
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	if(this->hnodes[analysis_counter]) this->hnodes[analysis_counter]->configure(nodesin);
+	this->hmatice->configure(materialsin);
+	this->hmatpar->configure(materialsin);
+
+	/*Now, go pick up the objects inside the hooks: */
+	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+	this->matice=(Matice*)this->hmatice->delivers();
+	this->matpar=(Matpar*)this->hmatpar->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+	/*get inputs configured too: */
+	this->inputs->Configure(parameters);
+
+}
+/*}}}*/
+/*FUNCTION Tria::DeepEcho{{{1*/
+void Tria::DeepEcho(void){
+
+	printf("Tria:\n");
+	printf("   id: %i\n",id);
+	if(nodes){
+		nodes[0]->DeepEcho();
+		nodes[1]->DeepEcho();
+		nodes[2]->DeepEcho();
+	}
+	else printf("nodes = NULL\n");
+
+	if (matice) matice->DeepEcho();
+	else printf("matice = NULL\n");
+
+	if (matpar) matpar->DeepEcho();
+	else printf("matpar = NULL\n");
+
+	printf("   parameters\n");
+	if (parameters) parameters->DeepEcho();
+	else printf("parameters = NULL\n");
+
+	printf("   inputs\n");
+	if (inputs) inputs->DeepEcho();
+	else printf("inputs=NULL\n");
+
+	if (results) results->DeepEcho();
+	else printf("results=NULL\n");
+
+	printf("neighboor sids: \n");
+	printf(" %i %i %i\n",horizontalneighborsids[0],horizontalneighborsids[1],horizontalneighborsids[2]);
+	
+	return;
+}
+/*}}}*/
+/*FUNCTION Tria::DeleteResults {{{1*/
+void  Tria::DeleteResults(void){
+
+	/*Delete and reinitialize results*/
+	delete this->results;
+	this->results=new Results();
+
+}
+/*}}}*/
+/*FUNCTION Tria::Echo{{{1*/
+void Tria::Echo(void){
+	printf("Tria:\n");
+	printf("   id: %i\n",id);
+	if(nodes){
+		nodes[0]->Echo();
+		nodes[1]->Echo();
+		nodes[2]->Echo();
+	}
+	else printf("nodes = NULL\n");
+
+	if (matice) matice->Echo();
+	else printf("matice = NULL\n");
+
+	if (matpar) matpar->Echo();
+	else printf("matpar = NULL\n");
+
+	printf("   parameters\n");
+	if (parameters) parameters->Echo();
+	else printf("parameters = NULL\n");
+
+	printf("   inputs\n");
+	if (inputs) inputs->Echo();
+	else printf("inputs=NULL\n");
+
+	if (results) results->Echo();
+	else printf("results=NULL\n");
+
+	printf("neighboor sids: \n");
+	printf(" %i %i %i\n",horizontalneighborsids[0],horizontalneighborsids[1],horizontalneighborsids[2]);
+}
+/*}}}*/
+/*FUNCTION Tria::ObjectEnum{{{1*/
+int Tria::ObjectEnum(void){
+
+	return TriaEnum;
+
+}
+/*}}}*/
+/*FUNCTION Tria::GetArea {{{1*/
+double Tria::GetArea(void){
+
+	double area=0;
+	double xyz_list[NUMVERTICES][3];
+	double x1,y1,x2,y2,x3,y3;
+
+	/*Get xyz list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	x1=xyz_list[0][0]; y1=xyz_list[0][1];
+	x2=xyz_list[1][0]; y2=xyz_list[1][1];
+	x3=xyz_list[2][0]; y3=xyz_list[2][1];
+ 
+	_assert_(x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1>0);
+	return (x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1)/2;
+}
+/*}}}*/
+/*FUNCTION Tria::GetDofList {{{1*/
+void  Tria::GetDofList(int** pdoflist, int approximation_enum,int setenum){
+
+	int i,j;
+	int count=0;
+	int numberofdofs=0;
+	int* doflist=NULL;
+
+	/*First, figure out size of doflist and create it: */
+	for(i=0;i<3;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
+	doflist=(int*)xmalloc(numberofdofs*sizeof(int));
+
+	/*Populate: */
+	count=0;
+	for(i=0;i<3;i++){
+		nodes[i]->GetDofList(doflist+count,approximation_enum,setenum);
+		count+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
+	}
+
+	/*Assign output pointers:*/
+	*pdoflist=doflist;
+}
+/*}}}*/
+/*FUNCTION Tria::GetDofList1 {{{1*/
+void  Tria::GetDofList1(int* doflist){
+
+	int i;
+	for(i=0;i<3;i++) doflist[i]=nodes[i]->GetDofList1();
+
+}
+/*}}}*/
+/*FUNCTION Tria::GetElementType {{{1*/
+int Tria::GetElementType(){
+
+	/*return TriaRef field*/
+	return this->element_type;
+
+}
+/*}}}*/
+/*FUNCTION Tria::GetHorizontalNeighboorSids {{{1*/
+int* Tria::GetHorizontalNeighboorSids(){
+
+	/*return TriaRef field*/
+	return &this->horizontalneighborsids[0];
+
+}
+/*}}}*/
+/*FUNCTION Tria::GetNodeIndex {{{1*/
+int Tria::GetNodeIndex(Node* node){
+
+	_assert_(nodes);
+	for(int i=0;i<NUMVERTICES;i++){
+		if(node==nodes[i])
+		 return i;
+	}
+	_error_("Node provided not found among element nodes");
+}
+/*}}}*/
+/*FUNCTION Tria::GetInputListOnVertices(double* pvalue,int enumtype) {{{1*/
+void Tria::GetInputListOnVertices(double* pvalue,int enumtype){
+
+	/*Intermediaries*/
+	double     value[NUMVERTICES];
+	GaussTria *gauss              = NULL;
+
+	/*Recover input*/
+	Input* input=inputs->GetInput(enumtype);
+	if (!input) _error_("Input %s not found in element",EnumToStringx(enumtype));
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+		input->GetInputValue(&pvalue[iv],gauss);
+	}
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GetInputListOnVertices(double* pvalue,int enumtype,double defaultvalue) {{{1*/
+void Tria::GetInputListOnVertices(double* pvalue,int enumtype,double defaultvalue){
+
+	double     value[NUMVERTICES];
+	GaussTria *gauss = NULL;
+	Input     *input = inputs->GetInput(enumtype);
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	if (input){
+		gauss=new GaussTria();
+		for (int iv=0;iv<NUMVERTICES;iv++){
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&pvalue[iv],gauss);
+		}
+	}
+	else{
+		for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
+	}
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GetInputListOnVertices(double* pvalue,int enumtype,double defaultvalue,int index) TO BE REMOVED{{{1*/
+void Tria::GetInputListOnVertices(double* pvalue,int enumtype,double defaultvalue,int index){
+
+	double     value[NUMVERTICES];
+	GaussTria *gauss = NULL;
+	Input     *input = inputs->GetInput(enumtype);
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	if (input){
+		gauss=new GaussTria();
+		for (int iv=0;iv<NUMVERTICES;iv++){
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&pvalue[iv],gauss,index);
+		}
+	}
+	else{
+		for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
+	}
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GetInputValue(double* pvalue,Node* node,int enumtype) {{{1*/
+void Tria::GetInputValue(double* pvalue,Node* node,int enumtype){
+
+	Input* input=inputs->GetInput(enumtype);
+	if(!input) _error_("No input of type %s found in tria",EnumToStringx(enumtype));
+
+	GaussTria* gauss=new GaussTria();
+	gauss->GaussVertex(this->GetNodeIndex(node));
+
+	input->GetInputValue(pvalue,gauss);
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GetSidList {{{1*/
+void  Tria::GetSidList(int* sidlist){
+	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->GetSidList();
+}
+/*}}}*/
+/*FUNCTION Tria::GetConnectivityList {{{1*/
+void  Tria::GetConnectivityList(int* connectivity){
+	for(int i=0;i<NUMVERTICES;i++) connectivity[i]=nodes[i]->GetConnectivity();
+}
+/*}}}*/
+/*FUNCTION Tria::GetSolutionFromInputs{{{1*/
+void  Tria::GetSolutionFromInputs(Vec solution){
+
+	/*retrive parameters: */
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Just branch to the correct InputUpdateFromSolution generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+	#ifdef _HAVE_DIAGNOSTIC_
+	case DiagnosticHorizAnalysisEnum:
+		GetSolutionFromInputsDiagnosticHoriz(solution);
+		break;
+	case DiagnosticHutterAnalysisEnum:
+		GetSolutionFromInputsDiagnosticHutter(solution);
+		break;
+	#endif
+	#ifdef _HAVE_HYDROLOGY_
+	case HydrologyAnalysisEnum:
+		GetSolutionFromInputsHydrology(solution);
+		break;
+	#endif
+	default:
+		_error_("analysis: %s not supported yet",EnumToStringx(analysis_type));
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::GetStrainRate2d(double* epsilon,double* xyz_list, GaussTria* gauss, Input* vx_input, Input* vy_input){{{1*/
+void Tria::GetStrainRate2d(double* epsilon,double* xyz_list, GaussTria* gauss, Input* vx_input, Input* vy_input){
+	/*Compute the 2d Strain Rate (3 components):
+	 * epsilon=[exx eyy exy] */
+
+	int i;
+	double epsilonvx[3];
+	double epsilonvy[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input){
+		_error_("Input missing. Here are the input pointers we have for vx: %p, vy: %p\n",vx_input,vy_input);
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetVxStrainRate2d(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate2d(epsilonvy,xyz_list,gauss);
+
+	/*Sum all contributions*/
+	for(i=0;i<3;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i];
+}
+/*}}}*/
+/*FUNCTION Tria::GetVectorFromInputs{{{1*/
+void  Tria::GetVectorFromInputs(Vec vector,int input_enum){
+
+	int doflist1[NUMVERTICES];
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(input_enum)) return;
+
+	/*Prepare index list*/
+	this->GetDofList1(&doflist1[0]);
+
+	/*Get input (either in element or material)*/
+	Input* input=inputs->GetInput(input_enum);
+	if(!input) _error_("Input %s not found in element",EnumToStringx(input_enum));
+
+	/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
+	input->GetVectorFromInputs(vector,&doflist1[0]);
+}
+/*}}}*/
+/*FUNCTION Tria::GetVectorFromResults{{{1*/
+void  Tria::GetVectorFromResults(Vec vector,int offset,int interp){
+
+	/*Get result*/
+	ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(offset);
+	if(interp==P1Enum){
+		int doflist1[NUMVERTICES];
+		int connectivity[NUMVERTICES];
+		this->GetSidList(&doflist1[0]);
+		this->GetConnectivityList(&connectivity[0]);
+		elementresult->GetVectorFromResults(vector,&doflist1[0],&connectivity[0],NUMVERTICES);
+	}
+	else if(interp==P0Enum){
+		elementresult->GetElementVectorFromResults(vector,sid);
+	}
+	else{
+		printf("Interpolation %s not supported\n",EnumToStringx(interp));
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::Id {{{1*/
+int    Tria::Id(){
+	
+	return id;
+
+}
+/*}}}*/
+/*FUNCTION Tria::Sid {{{1*/
+int    Tria::Sid(){
+	
+	return sid;
+
+}
+/*}}}*/
+/*FUNCTION Tria::InputArtificialNoise{{{1*/
+void  Tria::InputArtificialNoise(int enum_type,double min,double max){
+
+	Input* input=NULL;
+
+	/*Make a copy of the original input: */
+	input=(Input*)this->inputs->GetInput(enum_type);
+	if(!input)_error_(" could not find old input with enum: %s",EnumToStringx(enum_type));
+
+	/*ArtificialNoise: */
+	input->ArtificialNoise(min,max);
+}
+/*}}}*/
+/*FUNCTION Tria::InputConvergence{{{1*/
+bool Tria::InputConvergence(double* eps, int* enums,int num_enums,int* criterionenums,double* criterionvalues,int num_criterionenums){
+
+	bool    converged=true;
+	int     i;
+	Input** new_inputs=NULL;
+	Input** old_inputs=NULL;
+
+	new_inputs=(Input**)xmalloc(num_enums/2*sizeof(Input*)); //half the enums are for the new inputs
+	old_inputs=(Input**)xmalloc(num_enums/2*sizeof(Input*)); //half the enums are for the old inputs
+
+	for(i=0;i<num_enums/2;i++){
+		new_inputs[i]=(Input*)this->inputs->GetInput(enums[2*i+0]);
+		old_inputs[i]=(Input*)this->inputs->GetInput(enums[2*i+1]);
+		if(!new_inputs[i])_error_("%s%s"," could not find input with enum ",EnumToStringx(enums[2*i+0]));
+		if(!old_inputs[i])_error_("%s%s"," could not find input with enum ",EnumToStringx(enums[2*i+0]));
+	}
+
+	/*ok, we've got the inputs (new and old), now loop throught the number of criterions and fill the eps array:*/
+	for(i=0;i<num_criterionenums;i++){
+		IsInputConverged(eps+i,new_inputs,old_inputs,num_enums/2,criterionenums[i]);
+		if(eps[i]>criterionvalues[i]) converged=false; 
+	}
+
+	/*clean up and return*/
+	xfree((void**)&new_inputs);
+	xfree((void**)&old_inputs);
+	return converged;
+}
+/*}}}*/
+/*FUNCTION Tria::InputDepthAverageAtBase {{{1*/
+void  Tria::InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum){
+
+	/*New input*/
+	Input* oldinput=NULL;
+	Input* newinput=NULL;
+
+	/*copy input of enum_type*/
+	if (object_enum==MeshElementsEnum)
+	 oldinput=(Input*)this->inputs->GetInput(enum_type);
+	else if (object_enum==MaterialsEnum)
+	 oldinput=(Input*)this->matice->inputs->GetInput(enum_type);
+	else
+	 _error_("object %s not supported yet",EnumToStringx(object_enum));
+	if(!oldinput)_error_("%s%s"," could not find old input with enum: ",EnumToStringx(enum_type));
+	newinput=(Input*)oldinput->copy();
+
+	/*Assign new name (average)*/
+	newinput->ChangeEnum(average_enum_type);
+
+	/*Add new input to current element*/
+	if (object_enum==MeshElementsEnum)
+	 this->inputs->AddInput((Input*)newinput);
+	else if (object_enum==MaterialsEnum)
+	 this->matice->inputs->AddInput((Input*)newinput);
+	else
+	 _error_("object %s not supported yet",EnumToStringx(object_enum));
+}
+/*}}}*/
+/*FUNCTION Tria::InputDuplicate{{{1*/
+void  Tria::InputDuplicate(int original_enum,int new_enum){
+
+	/*Call inputs method*/
+	if (IsInput(original_enum)) inputs->DuplicateInput(original_enum,new_enum);
+
+}
+/*}}}*/
+/*FUNCTION Tria::InputScale{{{1*/
+void  Tria::InputScale(int enum_type,double 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: %s",EnumToStringx(enum_type));
+
+	/*Scale: */
+	input->Scale(scale_factor);
+}
+/*}}}*/
+/*FUNCTION Tria::InputToResult{{{1*/
+void  Tria::InputToResult(int enum_type,int step,double time){
+
+	int    i;
+	Input *input = NULL;
+
+	/*Go through all the input objects, and find the one corresponding to enum_type, if it exists: */
+	if (enum_type==MaterialsRheologyBbarEnum) input=this->matice->inputs->GetInput(enum_type);
+	else input=this->inputs->GetInput(enum_type);
+	//if (!input) _error_("Input %s not found in tria->inputs",EnumToStringx(enum_type));
+	if(!input)return;
+
+	/*If we don't find it, no big deal, just don't do the transfer. Otherwise, build a new Result 
+	 * object out of the input, with the additional step and time information: */
+	this->results->AddObject((Object*)input->SpawnResult(step,time));
+	
+	#ifdef _HAVE_CONTROL_
+	if(input->ObjectEnum()==ControlInputEnum) this->results->AddObject((Object*)((ControlInput*)input)->SpawnGradient(step,time));
+	#endif
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromConstant(int value, int name);{{{1*/
+void  Tria::InputUpdateFromConstant(int constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new IntInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromConstant(double value, int name);{{{1*/
+void  Tria::InputUpdateFromConstant(double constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new DoubleInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromConstant(bool value, int name);{{{1*/
+void  Tria::InputUpdateFromConstant(bool constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new BoolInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromIoModel{{{1*/
+void Tria::InputUpdateFromIoModel(int index, IoModel* iomodel){ //i is the element index
+
+	/*Intermediaries*/
+	int    i,j;
+	int    tria_vertex_ids[3];
+	double nodeinputs[3];
+	double cmmininputs[3];
+	double cmmaxinputs[3];
+	bool   control_analysis=false;
+	int    num_control_type;
+	double yts;
+	int    num_cm_responses;
+   
+	/*Get parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum); 
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
+	if(control_analysis) iomodel->Constant(&num_cm_responses,InversionNumCostFunctionsEnum);
+
+	/*Recover vertices ids needed to initialize inputs*/
+	for(i=0;i<3;i++){ 
+		tria_vertex_ids[i]=(int)iomodel->Data(MeshElementsEnum)[3*index+i]; //ids for vertices are in the elements array from Matlab
+	}
+
+	/*Control Inputs*/
+	#ifdef _HAVE_CONTROL_
+	if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+		for(i=0;i<num_control_type;i++){
+			switch((int)iomodel->Data(InversionControlParametersEnum)[i]){
+				case BalancethicknessThickeningRateEnum:
+					if (iomodel->Data(BalancethicknessThickeningRateEnum)){
+						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(BalancethicknessThickeningRateEnum)[tria_vertex_ids[j]-1]/yts;
+						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,TriaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case VxEnum:
+					if (iomodel->Data(VxEnum)){
+						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(VxEnum)[tria_vertex_ids[j]-1]/yts;
+						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(VxEnum,TriaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case VyEnum:
+					if (iomodel->Data(VyEnum)){
+						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(VyEnum)[tria_vertex_ids[j]-1]/yts;
+						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(VyEnum,TriaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case FrictionCoefficientEnum:
+					if (iomodel->Data(FrictionCoefficientEnum)){
+						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(FrictionCoefficientEnum)[tria_vertex_ids[j]-1];
+						for(j=0;j<3;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<3;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(tria_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,TriaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case MaterialsRheologyBbarEnum:
+					/*Matice will take care of it*/ break;
+				default:
+					_error_("Control %s not implemented yet",EnumToStringx((int)iomodel->Data(InversionControlParametersEnum)[i]));
+			}
+		}
+	}
+	#endif
+
+	/*DatasetInputs*/
+	if (control_analysis && iomodel->Data(InversionCostFunctionsCoefficientsEnum)){
+
+		/*Create inputs and add to DataSetInput*/
+		DatasetInput* datasetinput=new DatasetInput(InversionCostFunctionsCoefficientsEnum);
+		for(i=0;i<num_cm_responses;i++){
+			for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(InversionCostFunctionsCoefficientsEnum)[(tria_vertex_ids[j]-1)*num_cm_responses+i];
+			datasetinput->inputs->AddObject(new TriaP1Input(InversionCostFunctionsCoefficientsEnum,nodeinputs));
+		}
+
+		/*Add datasetinput to element inputs*/
+		this->inputs->AddInput(datasetinput);
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolution {{{1*/
+void  Tria::InputUpdateFromSolution(double* solution){
+
+	/*retrive parameters: */
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Just branch to the correct InputUpdateFromSolution generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum:
+			InputUpdateFromSolutionDiagnosticHoriz( solution);
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			InputUpdateFromSolutionDiagnosticHoriz( solution);
+			break;
+		#endif
+		#ifdef _HAVE_CONTROL_
+		case AdjointHorizAnalysisEnum:
+			InputUpdateFromSolutionAdjointHoriz( solution);
+			break;
+		case AdjointBalancethicknessAnalysisEnum:
+			InputUpdateFromSolutionAdjointBalancethickness( solution);
+			break;
+		#endif
+		#ifdef _HAVE_HYDROLOGY_ 
+		case HydrologyAnalysisEnum:
+			InputUpdateFromSolutionHydrology(solution);
+			break ;
+		#endif
+	 	#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,ThicknessEnum);
+			break;
+		#endif
+		case BedSlopeXAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,BedSlopeXEnum);
+			break;
+		case BedSlopeYAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,BedSlopeYEnum);
+			break;
+		case SurfaceSlopeXAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,SurfaceSlopeXEnum);
+			break;
+		case SurfaceSlopeYAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,SurfaceSlopeYEnum);
+			break;
+		case PrognosticAnalysisEnum:
+			InputUpdateFromSolutionPrognostic(solution);
+			break;
+		default:
+			_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionOneDof{{{1*/
+void  Tria::InputUpdateFromSolutionOneDof(double* solution,int enum_type){
+
+	const int numdof          = NDOF1*NUMVERTICES;
+
+	int*      doflist=NULL;
+	double    values[numdof];
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+		if(isnan(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new TriaP1Input(enum_type,values));
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionPrognostic{{{1*/
+void  Tria::InputUpdateFromSolutionPrognostic(double* solution){
+
+	/*Intermediaries*/
+	const int numdof = NDOF1*NUMVERTICES;
+
+	int       i,hydroadjustment;
+	int*      doflist=NULL;
+	double    rho_ice,rho_water,minthickness;
+	double    newthickness[numdof];
+	double    newbed[numdof];
+	double    newsurface[numdof];
+	double    oldbed[NUMVERTICES];
+	double    oldsurface[NUMVERTICES];
+	double    oldthickness[NUMVERTICES];
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	this->parameters->FindParam(&minthickness,PrognosticMinThicknessEnum);
+	for(i=0;i<numdof;i++){
+		newthickness[i]=solution[doflist[i]];
+		if(isnan(newthickness[i])) _error_("NaN found in solution vector");
+		/*Constrain thickness to be at least 1m*/
+		if(newthickness[i]<minthickness) newthickness[i]=minthickness;
+	}
+
+	/*Get previous bed, thickness and surface*/
+	GetInputListOnVertices(&oldbed[0],BedEnum);
+	GetInputListOnVertices(&oldsurface[0],SurfaceEnum);
+	GetInputListOnVertices(&oldthickness[0],ThicknessEnum);
+
+	/*Fing PrognosticHydrostaticAdjustment to figure out how to update the geometry:*/
+	this->parameters->FindParam(&hydroadjustment,PrognosticHydrostaticAdjustmentEnum);
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	for(i=0;i<numdof;i++) {
+		/*If shelf: hydrostatic equilibrium*/
+		if (this->nodes[i]->IsGrounded()){
+			newsurface[i]=oldbed[i]+newthickness[i]; //surface = oldbed + newthickness
+			newbed[i]=oldbed[i];               //same bed: do nothing
+		}
+		else{ //this is an ice shelf
+
+			if(hydroadjustment==AbsoluteEnum){
+				newsurface[i]=newthickness[i]*(1-rho_ice/rho_water);
+				newbed[i]=newthickness[i]*(-rho_ice/rho_water);
+			}
+			else if(hydroadjustment==IncrementalEnum){
+				newsurface[i]=oldsurface[i]+(1.0-rho_ice/rho_water)*(newthickness[i]-oldthickness[i]); //surface = oldsurface + (1-di) * dH 
+				newbed[i]=oldbed[i]-rho_ice/rho_water*(newthickness[i]-oldthickness[i]); //bed = oldbed + di * dH
+			}
+			else _error_("Hydrostatic adjustment %i (%s) not supported yet",hydroadjustment,EnumToStringx(hydroadjustment));
+		}
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new TriaP1Input(ThicknessEnum,newthickness));
+	this->inputs->AddInput(new TriaP1Input(SurfaceEnum,newsurface));
+	this->inputs->AddInput(new TriaP1Input(BedEnum,newbed));
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromVector(double* vector, int name, int type);{{{1*/
+void  Tria::InputUpdateFromVector(double* vector, int name, int type){
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			/*New TriaP1Input*/
+			double values[3];
+
+			/*Get values on the 3 vertices*/
+			for (int i=0;i<3;i++){
+				values[i]=vector[this->nodes[i]->GetVertexDof()];
+			}
+
+			/*update input*/
+			if (name==MaterialsRheologyBbarEnum || name==MaterialsRheologyBEnum){
+				matice->inputs->AddInput(new TriaP1Input(name,values));
+			}
+			else{
+				this->inputs->AddInput(new TriaP1Input(name,values));
+			}
+			return;
+
+		default:
+			_error_("type %i (%s) not implemented yet",type,EnumToStringx(type));
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromVector(int* vector, int name, int type);{{{1*/
+void  Tria::InputUpdateFromVector(int* vector, int name, int type){
+	_error_(" not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromVector(bool* vector, int name, int type);{{{1*/
+void  Tria::InputUpdateFromVector(bool* vector, int name, int type){
+	_error_(" not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Tria::InputCreate(double scalar,int enum,int code);{{{1*/
+void Tria::InputCreate(double scalar,int name,int code){
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+	
+	if ((code==5) || (code==1)){ //boolean
+		this->inputs->AddInput(new BoolInput(name,(bool)scalar));
+	}
+	else if ((code==6) || (code==2)){ //integer
+		this->inputs->AddInput(new IntInput(name,(int)scalar));
+	}
+	else if ((code==7) || (code==3)){ //double
+		this->inputs->AddInput(new DoubleInput(name,(int)scalar));
+	}
+	else _error_("%s%i"," could not recognize nature of vector from code ",code);
+
+}
+/*}}}*/
+/*FUNCTION Tria::InputCreate(double* vector,int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){{{1*/
+void Tria::InputCreate(double* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){//index into elements
+
+	/*Intermediaries*/
+	int    i,j,t;
+	int    tria_vertex_ids[3];
+	int    row;
+	double nodeinputs[3];
+	double time;
+	TransientInput* transientinput=NULL;
+	int    numberofvertices;
+	int    numberofelements;
+	double yts;
+
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+
+	/*Branch on type of vector: nodal or elementary: */
+	if(vector_type==1){ //nodal vector
+
+		/*Recover vertices ids needed to initialize inputs*/
+		for(i=0;i<3;i++){ 
+			tria_vertex_ids[i]=(int)iomodel->Data(MeshElementsEnum)[3*index+i]; //ids for vertices are in the elements array from Matlab
+		}
+
+		/*Are we in transient or static? */
+		if(M==numberofvertices){
+
+			/*create input values: */
+			for(i=0;i<3;i++)nodeinputs[i]=(double)vector[tria_vertex_ids[i]-1];
+
+			/*process units: */
+			UnitConversion(&nodeinputs[0], 3 ,ExtToIuEnum, vector_enum);
+
+			/*create static input: */
+			this->inputs->AddInput(new TriaP1Input(vector_enum,nodeinputs));
+		}
+		else if(M==numberofvertices+1){
+			/*create transient input: */
+			for(t=0;t<N;t++){ //N is the number of times
+
+				/*create input values: */
+				for(i=0;i<3;i++){
+					row=tria_vertex_ids[i]-1;
+					nodeinputs[i]=(double)vector[N*row+t];
+				}
+
+				/*process units: */
+				UnitConversion(&nodeinputs[0], 3 ,ExtToIuEnum, vector_enum);
+
+				/*time? :*/
+				time=(double)vector[(M-1)*N+t]*yts;
+
+				if(t==0) transientinput=new TransientInput(vector_enum);
+				transientinput->AddTimeInput(new TriaP1Input(vector_enum,nodeinputs),time);
+			}
+			this->inputs->AddInput(transientinput);
+		}
+		else _error_("nodal vector is either numberofnodes (%i), or numberofnodes+1 long. Field provided is %i long",numberofvertices,M);
+	}
+	else if(vector_type==2){ //element vector
+		/*Are we in transient or static? */
+		if(M==numberofelements){
+
+			/*static mode: create an input out of the element value: */
+
+			if (code==5){ //boolean
+				this->inputs->AddInput(new BoolInput(vector_enum,(bool)vector[index]));
+			}
+			else if (code==6){ //integer
+				this->inputs->AddInput(new IntInput(vector_enum,(int)vector[index]));
+			}
+			else if (code==7){ //double
+				this->inputs->AddInput(new DoubleInput(vector_enum,(double)vector[index]));
+			}
+			else _error_("%s%i"," could not recognize nature of vector from code ",code);
+		}
+		else {
+			_error_("transient elementary inputs not supported yet!");
+		}
+	}
+	else{
+		_error_("Cannot add input for vector type %i (not supported)",vector_type);
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::IsInput{{{1*/
+bool Tria::IsInput(int name){
+	if (
+				name==ThicknessEnum ||
+				name==SurfaceEnum ||
+				name==BedEnum ||
+				name==SurfaceSlopeXEnum ||
+				name==SurfaceSlopeYEnum ||
+				name==BasalforcingsMeltingRateEnum ||
+				name==WatercolumnEnum || 
+				name==SurfaceforcingsMassBalanceEnum ||
+				name==SurfaceAreaEnum||
+				name==VxEnum ||
+				name==VyEnum ||
+				name==InversionVxObsEnum ||
+				name==InversionVyObsEnum ||
+				name==FrictionCoefficientEnum ||
+				name==GradientEnum ||
+				name==OldGradientEnum ||
+				name==QmuVxEnum ||
+				name==QmuVyEnum ||
+				name==QmuPressureEnum ||
+				name==QmuBedEnum ||
+				name==QmuThicknessEnum ||
+				name==QmuSurfaceEnum ||
+				name==QmuTemperatureEnum ||
+				name==QmuMeltingEnum
+		){
+		return true;
+	}
+	else return false;
+}
+/*}}}*/
+/*FUNCTION Tria::IsOnBed {{{1*/
+bool Tria::IsOnBed(){
+	
+	bool onbed;
+	inputs->GetInputValue(&onbed,MeshElementonbedEnum);
+	return onbed;
+}
+/*}}}*/
+/*FUNCTION Tria::IsFloating {{{1*/
+bool   Tria::IsFloating(){
+
+	bool shelf;
+	inputs->GetInputValue(&shelf,MaskElementonfloatingiceEnum);
+	return shelf;
+}
+/*}}}*/
+/*FUNCTION Tria::IsNodeOnShelf {{{1*/
+bool   Tria::IsNodeOnShelf(){
+
+	int  i;
+	bool shelf=false;
+
+	for(i=0;i<3;i++){
+		if (nodes[i]->IsFloating()){
+			shelf=true;
+			break;
+		}
+	}
+	return shelf;
+}
+/*}}}*/
+/*FUNCTION Tria::IsNodeOnShelfFromFlags {{{1*/
+bool   Tria::IsNodeOnShelfFromFlags(double* flags){
+
+	int  i;
+	bool shelf=false;
+
+	for(i=0;i<NUMVERTICES;i++){
+		if (flags[nodes[i]->Sid()]){
+			shelf=true;
+			break;
+		}
+	}
+	return shelf;
+}
+/*}}}*/
+/*FUNCTION Tria::IsOnWater {{{1*/
+bool   Tria::IsOnWater(){
+
+	bool water;
+	inputs->GetInputValue(&water,MaskElementonwaterEnum);
+	return water;
+}
+/*}}}*/
+/*FUNCTION Tria::ListResultsInfo{{{*/
+void Tria::ListResultsInfo(int** in_resultsenums,int** in_resultssizes,double** in_resultstimes,int** in_resultssteps,int* in_num_results){
+
+	/*Intermediaries*/
+	int     i;
+	int     numberofresults = 0;
+	int     *resultsenums   = NULL;
+	int     *resultssizes   = NULL;
+	double  *resultstimes   = NULL;
+	int     *resultssteps   = NULL;
+
+	/*Checks*/
+	_assert_(in_num_results);
+
+	/*Count number of results*/
+	for(i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+		numberofresults++;
+	}
+
+	if(numberofresults){
+
+		/*Allocate output*/
+		resultsenums=(int*)xmalloc(numberofresults*sizeof(int));
+		resultssizes=(int*)xmalloc(numberofresults*sizeof(int));
+		resultstimes=(double*)xmalloc(numberofresults*sizeof(double));
+		resultssteps=(int*)xmalloc(numberofresults*sizeof(int));
+
+		/*populate enums*/
+		for(i=0;i<this->results->Size();i++){
+			ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+			resultsenums[i]=elementresult->InstanceEnum();
+			resultstimes[i]=elementresult->GetTime();
+			resultssteps[i]=elementresult->GetStep();
+			if(elementresult->ObjectEnum()==TriaP1ElementResultEnum){
+				resultssizes[i]=P1Enum;
+			}
+			else{
+				resultssizes[i]=P0Enum;
+			}
+		}
+	}
+
+	/*Assign output pointers:*/
+	*in_num_results=numberofresults;
+	*in_resultsenums=resultsenums;
+	*in_resultssizes=resultssizes;
+	*in_resultstimes=resultstimes;
+	*in_resultssteps=resultssteps;
+
+}/*}}}*/
+/*FUNCTION Tria::MigrateGroundingLine{{{1*/
+void  Tria::MigrateGroundingLine(double* old_floating_ice,double* sheet_ungrounding){
+
+	int     i,migration_style,unground;
+	bool    elementonshelf = false;
+	double  bed_hydro,yts,gl_melting_rate;
+	double  rho_water,rho_ice,density;
+	double  melting[NUMVERTICES];
+	double  h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],ba[NUMVERTICES];
+
+	/*Recover info at the vertices: */
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	parameters->FindParam(&yts,ConstantsYtsEnum);
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&s[0],SurfaceEnum);
+	GetInputListOnVertices(&b[0],BedEnum);
+	GetInputListOnVertices(&ba[0],BathymetryEnum);
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	density=rho_ice/rho_water;
+	
+	/*go through vertices, and update inputs, considering them to be TriaVertex type: */
+	for(i=0;i<NUMVERTICES;i++){
+		/*Ice shelf: if bed below bathymetry, impose it at the bathymetry and update surface, elso do nothing */
+		if(old_floating_ice[nodes[i]->Sid()]){
+			if(b[i]<=ba[i]){ 
+				b[i]=ba[i];
+				s[i]=b[i]+h[i];
+				nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,false));
+				nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,true));
+			}
+		}
+		/*Ice sheet: if hydrostatic bed above bathymetry, ice sheet starts to unground, elso do nothing */
+		/*Change only if AgressiveMigration or if the ice sheet is in contact with the ocean*/
+		else{
+			bed_hydro=-density*h[i];
+			if (bed_hydro>ba[i]){
+				/*Unground only if the element is connected to the ice shelf*/
+				if(migration_style==AgressiveMigrationEnum){
+					s[i]=(1-density)*h[i];
+					b[i]=-density*h[i];
+					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,true));
+					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,false));
+				}
+				else if(migration_style==SoftMigrationEnum && sheet_ungrounding[nodes[i]->Sid()]){
+					s[i]=(1-density)*h[i];
+					b[i]=-density*h[i];
+					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,true));
+					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,false));
+				}
+			}
+		}
+	}
+
+	/*If at least one vertex is now floating, the element is now floating*/
+	for(i=0;i<NUMVERTICES;i++){
+		if(nodes[i]->IsFloating()){
+			elementonshelf=true;
+			break;
+		}
+	}
+	
+   /*Add basal melting rate if element just ungrounded*/
+	if(!this->IsFloating() && elementonshelf==true){
+		for(i=0;i<NUMVERTICES;i++)melting[i]=gl_melting_rate/yts;
+		this->inputs->AddInput(new TriaP1Input(BasalforcingsMeltingRateEnum,&melting[0]));
+	} 
+
+	/*Update inputs*/
+   this->inputs->AddInput(new BoolInput(MaskElementonfloatingiceEnum,elementonshelf));
+
+	/*Update inputs*/    
+	this->inputs->AddInput(new TriaP1Input(SurfaceEnum,&s[0]));
+	this->inputs->AddInput(new TriaP1Input(BedEnum,&b[0]));
+}
+/*}}}*/
+/*FUNCTION Tria::MyRank {{{1*/
+int    Tria::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION Tria::PatchFill{{{1*/
+void  Tria::PatchFill(int* prow, Patch* patch){
+
+	int i,row;
+	int vertices_ids[3];
+
+	/*recover pointer: */
+	row=*prow;
+		
+	for(i=0;i<3;i++) vertices_ids[i]=nodes[i]->GetVertexId(); //vertices id start at column 3 of the patch.
+
+	for(i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+
+		/*For this result,fill the information in the Patch object (element id + vertices ids), and then hand 
+		 *it to the result object, to fill the rest: */
+		patch->fillelementinfo(row,this->sid+1,vertices_ids,3);
+		elementresult->PatchFill(row,patch);
+
+		/*increment rower: */
+		row++;
+	}
+
+	/*Assign output pointers:*/
+	*prow=row;
+}
+/*}}}*/
+/*FUNCTION Tria::PatchSize{{{1*/
+void  Tria::PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes){
+
+	int     i;
+	int     numrows       = 0;
+	int     numnodes      = 0;
+	int     temp_numnodes = 0;
+
+	/*Go through all the results objects, and update the counters: */
+	for (i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+		/*first, we have one more result: */
+		numrows++;
+		/*now, how many vertices and how many nodal values for this result? :*/
+		temp_numnodes=elementresult->NumberOfNodalValues(); //ask result object.
+		if(temp_numnodes>numnodes)numnodes=temp_numnodes;
+	}
+
+	/*Assign output pointers:*/
+	*pnumrows=numrows;
+	*pnumvertices=NUMVERTICES;
+	*pnumnodes=numnodes;
+}
+/*}}}*/
+/*FUNCTION Tria::PotentialSheetUngrounding{{{1*/
+void  Tria::PotentialSheetUngrounding(Vec potential_sheet_ungrounding){
+
+	int     i;
+	double  h[NUMVERTICES],ba[NUMVERTICES];
+	double  bed_hydro;
+	double  rho_water,rho_ice,density;
+	bool    elementonshelf = false;
+
+	/*material parameters: */
+	rho_water=matpar->GetRhoWater();
+	rho_ice=matpar->GetRhoIce();
+	density=rho_ice/rho_water;
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&ba[0],BathymetryEnum);
+
+	/*go through vertices, and figure out which ones are on the ice sheet, and want to unground: */
+	for(i=0;i<NUMVERTICES;i++){
+		/*Find if grounded vertices want to start floating*/
+		if (!nodes[i]->IsFloating()){
+			bed_hydro=-density*h[i];
+			if (bed_hydro>ba[i]){
+				/*Vertex that could potentially unground, flag it*/
+				VecSetValue(potential_sheet_ungrounding,nodes[i]->Sid(),1,INSERT_VALUES);
+			}
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::ProcessResultsUnits{{{1*/
+void  Tria::ProcessResultsUnits(void){
+
+	int i;
+
+	for(i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+		elementresult->ProcessUnits(this->parameters);
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::RequestedOutput{{{1*/
+void Tria::RequestedOutput(int output_enum,int step,double time){
+
+	if(IsInput(output_enum)){
+		/*just transfer this input to results, and we are done: */
+		InputToResult(output_enum,step,time);
+	}
+	else{
+		/*this input does not exist, compute it, and then transfer to results: */
+		switch(output_enum){
+			case StressTensorEnum: 
+				this->ComputeStressTensor();
+				InputToResult(StressTensorxxEnum,step,time);
+				InputToResult(StressTensorxyEnum,step,time);
+				InputToResult(StressTensorxzEnum,step,time);
+				InputToResult(StressTensoryyEnum,step,time);
+				InputToResult(StressTensoryzEnum,step,time);
+				InputToResult(StressTensorzzEnum,step,time);
+				break;
+
+			default:
+				/*do nothing, no need to derail the computation because one of the outputs requested cannot be found: */
+				break;
+		}
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::SetClone {{{1*/
+void  Tria::SetClone(int* minranks){
+
+	_error_("not implemented yet");
+}
+/*}}}1*/
+/*FUNCTION Tria::SmearFunction {{{1*/
+void  Tria::SmearFunction(Vec smearedvector,double (*WeightFunction)(double distance,double radius),double radius){
+	_error_("not implemented yet");
+
+}
+/*}}}1*/
+/*FUNCTION Tria::SetCurrentConfiguration {{{1*/
+void  Tria::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, DataSet* nodesin, Materials* materialsin, Parameters* parametersin){
+	
+	/*go into parameters and get the analysis_counter: */
+	int analysis_counter;
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Pick up nodes*/
+	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceArea {{{1*/
+double Tria::SurfaceArea(void){
+
+	int    i;
+	double S;
+	double normal[3];
+	double v13[3],v23[3];
+	double xyz_list[NUMVERTICES][3];
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	for (i=0;i<3;i++){
+		v13[i]=xyz_list[0][i]-xyz_list[2][i];
+		v23[i]=xyz_list[1][i]-xyz_list[2][i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+
+	S = 0.5 * sqrt(pow(normal[0],(double)2)+pow(normal[1],(double)2)+pow(normal[2],(double)2));
+
+	/*Return: */
+	return S;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceNormal{{{1*/
+void Tria::SurfaceNormal(double* surface_normal, double xyz_list[3][3]){
+
+	int i;
+	double v13[3],v23[3];
+	double normal[3];
+	double normal_norm;
+
+	for (i=0;i<3;i++){
+		v13[i]=xyz_list[0][i]-xyz_list[2][i];
+		v23[i]=xyz_list[1][i]-xyz_list[2][i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+
+	normal_norm=sqrt( pow(normal[0],(double)2)+pow(normal[1],(double)2)+pow(normal[2],(double)2) );
+
+	*(surface_normal)=normal[0]/normal_norm;
+	*(surface_normal+1)=normal[1]/normal_norm;
+	*(surface_normal+2)=normal[2]/normal_norm;
+}
+/*}}}*/
+/*FUNCTION Tria::TimeAdapt{{{1*/
+double  Tria::TimeAdapt(void){
+
+	/*intermediary: */
+	int    i;
+	double C,dt;
+	double dx,dy;
+	double maxx,minx;
+	double maxy,miny;
+	double maxabsvx,maxabsvy;
+	double xyz_list[NUMVERTICES][3];
+
+	/*get CFL coefficient:*/
+	this->parameters->FindParam(&C,TimesteppingCflCoefficientEnum);
+
+	/*Get for Vx and Vy, the max of abs value: */
+	#ifdef _HAVE_RESPONSES_
+	this->MaxAbsVx(&maxabsvx,false);
+	this->MaxAbsVy(&maxabsvy,false);
+	#else
+		_error_("ISSM was not compiled with responses compiled in, exiting!");
+	#endif
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], this->nodes, NUMVERTICES);
+
+	minx=xyz_list[0][0];
+	maxx=xyz_list[0][0];
+	miny=xyz_list[0][1];
+	maxy=xyz_list[0][1];
+
+	for(i=1;i<NUMVERTICES;i++){
+		if (xyz_list[i][0]<minx)minx=xyz_list[i][0];
+		if (xyz_list[i][0]>maxx)maxx=xyz_list[i][0];
+		if (xyz_list[i][1]<miny)miny=xyz_list[i][1];
+		if (xyz_list[i][1]>maxy)maxy=xyz_list[i][1];
+	}
+	dx=maxx-minx;
+	dy=maxy-miny;
+
+	/*CFL criterion: */
+	dt=C/(maxabsvy/dx+maxabsvy/dy);
+
+	return dt;
+}
+/*}}}*/
+/*FUNCTION Tria::Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type){{{1*/
+void Tria::Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type){ //i is the element index
+
+	/*Intermediaries*/
+	int    i,j;
+	int    tria_node_ids[3];
+	int    tria_vertex_ids[3];
+	int    tria_type;
+	double nodeinputs[3];
+	double yts;
+	int    progstabilization,balancestabilization;
+	bool   dakota_analysis;
+
+	/*Checks if debuging*/
+	/*{{{2*/
+	_assert_(iomodel->Data(MeshElementsEnum));
+	/*}}}*/
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&progstabilization,PrognosticStabilizationEnum);
+	iomodel->Constant(&balancestabilization,BalancethicknessStabilizationEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+
+	/*Recover element type*/
+	if ((analysis_type==PrognosticAnalysisEnum && progstabilization==3) || (analysis_type==BalancethicknessAnalysisEnum && balancestabilization==3)){
+		/*P1 Discontinuous Galerkin*/
+		tria_type=P1DGEnum;
+	}
+	else{
+		/*P1 Continuous Galerkin*/
+		tria_type=P1Enum;
+	}
+	this->SetElementType(tria_type,analysis_counter);
+
+	/*Recover vertices ids needed to initialize inputs*/
+	for(i=0;i<3;i++){ 
+		tria_vertex_ids[i]=(int)iomodel->Data(MeshElementsEnum)[3*index+i]; //ids for vertices are in the elements array from Matlab
+	}
+
+	/*Recover nodes ids needed to initialize the node hook.*/
+	if (tria_type==P1DGEnum){
+		/*Discontinuous Galerkin*/
+		tria_node_ids[0]=iomodel->nodecounter+3*index+1;
+		tria_node_ids[1]=iomodel->nodecounter+3*index+2;
+		tria_node_ids[2]=iomodel->nodecounter+3*index+3;
+	}
+	else{
+		/*Continuous Galerkin*/
+		for(i=0;i<3;i++){ 
+			tria_node_ids[i]=iomodel->nodecounter+(int)*(iomodel->Data(MeshElementsEnum)+3*index+i); //ids for vertices are in the elements array from Matlab
+		}
+	}
+
+	/*hooks: */
+	this->SetHookNodes(tria_node_ids,analysis_counter); this->nodes=NULL; //set hook to nodes, for this analysis type
+
+	/*Fill with IoModel*/
+	this->InputUpdateFromIoModel(index,iomodel);
+
+	/*Defaults if not provided in iomodel*/
+	switch(analysis_type){
+
+		case DiagnosticHorizAnalysisEnum:
+
+			/*default vx,vy and vz: either observation or 0 */
+			if(!iomodel->Data(VxEnum)){
+				for(i=0;i<3;i++)nodeinputs[i]=0;
+				this->inputs->AddInput(new TriaP1Input(VxEnum,nodeinputs));
+				if(dakota_analysis) this->inputs->AddInput(new TriaP1Input(QmuVxEnum,nodeinputs));
+			}
+			if(!iomodel->Data(VyEnum)){
+				for(i=0;i<3;i++)nodeinputs[i]=0;
+				this->inputs->AddInput(new TriaP1Input(VyEnum,nodeinputs));
+				if(dakota_analysis) this->inputs->AddInput(new TriaP1Input(QmuVyEnum,nodeinputs));
+			}
+			if(!iomodel->Data(VzEnum)){
+				for(i=0;i<3;i++)nodeinputs[i]=0;
+				this->inputs->AddInput(new TriaP1Input(VzEnum,nodeinputs));
+				if(dakota_analysis) this->inputs->AddInput(new TriaP1Input(QmuVzEnum,nodeinputs));
+			}
+			if(!iomodel->Data(PressureEnum)){
+				for(i=0;i<3;i++)nodeinputs[i]=0;
+				if(dakota_analysis){
+					this->inputs->AddInput(new TriaP1Input(PressureEnum,nodeinputs));
+					this->inputs->AddInput(new TriaP1Input(QmuPressureEnum,nodeinputs));
+				}
+			}
+			break;
+
+		default:
+			/*No update for other solution types*/
+			break;
+
+	}
+
+	//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+	this->parameters=NULL;
+}
+/*}}}*/
+/*FUNCTION Tria::UpdatePotentialSheetUngrounding{{{1*/
+int Tria::UpdatePotentialSheetUngrounding(double* vertices_potentially_ungrounding,Vec vec_nodes_on_iceshelf,double* nodes_on_iceshelf){
+
+	int i;
+	int nflipped=0;
+
+	/*Go through nodes, and whoever is on the potential_sheet_ungrounding, ends up in nodes_on_iceshelf: */
+	for(i=0;i<3;i++){
+		if (vertices_potentially_ungrounding[nodes[i]->Sid()]){
+			VecSetValue(vec_nodes_on_iceshelf,nodes[i]->Sid(),1,INSERT_VALUES);
+		
+			/*If node was not on ice shelf, we flipped*/
+			if(nodes_on_iceshelf[nodes[i]->Sid()]==0){
+				nflipped++;
+			}
+		}
+	}
+	return nflipped;
+}
+/*}}}*/
+
+#ifdef _HAVE_RESPONSES_
+/*FUNCTION Tria::IceVolume {{{1*/
+double Tria::IceVolume(void){
+
+	/*The volume of a troncated prism is base * 1/3 sum(length of edges)*/
+	double base,surface,bed;
+	double xyz_list[NUMVERTICES][3];
+
+	if(IsOnWater())return 0;
+
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Triangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average height*/
+	Input* surface_input = inputs->GetInput(SurfaceEnum); _assert_(surface_input);
+	Input* bed_input     = inputs->GetInput(BedEnum);     _assert_(bed_input);
+	surface_input->GetInputAverage(&surface);
+	bed_input->GetInputAverage(&bed);
+
+	/*Return: */
+	return base*(surface-bed);
+}
+/*}}}*/
+/*FUNCTION Tria::MassFlux {{{1*/
+double Tria::MassFlux( double* segment,bool process_units){
+
+	const int    numdofs=2;
+
+	int        i,dim;
+	double     mass_flux=0;
+	double     xyz_list[NUMVERTICES][3];
+	double     normal[2];
+	double     length,rho_ice;
+	double     x1,y1,x2,y2,h1,h2;
+	double     vx1,vx2,vy1,vy2;
+	GaussTria* gauss_1=NULL;
+	GaussTria* gauss_2=NULL;
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetRhoIce();
+
+	/*First off, check that this segment belongs to this element: */
+	if ((int)*(segment+4)!=this->id)_error_("%s%i%s%i","error message: segment with id ",(int)*(segment+4)," does not belong to element with id:",this->id);
+
+	/*Recover segment node locations: */
+	x1=*(segment+0); y1=*(segment+1); x2=*(segment+2); y2=*(segment+3);
+
+	/*Get xyz list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*get area coordinates of 0 and 1 locations: */
+	gauss_1=new GaussTria();
+	gauss_1->GaussFromCoords(x1,y1,&xyz_list[0][0]);
+	gauss_2=new GaussTria();
+	gauss_2->GaussFromCoords(x2,y2,&xyz_list[0][0]);
+
+	normal[0]=cos(atan2(x1-x2,y2-y1));
+	normal[1]=sin(atan2(x1-x2,y2-y1));
+
+	length=sqrt(pow(x2-x1,2.0)+pow(y2-y1,2));
+
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	Input* vx_input=NULL;
+	Input* vy_input=NULL;
+	if(dim==2){
+		vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	}
+	else{
+		vx_input=inputs->GetInput(VxAverageEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyAverageEnum); _assert_(vy_input);
+	}
+
+	thickness_input->GetInputValue(&h1, gauss_1);
+	thickness_input->GetInputValue(&h2, gauss_2);
+	vx_input->GetInputValue(&vx1,gauss_1);
+	vx_input->GetInputValue(&vx2,gauss_2);
+	vy_input->GetInputValue(&vy1,gauss_1);
+	vy_input->GetInputValue(&vy2,gauss_2);
+
+	mass_flux= rho_ice*length*(  
+				(ONETHIRD*(h1-h2)*(vx1-vx2)+0.5*h2*(vx1-vx2)+0.5*(h1-h2)*vx2+h2*vx2)*normal[0]+
+				(ONETHIRD*(h1-h2)*(vy1-vy2)+0.5*h2*(vy1-vy2)+0.5*(h1-h2)*vy2+h2*vy2)*normal[1]
+				);
+
+	/*Process units: */
+	mass_flux=UnitConversion(mass_flux,IuToExtEnum,MassFluxEnum);
+
+	/*clean up and return:*/
+	delete gauss_1;
+	delete gauss_2;
+	return mass_flux;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxAbsVx{{{1*/
+void  Tria::MaxAbsVx(double* pmaxabsvx, bool process_units){
+
+	/*Get maximum:*/
+	double maxabsvx=this->inputs->MaxAbs(VxEnum);
+
+	/*process units if requested: */
+	if(process_units) maxabsvx=UnitConversion(maxabsvx,IuToExtEnum,VxEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvx=maxabsvx;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxAbsVy{{{1*/
+void  Tria::MaxAbsVy(double* pmaxabsvy, bool process_units){
+
+	/*Get maximum:*/
+	double maxabsvy=this->inputs->MaxAbs(VyEnum);
+
+	/*process units if requested: */
+	if(process_units) maxabsvy=UnitConversion(maxabsvy,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvy=maxabsvy;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxAbsVz{{{1*/
+void  Tria::MaxAbsVz(double* pmaxabsvz, bool process_units){
+
+	/*Get maximum:*/
+	double maxabsvz=this->inputs->MaxAbs(VzEnum);
+
+	/*process units if requested: */
+	if(process_units) maxabsvz=UnitConversion(maxabsvz,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvz=maxabsvz;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxVel{{{1*/
+void  Tria::MaxVel(double* pmaxvel, bool process_units){
+
+	/*Get maximum:*/
+	double maxvel=this->inputs->Max(VelEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvel=UnitConversion(maxvel,IuToExtEnum,VelEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvel=maxvel;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxVx{{{1*/
+void  Tria::MaxVx(double* pmaxvx, bool process_units){
+
+	/*Get maximum:*/
+	double maxvx=this->inputs->Max(VxEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvx=UnitConversion(maxvx,IuToExtEnum,VxEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvx=maxvx;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxVy{{{1*/
+void  Tria::MaxVy(double* pmaxvy, bool process_units){
+
+	/*Get maximum:*/
+	double maxvy=this->inputs->Max(VyEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvy=UnitConversion(maxvy,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvy=maxvy;
+
+}
+/*}}}*/
+/*FUNCTION Tria::MaxVz{{{1*/
+void  Tria::MaxVz(double* pmaxvz, bool process_units){
+
+	/*Get maximum:*/
+	double maxvz=this->inputs->Max(VzEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvz=UnitConversion(maxvz,IuToExtEnum,VzEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvz=maxvz;
+}
+/*}}}*/
+/*FUNCTION Tria::MinVel{{{1*/
+void  Tria::MinVel(double* pminvel, bool process_units){
+
+	/*Get minimum:*/
+	double minvel=this->inputs->Min(VelEnum);
+
+	/*process units if requested: */
+	if(process_units) minvel=UnitConversion(minvel,IuToExtEnum,VelEnum);
+
+	/*Assign output pointers:*/
+	*pminvel=minvel;
+}
+/*}}}*/
+/*FUNCTION Tria::MinVx{{{1*/
+void  Tria::MinVx(double* pminvx, bool process_units){
+
+	/*Get minimum:*/
+	double minvx=this->inputs->Min(VxEnum);
+
+	/*process units if requested: */
+	if(process_units) minvx=UnitConversion(minvx,IuToExtEnum,VxEnum);
+
+	/*Assign output pointers:*/
+	*pminvx=minvx;
+}
+/*}}}*/
+/*FUNCTION Tria::MinVy{{{1*/
+void  Tria::MinVy(double* pminvy, bool process_units){
+
+	/*Get minimum:*/
+	double minvy=this->inputs->Min(VyEnum);
+
+	/*process units if requested: */
+	if(process_units) minvy=UnitConversion(minvy,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pminvy=minvy;
+}
+/*}}}*/
+/*FUNCTION Tria::MinVz{{{1*/
+void  Tria::MinVz(double* pminvz, bool process_units){
+
+	/*Get minimum:*/
+	double minvz=this->inputs->Min(VzEnum);
+
+	/*process units if requested: */
+	if(process_units) minvz=UnitConversion(minvz,IuToExtEnum,VzEnum);
+
+	/*Assign output pointers:*/
+	*pminvz=minvz;
+}
+/*}}}*/
+/*FUNCTION Tria::NodalValue {{{1*/
+int    Tria::NodalValue(double* pvalue, int index, int natureofdataenum,bool process_units){
+
+	int i;
+	int found=0;
+	double 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(i=0;i<NUMVERTICES;i++){
+		if(index==nodes[i]->GetVertexId()){
+			/*Do we have natureofdataenum in our inputs? :*/
+			if(data){
+				/*ok, we are good. retrieve value of input at vertex :*/
+				gauss=new GaussTria(); gauss->GaussVertex(i);
+				data->GetInputValue(&value,gauss);
+				found=1;
+				break;
+			}
+		}
+	}
+
+	if(found)*pvalue=value;
+	return found;
+}
+/*}}}*/
+/*FUNCTION Tria::ElementResponse{{{1*/
+void Tria::ElementResponse(double* presponse,int response_enum,bool process_units){
+
+	switch(response_enum){
+		case MaterialsRheologyBbarEnum:
+			*presponse=this->matice->GetBbar();
+			break;
+		case VelEnum:
+
+			/*Get input:*/
+			double vel;
+			Input* vel_input;
+
+			vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
+			vel_input->GetInputAverage(&vel);
+
+			/*process units if requested: */
+			if(process_units) vel=UnitConversion(vel,IuToExtEnum,VelEnum);
+
+			/*Assign output pointers:*/
+			*presponse=vel;
+		default:  
+			_error_("Response type %s not supported yet!",EnumToStringx(response_enum));
+	}
+
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_DIAGNOSTIC_
+/*FUNCTION Tria::CreateKMatrixDiagnosticMacAyeal {{{1*/
+ElementMatrix* Tria::CreateKMatrixDiagnosticMacAyeal(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyealViscous();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticMacAyealFriction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+	
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixDiagnosticMacAyealViscous{{{1*/
+ElementMatrix* Tria::CreateKMatrixDiagnosticMacAyealViscous(void){
+
+	/*Constants*/
+	const int  numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries*/
+	int        i,j,ig;
+	double     xyz_list[NUMVERTICES][3];
+	double     viscosity,newviscosity,oldviscosity;
+	double     viscosity_overshoot,thickness,Jdet;
+	double     epsilon[3],oldepsilon[3];    /* epsilon=[exx,eyy,exy];    */
+	double     B[3][numdof];
+	double     Bprime[3][numdof];
+	double     D[3][3]   = {0.0};
+	double     D_scalar;
+	GaussTria *gauss = NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* vx_input=inputs->GetInput(VxEnum);               _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);               _assert_(vy_input);
+	Input* vxold_input=inputs->GetInput(VxPicardEnum);      _assert_(vxold_input);
+	Input* vyold_input=inputs->GetInput(VyPicardEnum);      _assert_(vyold_input);
+	this->parameters->FindParam(&viscosity_overshoot,DiagnosticViscosityOvershootEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		GetBMacAyeal(&B[0][0], &xyz_list[0][0], gauss);
+		GetBprimeMacAyeal(&Bprime[0][0], &xyz_list[0][0], gauss);
+
+		this->GetStrainRate2d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		this->GetStrainRate2d(&oldepsilon[0],&xyz_list[0][0],gauss,vxold_input,vyold_input);
+		matice->GetViscosity2d(&viscosity, &epsilon[0]);
+		matice->GetViscosity2d(&oldviscosity, &oldepsilon[0]);
+		thickness_input->GetInputValue(&thickness, gauss);
+
+		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		D_scalar=2*newviscosity*thickness*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+
+		TripleMultiply(&B[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&Bprime[0][0],3,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixDiagnosticMacAyealFriction {{{1*/
+ElementMatrix* Tria::CreateKMatrixDiagnosticMacAyealFriction(void){
+
+	/*Constants*/
+	const int  numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries*/
+	int        i,j,ig;
+	int        analysis_type;
+	double     MAXSLOPE  = .06; // 6 %
+	double     MOUNTAINKEXPONENT = 10;
+	double     slope_magnitude,alpha2;
+	double     Jdet;
+	double     L[2][numdof];
+	double     DL[2][2]  = {{ 0,0 },{0,0}};
+	double     DL_scalar;
+	double     slope[2]  = {0.0,0.0};
+	double     xyz_list[NUMVERTICES][3];
+	Friction  *friction = NULL;
+	GaussTria *gauss    = NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(IsFloating()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* surface_input=inputs->GetInput(SurfaceEnum); _assert_(surface_input);
+	Input* vx_input=inputs->GetInput(VxEnum);           _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);           _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);           _assert_(vz_input);
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*build friction object, used later on: */
+	friction=new Friction("2d",inputs,matpar,analysis_type);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		// If we have a slope > 6% for this element,  it means  we are on a mountain. In this particular case, 
+		//velocity should be = 0. To achieve this result, we set alpha2_list to a very high value: */
+		surface_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
+		slope_magnitude=sqrt(pow(slope[0],2)+pow(slope[1],2));
+		if(slope_magnitude>MAXSLOPE) alpha2=pow((double)10,MOUNTAINKEXPONENT);
+		else friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum);
+
+		GetL(&L[0][0], &xyz_list[0][0], gauss,NDOF2);
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		DL_scalar=alpha2*gauss->weight*Jdet;
+		for (i=0;i<2;i++) DL[i][i]=DL_scalar;
+		
+		TripleMultiply( &L[0][0],2,numdof,1,
+					&DL[0][0],2,2,0,
+					&L[0][0],2,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixDiagnosticHutter{{{1*/
+ElementMatrix* Tria::CreateKMatrixDiagnosticHutter(void){
+
+	/*Intermediaries*/
+	const int numdof=NUMVERTICES*NDOF2;
+	int    i,connectivity;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Create Element matrix*/
+	for(i=0;i<NUMVERTICES;i++){
+		connectivity=nodes[i]->GetConnectivity();
+		Ke->values[(2*i)*numdof  +(2*i)  ]=1/(double)connectivity;
+		Ke->values[(2*i+1)*numdof+(2*i+1)]=1/(double)connectivity;
+	}
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorDiagnosticMacAyeal {{{1*/
+ElementVector* Tria::CreatePVectorDiagnosticMacAyeal(){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int            i,j,ig;
+	double         driving_stress_baseline,thickness;
+	double         Jdet;
+	double         xyz_list[NUMVERTICES][3];
+	double         slope[2];
+	double         basis[3];
+	double         pe_g_gaussian[numdof];
+	GaussTria*     gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input); 
+	Input* surface_input=inputs->GetInput(SurfaceEnum);     _assert_(surface_input);
+	Input* drag_input=inputs->GetInput(FrictionCoefficientEnum);_assert_(drag_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		surface_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
+		driving_stress_baseline=matpar->GetRhoIce()*matpar->GetG()*thickness;
+
+		/*Build pe_g_gaussian vector: */
+		for (i=0;i<NUMVERTICES;i++){
+			for (j=0;j<NDOF2;j++){
+				pe->values[i*NDOF2+j]+=-driving_stress_baseline*slope[j]*Jdet*gauss->weight*basis[i];
+			}
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorDiagnosticHutter{{{1*/
+ElementVector* Tria::CreatePVectorDiagnosticHutter(void){
+
+	/*Intermediaries */
+	int        i,connectivity;
+	double     constant_part,ub,vb;
+	double     rho_ice,gravity,n,B;
+	double     slope2,thickness;
+	double     slope[2];
+	GaussTria* gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+	n=matice->GetN();
+	B=matice->GetBbar();
+	Input* slopex_input=inputs->GetInput(SurfaceSlopeXEnum); _assert_(slopex_input);
+	Input* slopey_input=inputs->GetInput(SurfaceSlopeYEnum); _assert_(slopey_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);  _assert_(thickness_input);
+
+	/*Spawn 3 sing elements: */
+	gauss=new GaussTria();
+	for(i=0;i<NUMVERTICES;i++){
+
+		gauss->GaussVertex(i);
+
+		connectivity=nodes[i]->GetConnectivity();
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		slopex_input->GetInputValue(&slope[0],gauss);
+		slopey_input->GetInputValue(&slope[1],gauss);
+		slope2=pow(slope[0],2)+pow(slope[1],2);
+
+		constant_part=-2*pow(rho_ice*gravity,n)*pow(slope2,((n-1)/2));
+
+		ub=-1.58*pow((double)10.0,(double)-10.0)*rho_ice*gravity*thickness*slope[0];
+		vb=-1.58*pow((double)10.0,(double)-10.0)*rho_ice*gravity*thickness*slope[1];
+
+		pe->values[2*i]  =(ub-2.0*pow(rho_ice*gravity,n)*pow(slope2,((n-1)/2.0))*pow(thickness,n)/(pow(B,n)*(n+1))*slope[0])/(double)connectivity;
+		pe->values[2*i+1]=(vb-2.0*pow(rho_ice*gravity,n)*pow(slope2,((n-1)/2.0))*pow(thickness,n)/(pow(B,n)*(n+1))*slope[1])/(double)connectivity;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::GetSolutionFromInputsDiagnosticHoriz{{{1*/
+void  Tria::GetSolutionFromInputsDiagnosticHoriz(Vec solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	double       vx,vy;
+	double       values[numdof];
+	GaussTria*   gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Get inputs*/
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	/*P1 element only for now*/
+	gauss=new GaussTria();
+	for(i=0;i<NUMVERTICES;i++){
+
+		gauss->GaussVertex(i);
+
+		/*Recover vx and vy*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		values[i*NDOF2+0]=vx;
+		values[i*NDOF2+1]=vy;
+	}
+
+	VecSetValues(solution,numdof,doflist,(const double*)values,INSERT_VALUES);
+
+	/*Free ressources:*/
+	delete gauss;
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::GetSolutionFromInputsDiagnosticHutter{{{1*/
+void  Tria::GetSolutionFromInputsDiagnosticHutter(Vec solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int        i;
+	double     vx,vy;
+	double     values[numdof];
+	int       *doflist = NULL;
+	GaussTria *gauss   = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Get inputs*/
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	/*P1 element only for now*/
+	gauss=new GaussTria();
+	for(i=0;i<NUMVERTICES;i++){
+
+		gauss->GaussVertex(i);
+
+		/*Recover vx and vy*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		values[i*NDOF2+0]=vx;
+		values[i*NDOF2+1]=vy;
+	}
+
+	VecSetValues(solution,numdof,doflist,(const double*)values,INSERT_VALUES);
+
+	/*Free ressources:*/
+	delete gauss;
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionDiagnosticHoriz {{{1*/
+void  Tria::InputUpdateFromSolutionDiagnosticHoriz(double* solution){
+	
+	const int numdof=NDOF2*NUMVERTICES;
+
+	int       i;
+	int*      doflist=NULL;
+	double    rho_ice,g;
+	double    values[numdof];
+	double    vx[NUMVERTICES];
+	double    vy[NUMVERTICES];
+	double    vz[NUMVERTICES];
+	double    vel[NUMVERTICES];
+	double    pressure[NUMVERTICES];
+	double    thickness[NUMVERTICES];
+	
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&values[0],nodes,NUMVERTICES,XYEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		vx[i]=values[i*NDOF2+0];
+		vy[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(isnan(vx[i])) _error_("NaN found in solution vector");
+		if(isnan(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz and compute vel*/
+	GetInputListOnVertices(&vz[0],VzEnum,0);
+	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 2D, 
+	 *so the pressure is just the pressure at the bedrock: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	GetInputListOnVertices(&thickness[0],ThicknessEnum);
+	for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*thickness[i];
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new TriaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new TriaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new TriaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new TriaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionDiagnosticHutter {{{1*/
+void  Tria::InputUpdateFromSolutionDiagnosticHutter(double* solution){
+	
+	const int numdof=NDOF2*NUMVERTICES;
+	
+	int       i;
+	int*      doflist=NULL;
+	double    rho_ice,g;
+	double    values[numdof];
+	double    vx[NUMVERTICES];
+	double    vy[NUMVERTICES];
+	double    vz[NUMVERTICES];
+	double    vel[NUMVERTICES];
+	double    pressure[NUMVERTICES];
+	double    thickness[NUMVERTICES];
+	
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		vx[i]=values[i*NDOF2+0];
+		vy[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(isnan(vx[i])) _error_("NaN found in solution vector");
+		if(isnan(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Now Compute vel*/
+	GetInputListOnVertices(&vz[0],VzEnum,0.0); //default is 0
+	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 2D, 
+	 *so the pressure is just the pressure at the bedrock: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	GetInputListOnVertices(&thickness[0],ThicknessEnum);
+	for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*thickness[i];
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new TriaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new TriaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new TriaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new TriaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_CONTROL_
+/*FUNCTION Tria::InputControlUpdate{{{1*/
+void  Tria::InputControlUpdate(double scalar,bool save_parameter){
+
+	/*Intermediary*/
+	int    num_controls;
+	int*   control_type=NULL;
+	Input* input=NULL;
+
+	/*retrieve some parameters: */
+	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+	for(int i=0;i<num_controls;i++){
+
+		if(control_type[i]==MaterialsRheologyBbarEnum){
+			input=(Input*)matice->inputs->GetInput(control_type[i]); _assert_(input);
+		}
+		else{
+			input=(Input*)this->inputs->GetInput(control_type[i]);   _assert_(input);
+		}
+
+		if (input->ObjectEnum()!=ControlInputEnum){
+			_error_("input %s is not a ControlInput",EnumToStringx(control_type[i]));
+		}
+
+		((ControlInput*)input)->UpdateValue(scalar);
+		((ControlInput*)input)->Constrain();
+		if (save_parameter) ((ControlInput*)input)->SaveValue();
+
+	}
+
+	/*Clean up and return*/
+	xfree((void**)&control_type);
+}
+/*}}}*/
+/*FUNCTION Tria::ControlInputGetGradient{{{1*/
+void Tria::ControlInputGetGradient(Vec gradient,int enum_type){
+
+	int doflist1[NUMVERTICES];
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)matice->inputs->GetInput(enum_type);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input %s not found",EnumToStringx(enum_type));
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input %s is not a ControlInput",EnumToStringx(enum_type));
+
+	this->GetDofList1(&doflist1[0]);
+	((ControlInput*)input)->GetGradient(gradient,&doflist1[0]);
+
+}/*}}}*/
+/*FUNCTION Tria::ControlInputScaleGradient{{{1*/
+void Tria::ControlInputScaleGradient(int enum_type,double scale){
+
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)matice->inputs->GetInput(enum_type);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input %s not found",EnumToStringx(enum_type));
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input %s is not a ControlInput",EnumToStringx(enum_type));
+
+	((ControlInput*)input)->ScaleGradient(scale);
+}/*}}}*/
+/*FUNCTION Tria::ControlInputSetGradient{{{1*/
+void Tria::ControlInputSetGradient(double* gradient,int enum_type){
+
+	int    doflist1[NUMVERTICES];
+	double grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)matice->inputs->GetInput(enum_type);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input %s not found",EnumToStringx(enum_type));
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input %s is not a ControlInput",EnumToStringx(enum_type));
+
+	this->GetDofList1(&doflist1[0]);
+	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[doflist1[i]];
+	grad_input=new TriaP1Input(GradientEnum,grad_list);
+
+	((ControlInput*)input)->SetGradient(grad_input);
+
+}/*}}}*/
+/*FUNCTION Tria::Gradj {{{1*/
+void  Tria::Gradj(Vec gradient,int control_type){
+	/*dJ/dalpha = ∂L/∂alpha = ∂J/∂alpha + ∂/∂alpha(KU-F)*/
+
+	/*If on water, grad = 0: */
+	if(IsOnWater()) return;
+
+	/*First deal with ∂/∂alpha(KU-F)*/
+	switch(control_type){
+		case FrictionCoefficientEnum:
+			GradjDragMacAyeal(gradient);
+			break;
+		case MaterialsRheologyBbarEnum:
+			GradjBMacAyeal(gradient);
+			break;
+		case BalancethicknessThickeningRateEnum:
+			GradjDhDtBalancedthickness(gradient);
+			break;
+		case VxEnum:
+			GradjVxBalancedthickness(gradient);
+			break;
+		case VyEnum:
+			GradjVyBalancedthickness(gradient);
+			break;
+		default:
+			_error_("%s%i","control type not supported yet: ",control_type);
+	}
+
+	/*Now deal with ∂J/∂alpha*/
+	int        *responses = NULL;
+	int         num_responses,resp;
+	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+
+	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+		//FIXME: the control type should be checked somewhere (with respect to what variable are we taking the gradient!)
+
+		case ThicknessAbsMisfitEnum:
+		case ThicknessAbsGradientEnum:
+		case SurfaceAbsVelMisfitEnum:
+		case SurfaceRelVelMisfitEnum:
+		case SurfaceLogVelMisfitEnum:
+		case SurfaceLogVxVyMisfitEnum:
+		case SurfaceAverageVelMisfitEnum:
+			/*Nothing, J does not depends on the parameter being inverted for*/
+			break;
+		case DragCoefficientAbsGradientEnum:
+			GradjDragGradient(gradient,resp);
+			break;
+		case RheologyBbarAbsGradientEnum:
+			GradjBGradient(gradient,resp);
+			break;
+		default:
+			_error_("response %s not supported yet",EnumToStringx(responses[resp]));
+	}
+
+	xfree((void**)&responses);
+}
+/*}}}*/
+/*FUNCTION Tria::GradjBGradient{{{1*/
+void  Tria::GradjBGradient(Vec gradient, int weight_index){
+
+	int        i,ig;
+	int        doflist1[NUMVERTICES];
+	double     Jdet,weight;
+	double     xyz_list[NUMVERTICES][3];
+	double     dbasis[NDOF2][NUMVERTICES];
+	double     dk[NDOF2]; 
+	double     grade_g[NUMVERTICES]={0.0};
+	GaussTria  *gauss=NULL;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	GetDofList1(&doflist1[0]);
+	Input* rheologyb_input=matice->inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+
+		/*Build alpha_complement_list: */
+		rheologyb_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for (i=0;i<NUMVERTICES;i++) grade_g[i]+=-weight*Jdet*gauss->weight*(dbasis[0][i]*dk[0]+dbasis[1][i]*dk[1]);
+	}
+	VecSetValues(gradient,NUMVERTICES,doflist1,(const double*)grade_g,ADD_VALUES);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjBMacAyeal{{{1*/
+void  Tria::GradjBMacAyeal(Vec gradient){
+
+	/*Intermediaries*/
+	int        i,ig;
+	int        doflist[NUMVERTICES];
+	double     vx,vy,lambda,mu,thickness,Jdet;
+	double     viscosity_complement;
+	double     dvx[NDOF2],dvy[NDOF2],dadjx[NDOF2],dadjy[NDOF2],dB[NDOF2]; 
+	double     xyz_list[NUMVERTICES][3];
+	double     basis[3],epsilon[3];
+	double     grad[NUMVERTICES]={0.0};
+	GaussTria *gauss = NULL;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	GetDofList1(&doflist[0]);
+
+	/*Retrieve all inputs*/
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);            _assert_(thickness_input);
+	Input* vx_input=inputs->GetInput(VxEnum);                          _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                          _assert_(vy_input);
+	Input* adjointx_input=inputs->GetInput(AdjointxEnum);              _assert_(adjointx_input);
+	Input* adjointy_input=inputs->GetInput(AdjointyEnum);              _assert_(adjointy_input);
+	Input* rheologyb_input=matice->inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(4);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		rheologyb_input->GetInputDerivativeValue(&dB[0],&xyz_list[0][0],gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
+		adjointx_input->GetInputDerivativeValue(&dadjx[0],&xyz_list[0][0],gauss);
+		adjointy_input->GetInputDerivativeValue(&dadjy[0],&xyz_list[0][0],gauss);
+
+		this->GetStrainRate2d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		matice->GetViscosityComplement(&viscosity_complement,&epsilon[0]);
+
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		/*standard gradient dJ/dki*/
+		for (i=0;i<NUMVERTICES;i++) grad[i]+=-viscosity_complement*thickness*(
+					(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
+					)*Jdet*gauss->weight*basis[i];
+	}
+
+	VecSetValues(gradient,NUMVERTICES,doflist,(const double*)grad,ADD_VALUES);
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjDragMacAyeal {{{1*/
+void  Tria::GradjDragMacAyeal(Vec gradient){
+
+	int        i,ig;
+	int        analysis_type;
+	int        doflist1[NUMVERTICES];
+	double     vx,vy,lambda,mu,alpha_complement,Jdet;
+	double     bed,thickness,Neff,drag;
+	double     xyz_list[NUMVERTICES][3];
+	double     dk[NDOF2]; 
+	double     grade_g[NUMVERTICES]={0.0};
+	double     grade_g_gaussian[NUMVERTICES];
+	double     basis[3];
+	double     epsilon[3]; /* epsilon=[exx,eyy,exy];*/
+	Friction*  friction=NULL;
+	GaussTria  *gauss=NULL;
+
+	if(IsFloating())return;
+
+	/*retrive parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	GetDofList1(&doflist1[0]);
+
+	/*Build frictoin element, needed later: */
+	friction=new Friction("2d",inputs,matpar,analysis_type);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* adjointx_input=inputs->GetInput(AdjointxEnum);               _assert_(adjointx_input);
+	Input* adjointy_input=inputs->GetInput(AdjointyEnum);               _assert_(adjointy_input);
+	Input* vx_input=inputs->GetInput(VxEnum);                           _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                           _assert_(vy_input);
+	Input* dragcoefficient_input=inputs->GetInput(FrictionCoefficientEnum); _assert_(dragcoefficient_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(4);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+
+		/*Build alpha_complement_list: */
+		friction->GetAlphaComplement(&alpha_complement, gauss,VxEnum,VyEnum,VzEnum);
+	
+		dragcoefficient_input->GetInputValue(&drag, gauss);
+		adjointx_input->GetInputValue(&lambda, gauss);
+		adjointy_input->GetInputValue(&mu, gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		dragcoefficient_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for (i=0;i<NUMVERTICES;i++){
+			grade_g_gaussian[i]=-2*drag*alpha_complement*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i];
+		}
+		
+		/*Add gradje_g_gaussian vector to gradje_g: */
+		for(i=0;i<NUMVERTICES;i++){
+			_assert_(!isnan(grade_g[i]));
+			grade_g[i]+=grade_g_gaussian[i];
+		}
+	}
+	/*Analytical gradient*/
+	//delete gauss;
+	//gauss=new GaussTria();
+	//for (int iv=0;iv<NUMVERTICES;iv++){
+	//	gauss->GaussVertex(iv);
+	//	friction->GetAlphaComplement(&alpha_complement, gauss,VxEnum,VyEnum,VzEnum);
+	//	dragcoefficient_input->GetInputValue(&drag, gauss);
+	//	adjointx_input->GetInputValue(&lambda, gauss);
+	//	adjointy_input->GetInputValue(&mu, gauss);
+	//	vx_input->GetInputValue(&vx,gauss);
+	//	vy_input->GetInputValue(&vy,gauss);
+	//	grade_g[iv]=-2*drag*alpha_complement*((lambda*vx+mu*vy));
+	//	VecSetValues(gradient,NUMVERTICES,doflist1,(const double*)grade_g,INSERT_VALUES);
+	//}
+	/*End Analytical gradient*/
+
+	VecSetValues(gradient,NUMVERTICES,doflist1,(const double*)grade_g,ADD_VALUES);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjDragGradient{{{1*/
+void  Tria::GradjDragGradient(Vec gradient, int weight_index){
+
+	int        i,ig;
+	int        doflist1[NUMVERTICES];
+	double     Jdet,weight;
+	double     xyz_list[NUMVERTICES][3];
+	double     dbasis[NDOF2][NUMVERTICES];
+	double     dk[NDOF2]; 
+	double     grade_g[NUMVERTICES]={0.0};
+	GaussTria  *gauss=NULL;
+
+	/*Retrieve all inputs we will be needing: */
+	if(IsFloating())return;
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	GetDofList1(&doflist1[0]);
+	Input* dragcoefficient_input=inputs->GetInput(FrictionCoefficientEnum); _assert_(dragcoefficient_input);
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                 _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+
+		/*Build alpha_complement_list: */
+		dragcoefficient_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for (i=0;i<NUMVERTICES;i++){
+			grade_g[i]+=-weight*Jdet*gauss->weight*(dbasis[0][i]*dk[0]+dbasis[1][i]*dk[1]);
+			_assert_(!isnan(grade_g[i]));
+		}
+	}
+	VecSetValues(gradient,NUMVERTICES,doflist1,(const double*)grade_g,ADD_VALUES);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjDhDtBalancedthickness{{{1*/
+void  Tria::GradjDhDtBalancedthickness(Vec gradient){
+
+	/*Intermediaries*/
+	int    doflist1[NUMVERTICES];
+	double lambda[NUMVERTICES];
+	double gradient_g[NUMVERTICES];
+
+	GetDofList1(&doflist1[0]);
+
+	/*Compute Gradient*/
+	GetInputListOnVertices(&lambda[0],AdjointEnum);
+	for(int i=0;i<NUMVERTICES;i++) gradient_g[i]=-lambda[i];
+
+	VecSetValues(gradient,NUMVERTICES,doflist1,(const double*)gradient_g,INSERT_VALUES);
+}
+/*}}}*/
+/*FUNCTION Tria::GradjVxBalancedthickness{{{1*/
+void  Tria::GradjVxBalancedthickness(Vec gradient){
+
+	/*Intermediaries*/
+	int        i,ig;
+	int        doflist1[NUMVERTICES];
+	double     thickness,Jdet;
+	double     basis[3];
+	double     Dlambda[2],dp[2];
+	double     xyz_list[NUMVERTICES][3];
+	double     grade_g[NUMVERTICES] = {0.0};
+	GaussTria *gauss                = NULL;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	GetDofList1(&doflist1[0]);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* adjoint_input=inputs->GetInput(AdjointEnum);     _assert_(adjoint_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+		
+		adjoint_input->GetInputDerivativeValue(&Dlambda[0],&xyz_list[0][0],gauss);
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
+
+		for(i=0;i<NUMVERTICES;i++) grade_g[i]+=thickness*Dlambda[0]*Jdet*gauss->weight*basis[i];
+	}
+
+	VecSetValues(gradient,NUMVERTICES,doflist1,(const double*)grade_g,ADD_VALUES);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjVyBalancedthickness{{{1*/
+void  Tria::GradjVyBalancedthickness(Vec gradient){
+
+	/*Intermediaries*/
+	int        i,ig;
+	int        doflist1[NUMVERTICES];
+	double     thickness,Jdet;
+	double     basis[3];
+	double     Dlambda[2],dp[2];
+	double     xyz_list[NUMVERTICES][3];
+	double     grade_g[NUMVERTICES] = {0.0};
+	GaussTria *gauss                = NULL;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	GetDofList1(&doflist1[0]);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* adjoint_input=inputs->GetInput(AdjointEnum);     _assert_(adjoint_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+
+		adjoint_input->GetInputDerivativeValue(&Dlambda[0],&xyz_list[0][0],gauss);
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
+
+		for(i=0;i<NUMVERTICES;i++) grade_g[i]+=thickness*Dlambda[1]*Jdet*gauss->weight*basis[i];
+	}
+	VecSetValues(gradient,NUMVERTICES,doflist1,(const double*)grade_g,ADD_VALUES);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::RheologyBbarAbsGradient{{{1*/
+double Tria::RheologyBbarAbsGradient(bool process_units,int weight_index){
+
+	/* Intermediaries */
+	int        ig;
+	double     Jelem = 0;
+	double     weight;
+	double     Jdet;
+	double     xyz_list[NUMVERTICES][3];
+	double     dp[NDOF2];
+	GaussTria *gauss = NULL;
+
+	/*retrieve parameters and inputs*/
+
+	/*If on water, return 0: */
+	if(IsOnWater()) return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* weights_input  =inputs->GetInput(InversionCostFunctionsCoefficientsEnum);              _assert_(weights_input);
+	Input* rheologyb_input=matice->inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		rheologyb_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
+
+		/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
+		//Jelem+=weight*1/2*(pow(dp[0],2.)+pow(dp[1],2.))*Jdet*gauss->weight;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceAverageVelMisfit {{{1*/
+double Tria::SurfaceAverageVelMisfit(bool process_units,int weight_index){
+
+	const int    numdof=2*NUMVERTICES;
+
+	int        i,ig;
+	double     Jelem=0,S,Jdet;
+	double     misfit;
+	double     vx,vy,vxobs,vyobs,weight;
+	double     xyz_list[NUMVERTICES][3];
+	GaussTria *gauss=NULL;
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	inputs->GetInputValue(&S,SurfaceAreaEnum);
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
+	Input* vy_input     =inputs->GetInput(VyEnum);        _assert_(vy_input);
+	Input* vxobs_input  =inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
+	Input* vyobs_input  =inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(3);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+
+		/*Compute SurfaceAverageVelMisfitEnum:
+		 *
+		 *      1                    2              2
+		 * J = ---  sqrt(  (u - u   )  +  (v - v   )  )
+		 *      S                obs            obs
+		 */
+		misfit=1/S*pow( pow(vx-vxobs,2.) + pow(vy-vyobs,2.) ,0.5);
+
+		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceAverageVelMisfitEnum);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean-up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceLogVelMisfit {{{1*/
+double Tria::SurfaceLogVelMisfit(bool process_units,int weight_index){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int        i,ig;
+	double     Jelem=0;
+	double     misfit,Jdet;
+	double     epsvel=2.220446049250313e-16;
+	double     meanvel=3.170979198376458e-05; /*1000 m/yr*/
+	double     velocity_mag,obs_velocity_mag;
+	double     xyz_list[NUMVERTICES][3];
+	double     vx,vy,vxobs,vyobs,weight;
+	GaussTria *gauss=NULL;
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
+	Input* vy_input     =inputs->GetInput(VyEnum);        _assert_(vy_input);
+	Input* vxobs_input  =inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
+	Input* vyobs_input  =inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(4);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+
+		/*Compute SurfaceLogVelMisfit:
+		 *                 [        vel + eps     ] 2
+		 * J = 4 \bar{v}^2 | log ( -----------  ) |  
+		 *                 [       vel   + eps    ]
+		 *                            obs
+		 */
+		velocity_mag    =sqrt(pow(vx,   2.)+pow(vy,   2.))+epsvel;
+		obs_velocity_mag=sqrt(pow(vxobs,2.)+pow(vyobs,2.))+epsvel;
+		misfit=4*pow(meanvel,2.)*pow(log(velocity_mag/obs_velocity_mag),2.);
+
+		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceLogVelMisfitEnum);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean-up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceLogVxVyMisfit {{{1*/
+double Tria::SurfaceLogVxVyMisfit(bool process_units,int weight_index){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int        i,ig;
+	int        fit=-1;
+	double     Jelem=0, S=0;
+	double     epsvel=2.220446049250313e-16;
+	double     meanvel=3.170979198376458e-05; /*1000 m/yr*/
+	double     misfit, Jdet;
+	double     vx,vy,vxobs,vyobs,weight;
+	double     xyz_list[NUMVERTICES][3];
+	GaussTria *gauss=NULL;
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
+	Input* vy_input     =inputs->GetInput(VyEnum);        _assert_(vy_input);
+	Input* vxobs_input  =inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
+	Input* vyobs_input  =inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);
+	
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(4);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+
+		/*Compute SurfaceRelVelMisfit:
+		 *
+		 *      1            [        |u| + eps     2          |v| + eps     2  ]
+		 * J = --- \bar{v}^2 | log ( -----------  )   +  log ( -----------  )   |  
+		 *      2            [       |u    |+ eps              |v    |+ eps     ]
+		 *                              obs                       obs
+		 */
+		misfit=0.5*pow(meanvel,2.)*(
+					pow(log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)),2.) +
+					pow(log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)),2.) );
+
+		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceLogVxVyMisfitEnum);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean-up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceAbsVelMisfit {{{1*/
+double Tria::SurfaceAbsVelMisfit(bool process_units,int weight_index){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int        i,ig;
+	double     Jelem=0;
+	double     misfit,Jdet;
+	double     vx,vy,vxobs,vyobs,weight;
+	double     xyz_list[NUMVERTICES][3];
+	GaussTria *gauss=NULL;
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
+	Input* vy_input     =inputs->GetInput(VyEnum);        _assert_(vy_input);
+	Input* vxobs_input  =inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
+	Input* vyobs_input  =inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+
+		/*Compute SurfaceAbsVelMisfitEnum:
+		 *
+		 *      1  [           2              2 ]
+		 * J = --- | (u - u   )  +  (v - v   )  |
+		 *      2  [       obs            obs   ]
+		 *
+		 */
+		misfit=0.5*( pow(vx-vxobs,2.) + pow(vy-vyobs,2.) );
+
+		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceAverageVelMisfitEnum);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceRelVelMisfit {{{1*/
+double Tria::SurfaceRelVelMisfit(bool process_units,int weight_index){
+	const int  numdof=2*NUMVERTICES;
+
+	int        i,ig;
+	double     Jelem=0;
+	double     scalex=1,scaley=1;
+	double     misfit,Jdet;
+	double     epsvel=2.220446049250313e-16;
+	double     meanvel=3.170979198376458e-05; /*1000 m/yr*/
+	double     vx,vy,vxobs,vyobs,weight;
+	double     xyz_list[NUMVERTICES][3];
+	GaussTria *gauss=NULL;
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
+	Input* vy_input     =inputs->GetInput(VyEnum);        _assert_(vy_input);
+	Input* vxobs_input  =inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
+	Input* vyobs_input  =inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(4);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+
+		/*Compute SurfaceRelVelMisfit:
+		 *                        
+		 *      1  [     \bar{v}^2             2   \bar{v}^2              2 ]
+		 * J = --- | -------------  (u - u   ) + -------------  (v - v   )  |
+		 *      2  [  (u   + eps)^2       obs    (v   + eps)^2       obs    ]
+		 *              obs                        obs                      
+		 */
+		scalex=pow(meanvel/(vxobs+epsvel),2.); if(vxobs==0)scalex=0;
+		scaley=pow(meanvel/(vyobs+epsvel),2.); if(vyobs==0)scaley=0;
+		misfit=0.5*(scalex*pow((vx-vxobs),2.)+scaley*pow((vy-vyobs),2.));
+		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceRelVelMisfitEnum);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::ThicknessAbsGradient{{{1*/
+double Tria::ThicknessAbsGradient(bool process_units,int weight_index){
+
+	/* Intermediaries */
+	int        ig;
+	double     Jelem = 0;
+	double     weight;
+	double     Jdet;
+	double     xyz_list[NUMVERTICES][3];
+	double     dp[NDOF2];
+	GaussTria *gauss = NULL;
+
+	/*retrieve parameters and inputs*/
+
+	/*If on water, return 0: */
+	if(IsOnWater()) return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* weights_input  =inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		thickness_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
+
+		/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
+		Jelem+=weight*1/2*(pow(dp[0],2.)+pow(dp[1],2.))*Jdet*gauss->weight;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::ThicknessAbsMisfit {{{1*/
+double Tria::ThicknessAbsMisfit(bool process_units,int weight_index){
+
+	/*Intermediaries*/
+	int        i,ig;
+	double     thickness,thicknessobs,weight;
+	double     Jdet;
+	double     Jelem = 0;
+	double     xyz_list[NUMVERTICES][3];
+	GaussTria *gauss = NULL;
+	double     dH[2];
+
+	/*If on water, return 0: */
+	if(IsOnWater())return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* thickness_input   =inputs->GetInput(ThicknessEnum);   _assert_(thickness_input);
+	Input* thicknessobs_input=inputs->GetInput(InversionThicknessObsEnum);_assert_(thicknessobs_input);
+	Input* weights_input     =inputs->GetInput(InversionCostFunctionsCoefficientsEnum);     _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get parameters at gauss point*/
+		thickness_input->GetInputValue(&thickness,gauss);
+		thickness_input->GetInputDerivativeValue(&dH[0],&xyz_list[0][0],gauss);
+		thicknessobs_input->GetInputValue(&thicknessobs,gauss);
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+
+		/*compute ThicknessAbsMisfit*/
+		Jelem+=0.5*pow(thickness-thicknessobs,2.0)*weight*Jdet*gauss->weight;
+	}
+
+	/* clean up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorAdjointBalancethickness{{{1*/
+ElementVector* Tria::CreatePVectorAdjointBalancethickness(void){
+
+	/*Constants*/
+	const int    numdof=1*NUMVERTICES;
+
+	/*Intermediaries */
+	int         i,ig,resp;
+	double      Jdet;
+	double      thickness,thicknessobs,weight;
+	int        *responses = NULL;
+	int         num_responses;
+	double      xyz_list[NUMVERTICES][3];
+	double      basis[3];
+	double      dbasis[NDOF2][NUMVERTICES];
+	double      dH[2];
+	GaussTria*  gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+	Input* thickness_input    = inputs->GetInput(ThicknessEnum);   _assert_(thickness_input);
+	Input* thicknessobs_input = inputs->GetInput(InversionThicknessObsEnum);_assert_(thicknessobs_input);
+	Input* weights_input      = inputs->GetInput(InversionCostFunctionsCoefficientsEnum);     _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dH[0],&xyz_list[0][0],gauss);
+		thicknessobs_input->GetInputValue(&thicknessobs, gauss);
+
+		/*Loop over all requested responses*/
+		for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+
+			case ThicknessAbsMisfitEnum:
+				weights_input->GetInputValue(&weight, gauss,resp);
+				for(i=0;i<numdof;i++) pe->values[i]+=(thicknessobs-thickness)*weight*Jdet*gauss->weight*basis[i];
+				break;
+			case ThicknessAbsGradientEnum:
+				weights_input->GetInputValue(&weight, gauss,resp);
+				for(i=0;i<numdof;i++) pe->values[i]+= - weight*dH[0]*dbasis[0][i]*Jdet*gauss->weight;
+				for(i=0;i<numdof;i++) pe->values[i]+= - weight*dH[1]*dbasis[1][i]*Jdet*gauss->weight;
+				break;
+			default:
+				_error_("response %s not supported yet",EnumToStringx(responses[resp]));
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorAdjointHoriz{{{1*/
+ElementVector* Tria::CreatePVectorAdjointHoriz(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,resp,ig;
+	int       *responses=NULL;
+	int        num_responses;
+	double     Jdet;
+	double     obs_velocity_mag,velocity_mag;
+	double     dux,duy;
+	double     epsvel=2.220446049250313e-16;
+	double     meanvel=3.170979198376458e-05; /*1000 m/yr*/
+	double     scalex=0,scaley=0,scale=0,S=0;
+	double     vx,vy,vxobs,vyobs,weight;
+	double     xyz_list[NUMVERTICES][3];
+	double     basis[3];
+	GaussTria* gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
+	Input* vy_input     =inputs->GetInput(VyEnum);        _assert_(vy_input);
+	Input* vxobs_input  =inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
+	Input* vyobs_input  =inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);
+
+	/*Get Surface if required by one response*/
+	for(resp=0;resp<num_responses;resp++){
+		if(responses[resp]==SurfaceAverageVelMisfitEnum){
+			inputs->GetInputValue(&S,SurfaceAreaEnum); break;
+		}
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(4);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+		GetNodalFunctions(basis, gauss);
+
+		/*Loop over all requested responses*/
+		for(resp=0;resp<num_responses;resp++){
+
+			weights_input->GetInputValue(&weight,gauss,resp);
+
+			switch(responses[resp]){
+				case SurfaceAbsVelMisfitEnum:
+					/*
+					 *      1  [           2              2 ]
+					 * J = --- | (u - u   )  +  (v - v   )  |
+					 *      2  [       obs            obs   ]
+					 *
+					 *        dJ
+					 * DU = - -- = (u   - u )
+					 *        du     obs
+					 */
+					for (i=0;i<NUMVERTICES;i++){
+						dux=vxobs-vx;
+						duy=vyobs-vy;
+						pe->values[i*NDOF2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceRelVelMisfitEnum:
+					/*
+					 *      1  [     \bar{v}^2             2   \bar{v}^2              2 ]
+					 * J = --- | -------------  (u - u   ) + -------------  (v - v   )  |
+					 *      2  [  (u   + eps)^2       obs    (v   + eps)^2       obs    ]
+					 *              obs                        obs                      
+					 *
+					 *        dJ     \bar{v}^2
+					 * DU = - -- = ------------- (u   - u )
+					 *        du   (u   + eps)^2    obs
+					 *               obs
+					 */
+					for (i=0;i<NUMVERTICES;i++){
+						scalex=pow(meanvel/(vxobs+epsvel),2.); if(vxobs==0)scalex=0;
+						scaley=pow(meanvel/(vyobs+epsvel),2.); if(vyobs==0)scaley=0;
+						dux=scalex*(vxobs-vx);
+						duy=scaley*(vyobs-vy);
+						pe->values[i*NDOF2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceLogVelMisfitEnum:
+					/*
+					 *                 [        vel + eps     ] 2
+					 * J = 4 \bar{v}^2 | log ( -----------  ) |  
+					 *                 [       vel   + eps    ]
+					 *                            obs
+					 *
+					 *        dJ                 2 * log(...)
+					 * DU = - -- = - 4 \bar{v}^2 -------------  u
+					 *        du                 vel^2 + eps
+					 *            
+					 */
+					for (i=0;i<NUMVERTICES;i++){
+						velocity_mag    =sqrt(pow(vx,   2.)+pow(vy,   2.))+epsvel;
+						obs_velocity_mag=sqrt(pow(vxobs,2.)+pow(vyobs,2.))+epsvel;
+						scale=-8*pow(meanvel,2.)/pow(velocity_mag,2.)*log(velocity_mag/obs_velocity_mag);
+						dux=scale*vx;
+						duy=scale*vy;
+						pe->values[i*NDOF2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceAverageVelMisfitEnum:
+					/*
+					 *      1                    2              2
+					 * J = ---  sqrt(  (u - u   )  +  (v - v   )  )
+					 *      S                obs            obs
+					 *
+					 *        dJ      1       1 
+					 * DU = - -- = - --- ----------- * 2 (u - u   )
+					 *        du      S  2 sqrt(...)           obs
+					 */
+					for (i=0;i<NUMVERTICES;i++){
+						scale=1./(S*2*sqrt(pow(vx-vxobs,2.)+pow(vy-vyobs,2.))+epsvel);
+						dux=scale*(vxobs-vx);
+						duy=scale*(vyobs-vy);
+						pe->values[i*NDOF2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceLogVxVyMisfitEnum:
+					/*
+					 *      1            [        |u| + eps     2          |v| + eps     2  ]
+					 * J = --- \bar{v}^2 | log ( -----------  )   +  log ( -----------  )   |  
+					 *      2            [       |u    |+ eps              |v    |+ eps     ]
+					 *                              obs                       obs
+					 *        dJ                              1      u                             1
+					 * DU = - -- = - \bar{v}^2 log(u...) --------- ----  ~ - \bar{v}^2 log(u...) ------
+					 *        du                         |u| + eps  |u|                           u + eps
+					 */
+					for (i=0;i<NUMVERTICES;i++){
+						dux = - pow(meanvel,2.) * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+						duy = - pow(meanvel,2.) * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
+						pe->values[i*NDOF2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case DragCoefficientAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case RheologyBbarAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				default:
+					_error_("response %s not supported yet",EnumToStringx(responses[resp]));
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xfree((void**)&responses);
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorAdjointStokes{{{1*/
+ElementVector* Tria::CreatePVectorAdjointStokes(void){
+
+	/*Intermediaries */
+	int        i,resp,ig;
+	int       *responses=NULL;
+	int        num_responses;
+	double     Jdet;
+	double     obs_velocity_mag,velocity_mag;
+	double     dux,duy;
+	double     epsvel=2.220446049250313e-16;
+	double     meanvel=3.170979198376458e-05; /*1000 m/yr*/
+	double     scalex=0,scaley=0,scale=0,S=0;
+	double     vx,vy,vxobs,vyobs,weight;
+	double     xyz_list[NUMVERTICES][3];
+	double     basis[3];
+	GaussTria* gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+	Input* weights_input = inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+	Input* vx_input      = inputs->GetInput(VxEnum);        _assert_(vx_input);
+	Input* vy_input      = inputs->GetInput(VyEnum);        _assert_(vy_input);
+	Input* vxobs_input   = inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
+	Input* vyobs_input   = inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);
+
+	/*Get Surface if required by one response*/
+	for(resp=0;resp<num_responses;resp++){
+		if(responses[resp]==SurfaceAverageVelMisfitEnum){
+			inputs->GetInputValue(&S,SurfaceAreaEnum); break;
+		}
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(4);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+		GetNodalFunctions(basis, gauss);
+
+		/*Loop over all requested responses*/
+		for(resp=0;resp<num_responses;resp++){
+
+			weights_input->GetInputValue(&weight,gauss,resp);
+
+			switch(responses[resp]){
+
+				case SurfaceAbsVelMisfitEnum:
+					/*
+					 *      1  [           2              2 ]
+					 * J = --- | (u - u   )  +  (v - v   )  |
+					 *      2  [       obs            obs   ]
+					 *
+					 *        dJ
+					 * DU = - -- = (u   - u )
+					 *        du     obs
+					 */
+					for (i=0;i<NUMVERTICES;i++){
+						dux=vxobs-vx;
+						duy=vyobs-vy;
+						pe->values[i*NDOF4+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF4+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceRelVelMisfitEnum:
+					/*
+					 *      1  [     \bar{v}^2             2   \bar{v}^2              2 ]
+					 * J = --- | -------------  (u - u   ) + -------------  (v - v   )  |
+					 *      2  [  (u   + eps)^2       obs    (v   + eps)^2       obs    ]
+					 *              obs                        obs                      
+					 *
+					 *        dJ     \bar{v}^2
+					 * DU = - -- = ------------- (u   - u )
+					 *        du   (u   + eps)^2    obs
+					 *               obs
+					 */
+					for (i=0;i<NUMVERTICES;i++){
+						scalex=pow(meanvel/(vxobs+epsvel),2.); if(vxobs==0)scalex=0;
+						scaley=pow(meanvel/(vyobs+epsvel),2.); if(vyobs==0)scaley=0;
+						dux=scalex*(vxobs-vx);
+						duy=scaley*(vyobs-vy);
+						pe->values[i*NDOF4+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF4+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceLogVelMisfitEnum:
+					/*
+					 *                 [        vel + eps     ] 2
+					 * J = 4 \bar{v}^2 | log ( -----------  ) |  
+					 *                 [       vel   + eps    ]
+					 *                            obs
+					 *
+					 *        dJ                 2 * log(...)
+					 * DU = - -- = - 4 \bar{v}^2 -------------  u
+					 *        du                 vel^2 + eps
+					 *            
+					 */
+					for (i=0;i<NUMVERTICES;i++){
+						velocity_mag    =sqrt(pow(vx,   2.)+pow(vy,   2.))+epsvel;
+						obs_velocity_mag=sqrt(pow(vxobs,2.)+pow(vyobs,2.))+epsvel;
+						scale=-8*pow(meanvel,2.)/pow(velocity_mag,2.)*log(velocity_mag/obs_velocity_mag);
+						dux=scale*vx;
+						duy=scale*vy;
+						pe->values[i*NDOF4+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF4+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceAverageVelMisfitEnum:
+					/*
+					 *      1                    2              2
+					 * J = ---  sqrt(  (u - u   )  +  (v - v   )  )
+					 *      S                obs            obs
+					 *
+					 *        dJ      1       1 
+					 * DU = - -- = - --- ----------- * 2 (u - u   )
+					 *        du      S  2 sqrt(...)           obs
+					 */
+					for (i=0;i<NUMVERTICES;i++){
+						scale=1./(S*2*sqrt(pow(vx-vxobs,2.)+pow(vy-vyobs,2.))+epsvel);
+						dux=scale*(vxobs-vx);
+						duy=scale*(vyobs-vy);
+						pe->values[i*NDOF4+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF4+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceLogVxVyMisfitEnum:
+					/*
+					 *      1            [        |u| + eps     2          |v| + eps     2  ]
+					 * J = --- \bar{v}^2 | log ( -----------  )   +  log ( -----------  )   |  
+					 *      2            [       |u    |+ eps              |v    |+ eps     ]
+					 *                              obs                       obs
+					 *        dJ                              1      u                             1
+					 * DU = - -- = - \bar{v}^2 log(u...) --------- ----  ~ - \bar{v}^2 log(u...) ------
+					 *        du                         |u| + eps  |u|                           u + eps
+					 */
+					for (i=0;i<NUMVERTICES;i++){
+						dux = - pow(meanvel,2.) * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+						duy = - pow(meanvel,2.) * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
+						pe->values[i*NDOF4+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF4+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case DragCoefficientAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case RheologyBbarAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				default:
+					_error_("response %s not supported yet",EnumToStringx(responses[resp]));
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xfree((void**)&responses);
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::DragCoefficientAbsGradient{{{1*/
+double Tria::DragCoefficientAbsGradient(bool process_units,int weight_index){
+
+	/* Intermediaries */
+	int        ig;
+	double     Jelem = 0;
+	double     weight;
+	double     Jdet;
+	double     xyz_list[NUMVERTICES][3];
+	double     dp[NDOF2];
+	GaussTria *gauss = NULL;
+
+	/*retrieve parameters and inputs*/
+
+	/*If on water, return 0: */
+	if(IsOnWater()) return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);         _assert_(weights_input);
+	Input* drag_input   =inputs->GetInput(FrictionCoefficientEnum); _assert_(drag_input);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,weight_index);
+		drag_input->GetInputDerivativeValue(&dp[0],&xyz_list[0][0],gauss);
+
+		/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
+		//Jelem+=weight*1/2*(pow(dp[0],2.)+pow(dp[1],2.))*Jdet*gauss->weight;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixAdjointBalancethickness {{{1*/
+ElementMatrix* Tria::CreateKMatrixAdjointBalancethickness(void){
+
+	ElementMatrix* Ke=NULL;
+
+	/*Get Element Matrix of the forward model*/
+	switch(GetElementType()){
+		case P1Enum:
+			Ke=CreateKMatrixBalancethickness_CG();
+			break;
+		case P1DGEnum:
+			Ke=CreateKMatrixBalancethickness_DG();
+			break;
+		default:
+			_error_("Element type %s not supported yet",EnumToStringx(GetElementType()));
+	}
+
+	/*Transpose and return Ke*/
+	Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionAdjointHoriz {{{1*/
+void  Tria::InputUpdateFromSolutionAdjointHoriz(double* solution){
+
+	const int numdof=NDOF2*NUMVERTICES;
+
+	int       i;
+	int*      doflist=NULL;
+	double    values[numdof];
+	double    lambdax[NUMVERTICES];
+	double    lambday[NUMVERTICES];
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		lambdax[i]=values[i*NDOF2+0];
+		lambday[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(isnan(lambdax[i])) _error_("NaN found in solution vector");
+		if(isnan(lambday[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new TriaP1Input(AdjointxEnum,lambdax));
+	this->inputs->AddInput(new TriaP1Input(AdjointyEnum,lambday));
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionAdjointBalancethickness {{{1*/
+void  Tria::InputUpdateFromSolutionAdjointBalancethickness(double* solution){
+
+	const int numdof=NDOF1*NUMVERTICES;
+
+	int       i;
+	int*      doflist=NULL;
+	double    values[numdof];
+	double    lambda[NUMVERTICES];
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<numdof;i++){
+		lambda[i]=values[i];
+		if(isnan(lambda[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new TriaP1Input(AdjointEnum,lambda));
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_HYDROLOGY_
+/*FUNCTION Tria::CreateHydrologyWaterVelocityInput {{{1*/
+void Tria::CreateHydrologyWaterVelocityInput(void){
+
+	/*material parameters: */
+	double mu_water;
+	double VelocityFactor;  // This factor represents the number 12 in laminar flow velocity which can vary by differnt hydrology.CR
+	double n_man,CR;
+	double w;
+	double rho_ice, rho_water, g;
+	double dsdx,dsdy,dbdx,dbdy;
+	double vx[NUMVERTICES];
+	double vy[NUMVERTICES];
+	GaussTria *gauss = NULL;
+
+	/*Retrieve all inputs and parameters*/
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+	g=matpar->GetG();
+	CR=matpar->GetHydrologyCR(); // To have Lebrocq equavalent equation: CR=0.01,n_man=0.02
+	n_man=matpar->GetHydrologyN(); 
+	mu_water=matpar->GetMuWater();
+	Input* surfaceslopex_input=inputs->GetInput(SurfaceSlopeXEnum); _assert_(surfaceslopex_input);
+	Input* surfaceslopey_input=inputs->GetInput(SurfaceSlopeYEnum); _assert_(surfaceslopey_input);
+	Input* bedslopex_input=inputs->GetInput(BedSlopeXEnum);         _assert_(bedslopex_input);
+	Input* bedslopey_input=inputs->GetInput(BedSlopeYEnum);         _assert_(bedslopey_input);
+	Input* watercolumn_input=inputs->GetInput(WatercolumnEnum);     _assert_(watercolumn_input);
+
+	/* compute VelocityFactor */
+	VelocityFactor= n_man*pow(CR,2)*rho_water*g/mu_water;
+	
+	gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+		surfaceslopex_input->GetInputValue(&dsdx,gauss);
+		surfaceslopey_input->GetInputValue(&dsdy,gauss);
+		bedslopex_input->GetInputValue(&dbdx,gauss);
+		bedslopey_input->GetInputValue(&dbdy,gauss);
+		watercolumn_input->GetInputValue(&w,gauss);
+
+		/* Water velocity x and y components */
+	//	vx[iv]= - pow(w,2)/(12 * mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
+	//	vy[iv]= - pow(w,2)/(12 * mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
+	
+		vx[iv]= - pow(w,2)/(VelocityFactor* mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
+		vy[iv]= - pow(w,2)/(VelocityFactor* mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
+	}
+
+	/*clean-up*/
+	delete gauss;
+
+	/*Add to inputs*/
+	this->inputs->AddInput(new TriaP1Input(HydrologyWaterVxEnum,vx));
+	this->inputs->AddInput(new TriaP1Input(HydrologyWaterVyEnum,vy));
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixHydrology{{{1*/
+ElementMatrix* Tria::CreateKMatrixHydrology(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	double     diffusivity;
+	int        i,j,ig;
+	double     Jdettria,DL_scalar,dt,h;
+	double     vx,vy,vel,dvxdx,dvydy;
+	double     dvx[2],dvy[2];
+	double     v_gauss[2]={0.0};
+	double     xyz_list[NUMVERTICES][3];
+	double     L[NUMVERTICES];
+	double     B[2][NUMVERTICES];
+	double     Bprime[2][NUMVERTICES];
+	double     K[2][2]                        ={0.0};
+	double     KDL[2][2]                      ={0.0};
+	double     DL[2][2]                        ={0.0};
+	double     DLprime[2][2]                   ={0.0};
+	GaussTria *gauss=NULL;
+
+	/*Skip if water or ice shelf element*/
+	if(IsOnWater() | IsFloating()) return NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Create water velocity vx and vy from current inputs*/
+	CreateHydrologyWaterVelocityInput();
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&diffusivity,HydrologyStabilizationEnum);
+	Input* vx_input=inputs->GetInput(HydrologyWaterVxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(HydrologyWaterVyEnum); _assert_(vy_input);
+	h=sqrt(2*this->GetArea());
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
+
+		DL_scalar=gauss->weight*Jdettria;
+
+		TripleMultiply( &L[0],1,numdof,1,
+					&DL_scalar,1,1,0,
+					&L[0],1,numdof,0,
+					&Ke->values[0],1);
+
+		GetBPrognostic(&B[0][0], &xyz_list[0][0], gauss);
+		GetBprimePrognostic(&Bprime[0][0], &xyz_list[0][0], gauss);
+
+		dvxdx=dvx[0];
+		dvydy=dvy[1];
+		DL_scalar=dt*gauss->weight*Jdettria;
+
+		DL[0][0]=DL_scalar*dvxdx;
+		DL[1][1]=DL_scalar*dvydy;
+		DLprime[0][0]=DL_scalar*vx;
+		DLprime[1][1]=DL_scalar*vy;
+
+		TripleMultiply( &B[0][0],2,numdof,1,
+					&DL[0][0],2,2,0,
+					&B[0][0],2,numdof,0,
+					&Ke->values[0],1);
+
+		TripleMultiply( &B[0][0],2,numdof,1,
+					&DLprime[0][0],2,2,0,
+					&Bprime[0][0],2,numdof,0,
+					&Ke->values[0],1);
+
+		/*Artificial diffusivity*/
+		vel=sqrt(pow(vx,2.)+pow(vy,2.));
+		K[0][0]=diffusivity*h/(2*vel)*vx*vx;
+		K[1][0]=diffusivity*h/(2*vel)*vy*vx;
+		K[0][1]=diffusivity*h/(2*vel)*vx*vy;
+		K[1][1]=diffusivity*h/(2*vel)*vy*vy;
+		KDL[0][0]=DL_scalar*K[0][0];
+		KDL[1][0]=DL_scalar*K[1][0];
+		KDL[0][1]=DL_scalar*K[0][1];
+		KDL[1][1]=DL_scalar*K[1][1];
+
+		TripleMultiply( &Bprime[0][0],2,numdof,1,
+					&KDL[0][0],2,2,0,
+					&Bprime[0][0],2,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorHydrology {{{1*/
+ElementVector* Tria::CreatePVectorHydrology(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	double     Jdettria,dt;
+	double     basal_melting_g;
+	double     old_watercolumn_g;
+	double     xyz_list[NUMVERTICES][3];
+	double     basis[numdof];
+	GaussTria* gauss=NULL;
+
+	/*Skip if water or ice shelf element*/
+	if(IsOnWater() | IsFloating()) return NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* basal_melting_input=inputs->GetInput(BasalforcingsMeltingRateEnum); _assert_(basal_melting_input);
+	Input* old_watercolumn_input=inputs->GetInput(WaterColumnOldEnum);         _assert_(old_watercolumn_input);
+
+	/*Initialize basal_melting_correction_g to 0, do not forget!:*/
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+
+		basal_melting_input->GetInputValue(&basal_melting_g,gauss);
+		old_watercolumn_input->GetInputValue(&old_watercolumn_g,gauss);
+
+		if(dt)for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(old_watercolumn_g+dt*basal_melting_g)*basis[i];
+		else  for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*basal_melting_g*basis[i];
+	}
+		
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::GetSolutionFromInputsHydrology{{{1*/
+void  Tria::GetSolutionFromInputsHydrology(Vec solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int i;
+	int*         doflist=NULL;
+	double       watercolumn;
+	double       values[numdof];
+	GaussTria*   gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Get inputs*/
+	Input* watercolumn_input=inputs->GetInput(WatercolumnEnum); _assert_(watercolumn_input);
+
+	/*Ok, we have watercolumn values, fill in watercolumn array: */
+	/*P1 element only for now*/
+	gauss=new GaussTria();
+	for(i=0;i<NUMVERTICES;i++){
+
+		gauss->GaussVertex(i);
+
+		/*Recover watercolumn*/
+		watercolumn_input->GetInputValue(&watercolumn,gauss);
+		values[i]=watercolumn;
+	}
+
+	VecSetValues(solution,numdof,doflist,(const double*)values,INSERT_VALUES);
+
+	/*Free ressources:*/
+	delete gauss;
+	xfree((void**)&doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionHydrology{{{1*/
+void  Tria::InputUpdateFromSolutionHydrology(double* solution){
+
+	/*Intermediaries*/
+	const int numdof = NDOF1*NUMVERTICES;
+
+	int       i;
+	int*      doflist=NULL;
+	double    values[numdof];
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+		if(isnan(values[i])) _error_("NaN found in solution vector");
+		if (values[i]<pow((double)10,(double)-10))values[i]=pow((double)10,(double)-10); //correcting the water column to positive values
+ 
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new TriaP1Input(WatercolumnEnum,values));
+
+	/*Free ressources:*/
+	xfree((void**)&doflist);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_DAKOTA_
+/*FUNCTION Tria::InputUpdateFromVectorDakota(double* vector, int name, int type);{{{1*/
+void  Tria::InputUpdateFromVectorDakota(double* vector, int name, int type){
+	
+	int i,j;
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			/*New TriaP1Input*/
+			double values[3];
+
+			/*Get values on the 3 vertices*/
+			for (i=0;i<3;i++){
+				values[i]=vector[this->nodes[i]->GetSidList()]; //careful, vector of values here is not parallel distributed, but serial distributed (from a serial Dakota core!)
+			}
+
+			/*Branch on the specified type of update: */
+			switch(name){
+				case ThicknessEnum:
+					/*Update thickness + surface: assume bed is constant. On ice shelves, takes hydrostatic equilibrium {{{2*/
+					double  thickness[3];
+					double  thickness_init[3];
+					double  hydrostatic_ratio[3];
+					double  surface[3];
+					double  bed[3];
+					
+					/*retrieve inputs: */
+					GetInputListOnVertices(&thickness_init[0],ThicknessEnum);
+					GetInputListOnVertices(&hydrostatic_ratio[0],GeometryHydrostaticRatioEnum);
+					GetInputListOnVertices(&bed[0],BedEnum);
+					GetInputListOnVertices(&surface[0],SurfaceEnum);
+
+					/*build new thickness: */
+//					for(j=0;j<3;j++)thickness[j]=values[j];
+
+					/*build new bed and surface: */
+					if (this->IsFloating()){
+						/*hydrostatic equilibrium: */
+						double 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];
+						}
+
+//						for(j=0;j<3;j++){
+//							surface[j]=(1-di)*thickness[j];
+//							bed[j]=-di*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++)surface[j]=bed[j]+thickness[j];
+						for(j=0;j<3;j++)bed[j]=surface[j]-thickness[j];
+					}
+
+					/*Add new inputs: */
+					this->inputs->AddInput(new TriaP1Input(ThicknessEnum,thickness));
+					this->inputs->AddInput(new TriaP1Input(BedEnum,bed));
+					this->inputs->AddInput(new TriaP1Input(SurfaceEnum,surface));
+
+					/*}}}*/
+					break;
+				default:
+					this->inputs->AddInput(new TriaP1Input(name,values));
+			}
+			break;
+
+		default:
+			_error_("type %i (%s) not implemented yet",type,EnumToStringx(type));
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromVectorDakota(int* vector, int name, int type);{{{1*/
+void  Tria::InputUpdateFromVectorDakota(int* vector, int name, int type){
+	_error_(" not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromVectorDakota(bool* vector, int name, int type);{{{1*/
+void  Tria::InputUpdateFromVectorDakota(bool* vector, int name, int type){
+	_error_(" not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromMatrixDakota(double* matrix, int nrows, int ncols, int name, int type);{{{1*/
+void  Tria::InputUpdateFromMatrixDakota(double* matrix, int nrows, int ncols, int name, int type){
+	
+	int i,j,t;
+	TransientInput* transientinput=NULL;
+	double values[3];
+	double time;
+	int row;
+	double yts;
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+			
+			/*Create transient input: */
+						
+			parameters->FindParam(&yts,ConstantsYtsEnum);
+			for(t=0;t<ncols;t++){ //ncols is the number of times
+
+				/*create input values: */
+				for(i=0;i<3;i++){
+					row=this->nodes[i]->GetSidList();
+					values[i]=(double)matrix[ncols*row+t];
+				}
+
+				/*time? :*/
+				time=(double)matrix[(nrows-1)*ncols+t]*yts;
+
+				if(t==0) transientinput=new TransientInput(name);
+				transientinput->AddTimeInput(new TriaP1Input(name,values),time);
+				transientinput->Configure(parameters);
+			}
+			this->inputs->AddInput(transientinput);
+			break;
+
+		default:
+			_error_("type %i (%s) not implemented yet",type,EnumToStringx(type));
+	}
+
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_BALANCED_
+/*FUNCTION Tria::CreateKMatrixBalancethickness {{{1*/
+ElementMatrix* Tria::CreateKMatrixBalancethickness(void){
+
+	switch(GetElementType()){
+		case P1Enum:
+			return CreateKMatrixBalancethickness_CG();
+		case P1DGEnum:
+			return CreateKMatrixBalancethickness_DG();
+		default:
+			_error_("Element type %s not supported yet",EnumToStringx(GetElementType()));
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixBalancethickness_CG {{{1*/
+ElementMatrix* Tria::CreateKMatrixBalancethickness_CG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        stabilization;
+	int        i,j,ig,dim;
+	double     Jdettria,vx,vy,dvxdx,dvydy,vel,h;
+	double     dvx[2],dvy[2];
+	double     xyz_list[NUMVERTICES][3];
+	double     L[NUMVERTICES];
+	double     B[2][NUMVERTICES];
+	double     Bprime[2][NUMVERTICES];
+	double     K[2][2]                          = {0.0};
+	double     KDL[2][2]                        = {0.0};
+	double     DL[2][2]                         = {0.0};
+	double     DLprime[2][2]                    = {0.0};
+	double     DL_scalar;
+	GaussTria *gauss                            = NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all Inputs and parameters: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&stabilization,BalancethicknessStabilizationEnum);
+	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	Input* vxaverage_input=NULL;
+	Input* vyaverage_input=NULL;
+	if(dim==2){
+		vxaverage_input=inputs->GetInput(VxEnum); _assert_(vxaverage_input);
+		vyaverage_input=inputs->GetInput(VyEnum); _assert_(vyaverage_input);
+	}
+	else{
+		vxaverage_input=inputs->GetInput(VxAverageEnum); _assert_(vxaverage_input);
+		vyaverage_input=inputs->GetInput(VyAverageEnum); _assert_(vyaverage_input);
+	}
+	h=sqrt(2*this->GetArea());
+
+	/*Start looping on the number of gaussian points:*/
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetBPrognostic(&B[0][0], &xyz_list[0][0], gauss);
+		GetBprimePrognostic(&Bprime[0][0], &xyz_list[0][0], gauss);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		vxaverage_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
+		vyaverage_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
+
+		dvxdx=dvx[0];
+		dvydy=dvy[1];
+		DL_scalar=gauss->weight*Jdettria;
+
+		DL[0][0]=DL_scalar*dvxdx;
+		DL[1][1]=DL_scalar*dvydy;
+
+		DLprime[0][0]=DL_scalar*vx;
+		DLprime[1][1]=DL_scalar*vy;
+
+		TripleMultiply( &B[0][0],2,numdof,1,
+					&DL[0][0],2,2,0,
+					&B[0][0],2,numdof,0,
+					&Ke->values[0],1);
+
+		TripleMultiply( &B[0][0],2,numdof,1,
+					&DLprime[0][0],2,2,0,
+					&Bprime[0][0],2,numdof,0,
+					&Ke->values[0],1);
+
+		if(stabilization==1){
+			/*Streamline upwinding*/
+			vel=sqrt(pow(vx,2.)+pow(vy,2.));
+			K[0][0]=h/(2*vel)*vx*vx;
+			K[1][0]=h/(2*vel)*vy*vx;
+			K[0][1]=h/(2*vel)*vx*vy;
+			K[1][1]=h/(2*vel)*vy*vy;
+		}
+		else if(stabilization==2){
+			/*MacAyeal*/
+			vxaverage_input->GetInputAverage(&vx);
+			vyaverage_input->GetInputAverage(&vy);
+			K[0][0]=h/2.0*fabs(vx);
+			K[0][1]=0.;
+			K[1][0]=0.;
+			K[1][1]=h/2.0*fabs(vy);
+		}
+		if(stabilization==1 || stabilization==2){
+			KDL[0][0]=DL_scalar*K[0][0];
+			KDL[1][0]=DL_scalar*K[1][0];
+			KDL[0][1]=DL_scalar*K[0][1];
+			KDL[1][1]=DL_scalar*K[1][1];
+			TripleMultiply( &Bprime[0][0],2,numdof,1,
+						&KDL[0][0],2,2,0,
+						&Bprime[0][0],2,numdof,0,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixBalancethickness_DG {{{1*/
+ElementMatrix* Tria::CreateKMatrixBalancethickness_DG(void){
+
+	/*Constants*/
+	const int  numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries*/
+	int        i,j,ig,dim;
+	double     vx,vy,Jdettria;
+	double     xyz_list[NUMVERTICES][3];
+	double     B[2][NUMVERTICES];
+	double     Bprime[2][NUMVERTICES];
+	double     DL[2][2]={0.0};
+	double     DL_scalar;
+	GaussTria  *gauss=NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	this->parameters->FindParam(&dim,MeshDimensionEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+
+	/*Start looping on the number of gaussian points:*/
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		/*WARNING: B and Bprime are inverted compared to usual prognostic!!!!*/
+		GetBPrognostic(&Bprime[0][0], &xyz_list[0][0], gauss);
+		GetBprimePrognostic(&B[0][0], &xyz_list[0][0], gauss);
+
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+
+		DL_scalar=-gauss->weight*Jdettria;
+		DL[0][0]=DL_scalar*vx;
+		DL[1][1]=DL_scalar*vy;
+
+		TripleMultiply( &B[0][0],2,numdof,1,
+					&DL[0][0],2,2,0,
+					&Bprime[0][0],2,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorBalancethickness{{{1*/
+ElementVector* Tria::CreatePVectorBalancethickness(void){
+
+	switch(GetElementType()){
+		case P1Enum:
+			return CreatePVectorBalancethickness_CG();
+			break;
+		case P1DGEnum:
+			return CreatePVectorBalancethickness_DG();
+		default:
+			_error_("Element type %s not supported yet",EnumToStringx(GetElementType()));
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorBalancethickness_CG{{{1*/
+ElementVector* Tria::CreatePVectorBalancethickness_CG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+	
+	/*Intermediaries */
+	int        i,j,ig;
+	double     xyz_list[NUMVERTICES][3];
+	double     dhdt_g,basal_melting_g,surface_mass_balance_g,Jdettria;
+	double     L[NUMVERTICES];
+	GaussTria* gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* surface_mass_balance_input=inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(surface_mass_balance_input);
+	Input* basal_melting_input=inputs->GetInput(BasalforcingsMeltingRateEnum);          _assert_(basal_melting_input);
+	Input* dhdt_input=inputs->GetInput(BalancethicknessThickeningRateEnum);             _assert_(dhdt_input);
+	
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		surface_mass_balance_input->GetInputValue(&surface_mass_balance_g,gauss);
+		basal_melting_input->GetInputValue(&basal_melting_g,gauss);
+		dhdt_input->GetInputValue(&dhdt_g,gauss);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(surface_mass_balance_g-basal_melting_g-dhdt_g)*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorBalancethickness_DG {{{1*/
+ElementVector* Tria::CreatePVectorBalancethickness_DG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	double     xyz_list[NUMVERTICES][3];
+	double     basal_melting_g,surface_mass_balance_g,dhdt_g,Jdettria;
+	double     L[NUMVERTICES];
+	GaussTria* gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* surface_mass_balance_input=inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(surface_mass_balance_input);
+	Input* basal_melting_input=inputs->GetInput(BasalforcingsMeltingRateEnum);          _assert_(basal_melting_input);
+	Input* dhdt_input=inputs->GetInput(BalancethicknessThickeningRateEnum);                                       _assert_(dhdt_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		surface_mass_balance_input->GetInputValue(&surface_mass_balance_g,gauss);
+		basal_melting_input->GetInputValue(&basal_melting_g,gauss);
+		dhdt_input->GetInputValue(&dhdt_g,gauss);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(surface_mass_balance_g-basal_melting_g-dhdt_g)*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Elements/Tria.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Elements/Tria.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Elements/Tria.h	(revision 11330)
@@ -0,0 +1,234 @@
+/*! \file Tria.h 
+ *  \brief: header file for tria object
+ */
+
+#ifndef _TRIA_H_
+#define _TRIA_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Element.h"
+#include "./TriaHook.h"
+#include "./TriaRef.h"
+class Parameters;
+class Inputs;
+class IoModel;
+class Node;
+class Matice;
+class Matpar;
+class ElementMatrix;
+class ElementVector;
+
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+/*}}}*/
+
+class Tria: public Element,public TriaHook,public TriaRef{
+
+	public:
+
+		int  id;
+		int  sid;
+
+		Node   **nodes;    // 3 nodes
+		Matice  *matice;   // 1 material ice
+		Matpar  *matpar;   // 1 material parameter
+		int      horizontalneighborsids[3];
+
+		Parameters *parameters;   //pointer to solution parameters
+		Inputs     *inputs;
+		Results    *results;
+
+		/*Tria constructors, destructors {{{1*/
+		Tria();
+		Tria(int tria_id,int tria_sid,int i, IoModel* iomodel,int nummodels);
+		~Tria();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{1*/
+		void  InputUpdateFromSolution(double* solutiong);
+		void  InputUpdateFromVector(double* vector, int name, int type);
+		void  InputUpdateFromVector(int* vector, int name, int type);
+		void  InputUpdateFromVector(bool* vector, int name, int type);
+		#ifdef _HAVE_DAKOTA_
+		void  InputUpdateFromVectorDakota(double* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
+		void  InputUpdateFromMatrixDakota(double* matrix, int nows, int ncols, int name, int type);
+		#endif
+		void  InputUpdateFromConstant(double constant, int name);
+		void  InputUpdateFromConstant(int constant, int name);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
+		/*}}}*/
+		/*Element virtual functions definitions: {{{1*/
+		void   AverageOntoPartition(Vec partition_contributions,Vec partition_areas,double* vertex_response,double* qmu_part);
+		void   ComputeBasalStress(Vec sigma_b);
+		void   ComputeStrainRate(Vec eps);
+		void   ComputeStressTensor();
+		void   Configure(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters);
+		void   SetCurrentConfiguration(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters);
+		void   CreateKMatrix(Mat Kff, Mat Kfs,Vec df);
+		void   CreatePVector(Vec pf);
+		int    GetNodeIndex(Node* node);
+		int    Sid();
+		bool   IsOnBed();
+		bool   IsFloating(); 
+		bool   IsNodeOnShelf(); 
+		bool   IsNodeOnShelfFromFlags(double* flags);
+		bool   IsOnWater(); 
+		void   GetSolutionFromInputs(Vec solution);
+		void   GetVectorFromInputs(Vec vector, int name_enum);
+		void   GetVectorFromResults(Vec vector,int offset,int interp);
+		void   InputArtificialNoise(int enum_type,double min, double max);
+		bool   InputConvergence(double* eps, int* enums,int num_enums,int* criterionenums,double* criterionvalues,int num_criterionenums);
+		void   InputCreate(double scalar,int name,int code);
+		void   InputCreate(double* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code);
+		void   InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum=MeshElementsEnum);
+		void   InputDuplicate(int original_enum,int new_enum);
+		void   InputScale(int enum_type,double scale_factor);
+		void   InputToResult(int enum_type,int step,double time);
+		void   DeleteResults(void);
+		void   MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
+		void   MigrateGroundingLine(double* oldfloating,double* sheet_ungrounding);
+		void   PotentialSheetUngrounding(Vec potential_sheet_ungrounding);
+		void   RequestedOutput(int output_enum,int step,double time);
+		void   ListResultsInfo(int** results_enums,int** results_size,double** results_times,int** results_steps,int* num_results);
+		void   PatchFill(int* pcount, Patch* patch);
+		void   PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes);
+		void   ProcessResultsUnits(void);
+		void   ResetCoordinateSystem(void){_error_("not implemented yet");};
+		double SurfaceArea(void);
+		void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type);
+		int    UpdatePotentialSheetUngrounding(double* vertices_potentially_ungrounding,Vec vec_nodes_on_iceshelf,double* nodes_on_iceshelf);
+		double TimeAdapt();
+		int*   GetHorizontalNeighboorSids(void);
+		void   SmearFunction(Vec smearedvector,double (*WeightFunction)(double distance,double radius),double radius);
+
+		#ifdef _HAVE_RESPONSES_
+		double IceVolume(void);
+		void   MinVel(double* pminvel, bool process_units);
+		void   MinVx(double* pminvx, bool process_units);
+		void   MinVy(double* pminvy, bool process_units);
+		void   MinVz(double* pminvz, bool process_units);
+		int    NodalValue(double* pvalue, int index, int natureofdataenum,bool process_units);
+		double MassFlux(double* segment,bool process_units);
+		void   MaxAbsVx(double* pmaxabsvx, bool process_units);
+		void   MaxAbsVy(double* pmaxabsvy, bool process_units);
+		void   MaxAbsVz(double* pmaxabsvz, bool process_units);
+		void   ElementResponse(double* presponse,int response_enum,bool process_units);
+		void   MaxVel(double* pmaxvel, bool process_units);
+		void   MaxVx(double* pmaxvx, bool process_units);
+		void   MaxVy(double* pmaxvy, bool process_units);
+		void   MaxVz(double* pmaxvz, bool process_units);
+		#endif
+
+
+		#ifdef _HAVE_CONTROL_
+		double DragCoefficientAbsGradient(bool process_units,int weight_index);
+		void   Gradj(Vec gradient,int control_type);
+		void   GradjBGradient(Vec gradient,int weight_index);
+		void   GradjBMacAyeal(Vec gradient);
+		void   GradjDragMacAyeal(Vec gradient);
+		void   GradjDragStokes(Vec gradient);
+		void   GradjDragGradient(Vec gradient,int weight_index);
+		void   GradjDhDtBalancedthickness(Vec gradient);
+		void   GradjVxBalancedthickness(Vec gradient);
+		void   GradjVyBalancedthickness(Vec gradient);
+		void   ControlInputGetGradient(Vec gradient,int enum_type);
+		void   ControlInputScaleGradient(int enum_type,double scale);
+		void   ControlInputSetGradient(double* gradient,int enum_type);
+		double RheologyBbarAbsGradient(bool process_units,int weight_index);
+		double ThicknessAbsMisfit(     bool process_units,int weight_index);
+		double SurfaceAbsVelMisfit(    bool process_units,int weight_index);
+		double ThicknessAbsGradient(bool process_units,int weight_index);
+		double SurfaceRelVelMisfit(    bool process_units,int weight_index);
+		double SurfaceLogVelMisfit(    bool process_units,int weight_index);
+		double SurfaceLogVxVyMisfit(   bool process_units,int weight_index);
+		double SurfaceAverageVelMisfit(bool process_units,int weight_index);
+		void   InputControlUpdate(double scalar,bool save_parameter);
+		#endif
+
+		/*}}}*/
+		/*Tria specific routines:{{{1*/
+		ElementMatrix* CreateKMatrixBalancethickness(void);
+		ElementMatrix* CreateKMatrixBalancethickness_DG(void);
+		ElementMatrix* CreateKMatrixBalancethickness_CG(void);
+		ElementMatrix* CreateKMatrixMelting(void);
+		ElementMatrix* CreateKMatrixPrognostic(void);
+		ElementMatrix* CreateKMatrixPrognostic_CG(void);
+		ElementMatrix* CreateKMatrixPrognostic_DG(void);
+		ElementMatrix* CreateKMatrixSlope(void);
+		ElementVector* CreatePVectorBalancethickness(void);
+		ElementVector* CreatePVectorBalancethickness_DG(void);
+		ElementVector* CreatePVectorBalancethickness_CG(void);
+		ElementVector* CreatePVectorPrognostic(void);
+		ElementVector* CreatePVectorPrognostic_CG(void);
+		ElementVector* CreatePVectorPrognostic_DG(void);
+		ElementVector* CreatePVectorSlope(void);
+		double         GetArea(void);
+		int            GetElementType(void);
+		void	         GetDofList(int** pdoflist,int approximation_enum,int setenum);
+		void	         GetDofList1(int* doflist);
+		void           GetSidList(int* sidlist);
+		void           GetConnectivityList(int* connectivity);
+		void           GetInputListOnVertices(double* pvalue,int enumtype);
+		void           GetInputListOnVertices(double* pvalue,int enumtype,double defaultvalue);
+		void           GetInputListOnVertices(double* pvalue,int enumtype,double defaultvalue,int index); //TO BE REMOVED
+		void           GetInputValue(double* pvalue,Node* node,int enumtype);
+		void           GetStrainRate2d(double* epsilon,double* xyz_list, GaussTria* gauss, Input* vx_input, Input* vy_input);
+		void	         InputUpdateFromSolutionOneDof(double* solution,int enum_type);
+		void	         InputUpdateFromSolutionPrognostic(double* solution);
+		bool	         IsInput(int name);
+		void	         SetClone(int* minranks);
+		void	         SurfaceNormal(double* surface_normal, double xyz_list[3][3]);
+		
+		#ifdef _HAVE_DIAGNOSTIC_
+		ElementMatrix* CreateKMatrixDiagnosticMacAyeal(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyealViscous(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyealFriction(void);
+		ElementMatrix* CreateKMatrixDiagnosticHutter(void);
+		ElementVector* CreatePVectorDiagnosticMacAyeal(void);
+		ElementVector* CreatePVectorDiagnosticHutter(void);
+		void	  GetSolutionFromInputsDiagnosticHoriz(Vec solution);
+		void	  GetSolutionFromInputsDiagnosticHutter(Vec solution);
+		void	  InputUpdateFromSolutionDiagnosticHoriz( double* solution);
+		void	  InputUpdateFromSolutionDiagnosticHutter( double* solution);
+		#endif
+
+		#ifdef _HAVE_CONTROL_
+		ElementMatrix* CreateKMatrixAdjointBalancethickness(void);
+		ElementVector* CreatePVectorAdjointHoriz(void);
+		ElementVector* CreatePVectorAdjointStokes(void);
+		ElementVector* CreatePVectorAdjointBalancethickness(void);
+		void	  InputUpdateFromSolutionAdjointBalancethickness( double* solution);
+		void	  InputUpdateFromSolutionAdjointHoriz( double* solution);
+		#endif
+
+		#ifdef _HAVE_HYDROLOGY_
+		ElementMatrix* CreateKMatrixHydrology(void);
+		ElementVector* CreatePVectorHydrology(void);
+		void      CreateHydrologyWaterVelocityInput(void);
+		void	  GetSolutionFromInputsHydrology(Vec solution);
+		void	  InputUpdateFromSolutionHydrology(double* solution);
+		#endif
+		#ifdef _HAVE_BALANCED_
+		#endif
+
+		/*}}}*/
+
+};
+#endif  /* _TRIA_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Elements/TriaHook.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Elements/TriaHook.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Elements/TriaHook.cpp	(revision 11330)
@@ -0,0 +1,72 @@
+/*!\file TriaHook.c
+ * \brief: implementation of the TriaHook object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION TriaHook::TriaHook(){{{1*/
+TriaHook::TriaHook(){
+	numanalyses=UNDEF;
+	this->hnodes=NULL;
+	this->hmatice=NULL;
+	this->hmatpar=NULL;
+}
+/*}}}*/
+/*FUNCTION TriaHook::~TriaHook(){{{1*/
+TriaHook::~TriaHook(){
+	int i;
+
+	for(i=0;i<this->numanalyses;i++){
+		if (this->hnodes[i]) delete this->hnodes[i];
+	}
+	delete [] this->hnodes;
+	delete hmatice;
+	delete hmatpar;
+
+}
+/*}}}*/
+/*FUNCTION TriaHook::TriaHook(int in_numanalyses,int matice_id, int matpar_id){{{1*/
+TriaHook::TriaHook(int in_numanalyses,int matice_id, IoModel* iomodel){
+
+	/*intermediary: */
+	int matpar_id;
+
+	/*retrieve parameters: */
+	iomodel->Constant(&matpar_id,MeshNumberofelementsEnum); matpar_id++;
+	
+	this->numanalyses=in_numanalyses;
+	this->hnodes= new Hook*[in_numanalyses];
+	this->hmatice=new Hook(&matice_id,1);
+	this->hmatpar=new Hook(&matpar_id,1);
+
+	//Initialize hnodes as NULL
+	for(int i=0;i<this->numanalyses;i++){
+		this->hnodes[i]=NULL;
+	}
+
+}
+/*}}}*/
+
+/*FUNCTION TriaHook::SetHookNodes{{{1*/
+void TriaHook::SetHookNodes(int* node_ids,int analysis_counter){
+
+	/*initialize hook*/
+	this->hnodes[analysis_counter]=new Hook(node_ids,3);
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Elements/TriaHook.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Elements/TriaHook.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Elements/TriaHook.h	(revision 11330)
@@ -0,0 +1,31 @@
+/*!\file: TriaHook.h
+ * \brief prototypes for TriaHook.h
+ */ 
+
+#ifndef _TRIAHOOK_H_
+#define  _TRIAHOOK_H_
+
+class Hook;
+class IoModel;
+
+class TriaHook{
+
+	public: 
+		int    numanalyses; //number of analysis types
+		Hook** hnodes; // 3 nodes for each analysis type
+		Hook*  hmatice; // 1 ice material
+		Hook*  hmatpar; // 1 material parameter
+
+
+		/*FUNCTION constructors, destructors {{{1*/
+		TriaHook();
+		TriaHook(int in_numanalyses,int matice_id, IoModel* iomodel);
+		~TriaHook();
+		void SetHookNodes(int* node_ids,int analysis_counter);
+		/*}}}*/
+
+};
+
+
+#endif //ifndef _TRIAHOOK_H_
+
Index: /issm/trunk-jpl-damage/src/c/objects/Elements/TriaRef.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Elements/TriaRef.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Elements/TriaRef.cpp	(revision 11330)
@@ -0,0 +1,503 @@
+/*!\file TriaRef.c
+ * \brief: implementation of the TriaRef object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMNODES 3
+
+/*Object constructors and destructor*/
+/*FUNCTION TriaRef::TriaRef(){{{1*/
+TriaRef::TriaRef(){
+	this->element_type_list=NULL;
+}
+/*}}}*/
+/*FUNCTION TriaRef::TriaRef(int* types,int nummodels){{{1*/
+
+TriaRef::TriaRef(const int nummodels){
+
+	/*Only allocate pointer*/
+	element_type_list=(int*)xmalloc(nummodels*sizeof(int));
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::~TriaRef(){{{1*/
+TriaRef::~TriaRef(){
+	xfree((void**)&element_type_list);
+}
+/*}}}*/
+
+/*Management*/
+/*FUNCTION TriaRef::SetElementType{{{1*/
+void TriaRef::SetElementType(int type,int type_counter){
+
+	_assert_(type==P1Enum || type==P1DGEnum);
+
+	/*initialize element type*/
+	this->element_type_list[type_counter]=type;
+}
+/*}}}*/
+
+/*Reference Element numerics*/
+/*FUNCTION TriaRef::GetBMacAyeal {{{1*/
+void TriaRef::GetBMacAyeal(double* B, double* xyz_list, GaussTria* gauss){
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ dh/dx           0    ]
+	 *          [   0           dh/dy  ]
+	 *          [ 1/2*dh/dy  1/2*dh/dx ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF2*NUMNODES)
+	 */
+
+	int i;
+	double dbasis[NDOF2][NUMNODES];
+
+	/*Get dh1dh2dh3 in actual coordinate system: */
+	GetNodalFunctionsDerivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build B: */
+	for (i=0;i<NUMNODES;i++){
+		*(B+NDOF2*NUMNODES*0+NDOF2*i)=dbasis[0][i]; //B[0][NDOF2*i]=dbasis[0][i];
+		*(B+NDOF2*NUMNODES*0+NDOF2*i+1)=0;
+		*(B+NDOF2*NUMNODES*1+NDOF2*i)=0;
+		*(B+NDOF2*NUMNODES*1+NDOF2*i+1)=dbasis[1][i];
+		*(B+NDOF2*NUMNODES*2+NDOF2*i)=(float).5*dbasis[1][i]; 
+		*(B+NDOF2*NUMNODES*2+NDOF2*i+1)=(float).5*dbasis[0][i]; 
+	}
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBMacAyealStokes {{{1*/
+void TriaRef::GetBMacAyealStokes(double* B, double* xyz_list, GaussTria* gauss){
+
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[   dh/dx         0     ]
+	 *          [       0       dh/dy   ]
+	 *          [  1/2*dh/dy  1/2*dh/dx ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF2*NUMNODES)
+	 */
+
+	/*Same thing in the actual coordinate system: */
+	double dbasis[NDOF2][NUMNODES];
+
+	/*Get dh1dh2dh3 in actual coordinates system : */
+	GetNodalFunctionsDerivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build B': */
+	for (int i=0;i<NUMNODES;i++){
+		*(B+NDOF2*NUMNODES*0+NDOF2*i)=dbasis[0][i]; 
+		*(B+NDOF2*NUMNODES*0+NDOF2*i+1)=0; 
+		*(B+NDOF2*NUMNODES*1+NDOF2*i)=0; 
+		*(B+NDOF2*NUMNODES*1+NDOF2*i+1)=dbasis[1][i]; 
+		*(B+NDOF2*NUMNODES*2+NDOF2*i)=0.5*dbasis[1][i]; 
+		*(B+NDOF2*NUMNODES*2+NDOF2*i+1)=0.5*dbasis[0][i]; 
+	}
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetSegmentBFlux{{{1*/
+void TriaRef::GetSegmentBFlux(double* B,GaussTria* gauss, int index1,int index2){
+	/*Compute B  matrix. B=[phi1 phi2 -phi3 -phi4]
+	 *
+	 * and phi1=phi3 phi2=phi4
+	 *
+	 * We assume B has been allocated already, of size: 1x4
+	 */
+
+	double l1l3[NUMNODES];
+
+	GetNodalFunctions(&l1l3[0],gauss);
+
+	B[0] = +l1l3[index1];
+	B[1] = +l1l3[index2];
+	B[2] = -l1l3[index1];
+	B[3] = -l1l3[index2];
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetSegmentBprimeFlux{{{1*/
+void TriaRef::GetSegmentBprimeFlux(double* Bprime,GaussTria* gauss, int index1,int index2){
+	/*Compute Bprime  matrix. Bprime=[phi1 phi2 phi3 phi4]
+	 *
+	 * and phi1=phi3 phi2=phi4
+	 *
+	 * We assume Bprime has been allocated already, of size: 1x4
+	 */
+
+	double l1l3[NUMNODES];
+
+	GetNodalFunctions(&l1l3[0],gauss);
+
+	Bprime[0] = l1l3[index1];
+	Bprime[1] = l1l3[index2];
+	Bprime[2] = l1l3[index1];
+	Bprime[3] = l1l3[index2];
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBPrognostic{{{1*/
+void TriaRef::GetBPrognostic(double* B_prog, double* xyz_list, GaussTria* gauss){
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ h ]
+	 *          [ h ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*NUMNODES)
+	 */
+
+	double basis[NUMNODES];
+
+	/*Get dh1dh2dh3 in actual coordinate system: */
+	GetNodalFunctions(&basis[0],gauss);
+
+	/*Build B_prog: */
+	for (int i=0;i<NUMNODES;i++){
+		*(B_prog+NDOF1*NUMNODES*0+NDOF1*i)=basis[i];
+		*(B_prog+NDOF1*NUMNODES*1+NDOF1*i)=basis[i];
+	}
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBprimeMacAyeal {{{1*/
+void TriaRef::GetBprimeMacAyeal(double* Bprime, double* xyz_list, GaussTria* gauss){
+
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ 2*dh/dx    dh/dy ]
+	 *                [   dh/dx  2*dh/dy ]
+	 *                [   dh/dy    dh/dx ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*NUMNODES)
+	 */
+
+	/*Same thing in the actual coordinate system: */
+	double dbasis[NDOF2][NUMNODES];
+
+	/*Get dh1dh2dh3 in actual coordinates system : */
+	GetNodalFunctionsDerivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build B': */
+	for (int i=0;i<NUMNODES;i++){
+		*(Bprime+NDOF2*NUMNODES*0+NDOF2*i)=2*dbasis[0][i]; 
+		*(Bprime+NDOF2*NUMNODES*0+NDOF2*i+1)=dbasis[1][i]; 
+		*(Bprime+NDOF2*NUMNODES*1+NDOF2*i)=dbasis[0][i]; 
+		*(Bprime+NDOF2*NUMNODES*1+NDOF2*i+1)=2*dbasis[1][i]; 
+		*(Bprime+NDOF2*NUMNODES*2+NDOF2*i)=dbasis[1][i]; 
+		*(Bprime+NDOF2*NUMNODES*2+NDOF2*i+1)=dbasis[0][i]; 
+	}
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBprimeMacAyealStokes {{{1*/
+void TriaRef::GetBprimeMacAyealStokes(double* Bprime, double* xyz_list, GaussTria* gauss){
+
+	/*Compute Bprime  matrix. Bprime=[Bprime1 Bprime2 Bprime3] where Bprimei is of size 3*NDOF2. 
+	 * For node i, Bprimei can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bprimei=[  dh/dx    0   ]
+	 *               [    0    dh/dy ]
+	 *               [  dh/dy  dh/dx ]
+	 *               [  dh/dx  dh/dy ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume Bprime has been allocated already, of size: 3x(NDOF2*NUMNODES)
+	 */
+
+	/*Same thing in the actual coordinate system: */
+	double dbasis[NDOF2][NUMNODES];
+
+	/*Get dh1dh2dh3 in actual coordinates system : */
+	GetNodalFunctionsDerivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build Bprime: */
+	for (int i=0;i<NUMNODES;i++){
+		*(Bprime+NDOF2*NUMNODES*0+NDOF2*i)=dbasis[0][i]; 
+		*(Bprime+NDOF2*NUMNODES*0+NDOF2*i+1)=0; 
+		*(Bprime+NDOF2*NUMNODES*1+NDOF2*i)=0; 
+		*(Bprime+NDOF2*NUMNODES*1+NDOF2*i+1)=dbasis[1][i]; 
+		*(Bprime+NDOF2*NUMNODES*2+NDOF2*i)=dbasis[1][i]; 
+		*(Bprime+NDOF2*NUMNODES*2+NDOF2*i+1)=dbasis[0][i]; 
+		*(Bprime+NDOF2*NUMNODES*3+NDOF2*i)=dbasis[0][i]; 
+		*(Bprime+NDOF2*NUMNODES*3+NDOF2*i+1)=dbasis[1][i]; 
+	}
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBprimePrognostic{{{1*/
+void TriaRef::GetBprimePrognostic(double* Bprime_prog, double* xyz_list, GaussTria* gauss){
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dh/dx ]
+	 *                [ dh/dy ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*NUMNODES)
+	 */
+
+	/*Same thing in the actual coordinate system: */
+	double dbasis[NDOF2][NUMNODES];
+
+	/*Get dh1dh2dh3 in actual coordinates system : */
+	GetNodalFunctionsDerivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build B': */
+	for (int i=0;i<NUMNODES;i++){
+		*(Bprime_prog+NDOF1*NUMNODES*0+NDOF1*i)=dbasis[0][i]; 
+		*(Bprime_prog+NDOF1*NUMNODES*1+NDOF1*i)=dbasis[1][i]; 
+	}
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetL{{{1*/
+void TriaRef::GetL(double* L, double* xyz_list,GaussTria* gauss,int numdof){
+	/*Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
+	 * For node i, Li can be expressed in the actual coordinate system
+	 * by: 
+	 *       numdof=1: 
+	 *                 Li=h;
+	 *       numdof=2:
+	 *                 Li=[ h   0 ]
+	 *                    [ 0   h ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume L has been allocated already, of size: NUMNODES (numdof=1), or numdofx(numdof*NUMNODES) (numdof=2)
+	 */
+
+	int i;
+	double basis[3];
+
+	/*Get basis in actual coordinate system: */
+	GetNodalFunctions(basis,gauss);
+
+	/*Build L: */
+	if(numdof==1){
+		for (i=0;i<NUMNODES;i++){
+			L[i]=basis[i]; 
+		}
+	}
+	else{
+		for (i=0;i<NUMNODES;i++){
+			*(L+numdof*NUMNODES*0+numdof*i)=basis[i]; //L[0][NDOF2*i]=dbasis[0][i];
+			*(L+numdof*NUMNODES*0+numdof*i+1)=0;
+			*(L+numdof*NUMNODES*1+numdof*i)=0;
+			*(L+numdof*NUMNODES*1+numdof*i+1)=basis[i];
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetJacobian{{{1*/
+void TriaRef::GetJacobian(double* J, double* xyz_list,GaussTria* gauss){
+	/*The Jacobian is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+	double x1,y1,x2,y2,x3,y3;
+
+	x1=*(xyz_list+NUMNODES*0+0);
+	y1=*(xyz_list+NUMNODES*0+1);
+	x2=*(xyz_list+NUMNODES*1+0);
+	y2=*(xyz_list+NUMNODES*1+1);
+	x3=*(xyz_list+NUMNODES*2+0);
+	y3=*(xyz_list+NUMNODES*2+1);
+
+
+	*(J+NDOF2*0+0)=0.5*(x2-x1);
+	*(J+NDOF2*1+0)=SQRT3/6.0*(2*x3-x1-x2);
+	*(J+NDOF2*0+1)=0.5*(y2-y1);
+	*(J+NDOF2*1+1)=SQRT3/6.0*(2*y3-y1-y2);
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetSegmentJacobianDeterminant{{{1*/
+void TriaRef::GetSegmentJacobianDeterminant(double* Jdet, double* xyz_list,GaussTria* gauss){
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated*/
+	double x1,y1,x2,y2;
+
+	x1=*(xyz_list+3*0+0);
+	y1=*(xyz_list+3*0+1);
+	x2=*(xyz_list+3*1+0);
+	y2=*(xyz_list+3*1+1);
+
+	*Jdet=1.0/2.0*sqrt(pow(x2-x1,2.) + pow(y2-y1,2.));
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetJacobianDeterminant2d{{{1*/
+void TriaRef::GetJacobianDeterminant2d(double* Jdet, double* xyz_list,GaussTria* gauss){
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+	double J[2][2];
+
+	/*Get Jacobian*/
+	GetJacobian(&J[0][0],xyz_list,gauss);
+
+	/*Get Determinant*/
+	Matrix2x2Determinant(Jdet,&J[0][0]);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetJacobianDeterminant3d {{{1*/
+void TriaRef::GetJacobianDeterminant3d(double*  Jdet, double* xyz_list,GaussTria* gauss){
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	double x1,x2,x3,y1,y2,y3,z1,z2,z3;
+
+	x1=*(xyz_list+3*0+0);
+	y1=*(xyz_list+3*0+1);
+	z1=*(xyz_list+3*0+2);
+	x2=*(xyz_list+3*1+0);
+	y2=*(xyz_list+3*1+1);
+	z2=*(xyz_list+3*1+2);
+	x3=*(xyz_list+3*2+0);
+	y3=*(xyz_list+3*2+1);
+	z3=*(xyz_list+3*2+2);
+
+	*Jdet=SQRT3/6.0*pow(pow(((y2-y1)*(z3-z1)-(z2-z1)*(y3-y1)),2.0)+pow(((z2-z1)*(x3-x1)-(x2-x1)*(z3-z1)),2.0)+pow(((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)),2.0),0.5);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetJacobianInvert{{{1*/
+void TriaRef::GetJacobianInvert(double*  Jinv, double* xyz_list,GaussTria* gauss){
+
+	/*Jacobian*/
+	double J[2][2];
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J[0][0], xyz_list, gauss);
+
+	/*Invert Jacobian matrix: */
+	Matrix2x2Invert(Jinv,&J[0][0]);
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctions{{{1*/
+void TriaRef::GetNodalFunctions(double* basis,GaussTria* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	basis[0]=gauss->coord1;
+	basis[1]=gauss->coord2;
+	basis[2]=gauss->coord3;
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetSegmentNodalFunctions{{{1*/
+void TriaRef::GetSegmentNodalFunctions(double* basis,GaussTria* gauss,int index1,int index2){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	double BasisFunctions[3];
+
+	GetNodalFunctions(&BasisFunctions[0],gauss);
+
+	_assert_(index1>=0 && index1<3);
+	_assert_(index2>=0 && index2<3);
+	basis[0]=BasisFunctions[index1];
+	basis[1]=BasisFunctions[index2];
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctionsDerivatives{{{1*/
+void TriaRef::GetNodalFunctionsDerivatives(double* dbasis,double* xyz_list, GaussTria* gauss){
+
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * actual coordinate system): */
+	int       i;
+	double    dbasis_ref[NDOF2][NUMNODES];
+	double    Jinv[NDOF2][NDOF2];
+
+	/*Get derivative values with respect to parametric coordinate system: */
+	GetNodalFunctionsDerivativesReference(&dbasis_ref[0][0], gauss); 
+
+	/*Get Jacobian invert: */
+	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
+
+	/*Build dbasis: 
+	 *
+	 * [dhi/dx]= Jinv*[dhi/dr]
+	 * [dhi/dy]       [dhi/ds]
+	 */
+	for (i=0;i<NUMNODES;i++){
+		dbasis[NUMNODES*0+i]=Jinv[0][0]*dbasis_ref[0][i]+Jinv[0][1]*dbasis_ref[1][i];
+		dbasis[NUMNODES*1+i]=Jinv[1][0]*dbasis_ref[0][i]+Jinv[1][1]*dbasis_ref[1][i];
+	}
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctionsDerivativesReference{{{1*/
+void TriaRef::GetNodalFunctionsDerivativesReference(double* dl1dl3,GaussTria* gauss){
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * natural coordinate system) at the gaussian point. */
+
+	/*First nodal function: */
+	*(dl1dl3+NUMNODES*0+0)=-0.5; 
+	*(dl1dl3+NUMNODES*1+0)=-1.0/(2.0*SQRT3);
+
+	/*Second nodal function: */
+	*(dl1dl3+NUMNODES*0+1)=0.5;
+	*(dl1dl3+NUMNODES*1+1)=-1.0/(2.0*SQRT3);
+
+	/*Third nodal function: */
+	*(dl1dl3+NUMNODES*0+2)=0;
+	*(dl1dl3+NUMNODES*1+2)=1.0/SQRT3;
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetInputDerivativeValue{{{1*/
+void TriaRef::GetInputDerivativeValue(double* p, double* plist,double* xyz_list, GaussTria* gauss){
+
+	/*From node values of parameter p (plist[0],plist[1],plist[2]), return parameter derivative value at gaussian 
+	 * point specified by gauss_basis:
+	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx+plist[2]*dh3/dx
+	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx+plist[2]*dh3/dx
+	 *
+	 * p is a vector of size 2x1 already allocated.
+	 */
+
+	/*Nodal Derivatives*/
+	double dbasis[2][3]; //nodal derivative functions in actual coordinate system.
+
+	/*Get dh1dh2dh3 in actual coordinate system: */
+	GetNodalFunctionsDerivatives(&dbasis[0][0],xyz_list, gauss);
+
+	/*Assign values*/
+	*(p+0)=plist[0]*dbasis[0][0]+plist[1]*dbasis[0][1]+plist[2]*dbasis[0][2];
+	*(p+1)=plist[0]*dbasis[1][0]+plist[1]*dbasis[1][1]+plist[2]*dbasis[1][2];
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetInputValue{{{1*/
+void TriaRef::GetInputValue(double* p, double* plist, GaussTria* gauss){
+
+	/*From node values of parameter p (plist[0],plist[1],plist[2]), return parameter value at gaussian 
+	 * point specifie by gauss: */
+
+	/*nodal functions annd output: */
+	double basis[3];
+
+	/*Get nodal functions*/
+	GetNodalFunctions(basis, gauss);
+
+	/*Get parameter*/
+	*p=basis[0]*plist[0]+basis[1]*plist[1]+basis[2]*plist[2];
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Elements/TriaRef.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Elements/TriaRef.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Elements/TriaRef.h	(revision 11330)
@@ -0,0 +1,49 @@
+/*!\file:  TriaRef.h
+ * \brief abstract class for handling Tria oriented routines, like nodal functions, 
+ * strain rate generation, etc ...
+ */ 
+
+
+#ifndef _TRIAREF_H_
+#define _TRIAREF_H_
+
+class GaussTria;
+
+class TriaRef{
+	
+
+	public: 
+		int* element_type_list; //P1CG, P1DG, MINI, P2...
+		int  element_type;
+		
+		TriaRef();
+		TriaRef(const int nummodels);
+		~TriaRef();
+
+		/*Management*/
+		void SetElementType(int type,int type_counter);
+
+		/*Numerics*/
+		void GetBMacAyeal(double* B, double* xyz_list, GaussTria* gauss);
+		void GetBMacAyealStokes(double* B , double* xyz_list, GaussTria* gauss);
+		void GetBprimeMacAyeal(double* Bprime, double* xyz_list, GaussTria* gauss);
+		void GetBprimeMacAyealStokes(double* Bprime, double* xyz_list, GaussTria* gauss);
+		void GetBprimePrognostic(double* Bprime_prog, double* xyz_list, GaussTria* gauss);
+		void GetBPrognostic(double* B_prog, double* xyz_list, GaussTria* gauss);
+		void GetL(double* L, double* xyz_list,GaussTria* gauss,int numdof);
+		void GetJacobian(double* J, double* xyz_list,GaussTria* gauss);
+		void GetSegmentJacobianDeterminant(double* Jdet, double* xyz_list,GaussTria* gauss);
+		void GetJacobianDeterminant2d(double* Jdet, double* xyz_list,GaussTria* gauss);
+		void GetJacobianDeterminant3d(double* Jdet, double* xyz_list,GaussTria* gauss);
+		void GetJacobianInvert(double*  Jinv, double* xyz_list,GaussTria* gauss);
+		void GetNodalFunctions(double* l1l2l3,GaussTria* gauss);
+		void GetSegmentNodalFunctions(double* l1l2l3,GaussTria* gauss, int index1,int index2);
+		void GetSegmentBFlux(double* B,GaussTria* gauss, int index1,int index2);
+		void GetSegmentBprimeFlux(double* Bprime,GaussTria* gauss, int index1,int index2);
+		void GetNodalFunctionsDerivatives(double* l1l2l3,double* xyz_list, GaussTria* gauss);
+		void GetNodalFunctionsDerivativesReference(double* dl1dl3,GaussTria* gauss);
+		void GetInputValue(double* pp, double* plist, GaussTria* gauss);
+		void GetInputDerivativeValue(double* pp, double* plist,double* xyz_list, GaussTria* gauss);
+
+};
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/BoolExternalResult.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/BoolExternalResult.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/BoolExternalResult.cpp	(revision 11330)
@@ -0,0 +1,205 @@
+/*!\file BoolExternalResult.c
+ * \brief: implementation of the BoolExternalResult object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*BoolExternalResult constructors and destructor*/
+/*FUNCTION BoolExternalResult::BoolExternalResult(){{{1*/
+BoolExternalResult::BoolExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::BoolExternalResult(int enum_type,bool value){{{1*/
+BoolExternalResult::BoolExternalResult(int in_id, int in_enum_type,bool in_value,int in_step, double in_time){
+
+	id=in_id;
+	enum_type=in_enum_type;
+	value=in_value;
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::~BoolExternalResult(){{{1*/
+BoolExternalResult::~BoolExternalResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION BoolExternalResult::Echo {{{1*/
+void BoolExternalResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::DeepEcho{{{1*/
+void BoolExternalResult::DeepEcho(void){
+
+	printf("BoolExternalResult:\n");
+	printf("   id: %i\n",this->id);
+	printf("   enum:  %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %s\n",this->value?"true":"false");
+	printf("   step: %i\n",this->step);
+	printf("   time: %g\n",this->time);
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::Id{{{1*/
+int    BoolExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION BoolExternalResult::MyRank{{{1*/
+int    BoolExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION BoolExternalResult::Marshall{{{1*/
+void  BoolExternalResult::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of BoolExternalResult: */
+	enum_value=BoolExternalResultEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall BoolExternalResult data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&value,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(marshalled_dataset,&step,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(marshalled_dataset,&time,sizeof(time));marshalled_dataset+=sizeof(time);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::MarshallSize{{{1*/
+int   BoolExternalResult::MarshallSize(){
+	
+	return sizeof(value)+
+		+sizeof(id)
+		+sizeof(enum_type)
+		+sizeof(step)
+		+sizeof(time)
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::Demarshall{{{1*/
+void  BoolExternalResult::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&value,marshalled_dataset,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(&step,marshalled_dataset,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(&time,marshalled_dataset,sizeof(time));marshalled_dataset+=sizeof(time);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION BoolExternalResult::ObjectEnum{{{1*/
+int BoolExternalResult::ObjectEnum(void){
+
+	return BoolExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::copy{{{1*/
+Object* BoolExternalResult::copy() {
+	
+	return new BoolExternalResult(this->id,this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*BoolExternalResult management: */
+/*FUNCTION BoolExternalResult::WriteData{{{1*/
+void   BoolExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	int     size;
+	double  boolean;
+	extern  int my_rank;
+	char*   name = NULL;
+
+	/*return if now on cpu 0: */
+	if(my_rank)return;
+
+	/*First write enum: */
+	EnumToStringx(&name,this->enum_type);
+	length=(strlen(name)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(name,length,1,fid);
+	xfree((void**)&name);
+
+	/*Now write time and step: */
+	fwrite(&time,sizeof(double),1,fid);
+	fwrite(&step,sizeof(int),1,fid);
+
+	/*Now write bool, after casting it: */
+	boolean=(double)this->value;
+
+	/*writing a double, type is 1, size is 1: */
+	type=1;
+	size=1;
+	fwrite(&type,sizeof(int),1,fid);
+	fwrite(&size,sizeof(int),1,fid);
+	fwrite(&boolean,size*sizeof(double),1,fid);
+
+}
+/*}}}1*/
+/*FUNCTION BoolExternalResult::GetResultName{{{1*/
+void BoolExternalResult::GetResultName(char** pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void BoolExternalResult::SetMatlabField(mxArray* dataref){
+
+	char* name=NULL;
+	this->GetResultName(&name);
+	
+	mxSetField( dataref, this->step-1, name,mxCreateDoubleScalar((double)value));
+	mxSetField( dataref, this->step-1, "time",mxCreateDoubleScalar((double)this->time)); 
+	mxSetField( dataref, this->step-1, "step",mxCreateDoubleScalar((double)this->step)); 
+}
+#endif
+/*}}}*/
+/*FUNCTION BoolExternalResult::GetStep{{{1*/
+int BoolExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/BoolExternalResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/BoolExternalResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/BoolExternalResult.h	(revision 11330)
@@ -0,0 +1,67 @@
+/*! \file BoolExternalResult.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _BOOLEXTERNALRESULT_H_
+#define _BOOLEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{1*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+
+#include "./ExternalResult.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../include/include.h"
+/*}}}*/
+
+class BoolExternalResult: public ExternalResult{
+
+	public:
+		int    id;
+		int    enum_type;
+		bool   value;
+		int    step;
+		double time;
+
+		/*BoolExternalResult constructors, destructors: {{{1*/
+		BoolExternalResult();
+		BoolExternalResult(int id, int enum_type,bool value,int step,double time);
+		~BoolExternalResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult management: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+	    #ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif  /* _BOOLEXTERNALRESULT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleExternalResult.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleExternalResult.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleExternalResult.cpp	(revision 11330)
@@ -0,0 +1,201 @@
+/*!\file DoubleExternalResult.c
+ * \brief: implementation of the DoubleExternalResult object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*DoubleExternalResult constructors and destructor*/
+/*FUNCTION DoubleExternalResult::DoubleExternalResult(){{{1*/
+DoubleExternalResult::DoubleExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::DoubleExternalResult(int enum_type,double value){{{1*/
+DoubleExternalResult::DoubleExternalResult(int in_id, int in_enum_type,double in_value,int in_step, double in_time){
+
+	id=in_id;
+	enum_type=in_enum_type;
+	value=in_value;
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::~DoubleExternalResult(){{{1*/
+DoubleExternalResult::~DoubleExternalResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleExternalResult::Echo {{{1*/
+void DoubleExternalResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::DeepEcho{{{1*/
+void DoubleExternalResult::DeepEcho(void){
+
+	printf("DoubleExternalResult:\n");
+	printf("   id: %i\n",this->id);
+	printf("   enum:  %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %g\n",this->value);
+	printf("   step: %i\n",this->step);
+	printf("   time: %g\n",this->time);
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::Id{{{1*/
+int    DoubleExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleExternalResult::MyRank{{{1*/
+int    DoubleExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION DoubleExternalResult::Marshall{{{1*/
+void  DoubleExternalResult::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of DoubleExternalResult: */
+	enum_value=DoubleExternalResultEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall DoubleExternalResult data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&value,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(marshalled_dataset,&step,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(marshalled_dataset,&time,sizeof(time));marshalled_dataset+=sizeof(time);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::MarshallSize{{{1*/
+int   DoubleExternalResult::MarshallSize(){
+	
+	return sizeof(value)+
+		+sizeof(id)
+		+sizeof(enum_type)
+		+sizeof(step)
+		+sizeof(time)
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::Demarshall{{{1*/
+void  DoubleExternalResult::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&value,marshalled_dataset,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(&step,marshalled_dataset,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(&time,marshalled_dataset,sizeof(time));marshalled_dataset+=sizeof(time);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION DoubleExternalResult::ObjectEnum{{{1*/
+int DoubleExternalResult::ObjectEnum(void){
+
+	return DoubleExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::copy{{{1*/
+Object* DoubleExternalResult::copy() {
+	
+	return new DoubleExternalResult(this->id,this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*DoubleExternalResult management: */
+/*FUNCTION DoubleExternalResult::WriteData{{{1*/
+void   DoubleExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	int     size;
+	char   *name    = NULL;
+	extern  int my_rank;
+
+	/*return if now on cpu 0: */
+	if(my_rank)return;
+
+	/*First write enum: */
+	EnumToStringx(&name,this->enum_type);
+	length=(strlen(name)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(name,length,1,fid);
+	xfree((void**)&name);
+
+	/*Now write time and step: */
+	fwrite(&time,sizeof(double),1,fid);
+	fwrite(&step,sizeof(int),1,fid);
+
+	/*writing a double, type is 1, size is 1: */
+	type=1;
+	size=1;
+	fwrite(&type,sizeof(int),1,fid);
+	fwrite(&size,sizeof(int),1,fid);
+	fwrite(&this->value,size*sizeof(double),1,fid);
+
+}
+/*}}}1*/
+/*FUNCTION DoubleExternalResult::GetResultName{{{1*/
+void DoubleExternalResult::GetResultName(char** pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void DoubleExternalResult::SetMatlabField(mxArray* dataref){
+
+	char* name=NULL;
+	this->GetResultName(&name);
+	mxSetField( dataref,this->step-1, name,mxCreateDoubleScalar(value));
+	mxSetField( dataref, this->step-1, "time",mxCreateDoubleScalar((double)this->time)); 
+	mxSetField( dataref, this->step-1, "step",mxCreateDoubleScalar((double)this->step)); 
+
+}
+#endif
+/*}}}*/
+/*FUNCTION DoubleExternalResult::GetStep{{{1*/
+int DoubleExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleExternalResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleExternalResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleExternalResult.h	(revision 11330)
@@ -0,0 +1,68 @@
+/*! \file DoubleExternalResult.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _DOUBLEEXTERNALRESULT_H_
+#define _DOUBLEEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{1*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+
+#include "./ExternalResult.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../include/include.h"
+/*}}}*/
+
+class DoubleExternalResult: public ExternalResult{
+
+	public:
+		int    id;
+		int    enum_type;
+		double value;
+		int    step;
+		double time;
+
+
+		/*DoubleExternalResult constructors, destructors: {{{1*/
+		DoubleExternalResult();
+		DoubleExternalResult(int id,int enum_type,double value,int step,double time);
+		~DoubleExternalResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult management: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif  /* _DOUBLEEXTERNALRESULT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleMatExternalResult.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleMatExternalResult.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleMatExternalResult.cpp	(revision 11330)
@@ -0,0 +1,262 @@
+/*!\file DoubleMatExternalResult.c
+ * \brief: implementation of the DoubleMatExternalResult object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*DoubleMatExternalResult constructors and destructor*/
+/*FUNCTION DoubleMatExternalResult::DoubleMatExternalResult(){{{1*/
+DoubleMatExternalResult::DoubleMatExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::DoubleMatExternalResult(int in_id, int enum_type,IssmDoubleMat values,int M,int N,int in_step,double in_time){{{1*/
+DoubleMatExternalResult::DoubleMatExternalResult(int in_id, int in_enum_type,double* in_values, int in_M,int in_N,int in_step,double in_time){
+
+	id=in_id;
+	enum_type=in_enum_type;
+	M=in_M;
+	N=in_N;
+
+	/*Copy result in values*/
+	if(M*N){
+		values=(double*)xmalloc(M*N*sizeof(double));
+		memcpy(values,in_values,M*N*sizeof(double));
+	}
+	else values=NULL;
+
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::~DoubleMatExternalResult(){{{1*/
+DoubleMatExternalResult::~DoubleMatExternalResult(){
+
+	xfree((void**)&this->values);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleMatExternalResult::Echo {{{1*/
+void DoubleMatExternalResult::Echo(void){
+
+	printf("DoubleMatExternalResult:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   step: %i\n",this->step);
+	printf("   time: %g\n",this->time);
+	printf("   matrix size: %i-%i\n",this->M,this->N);
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::DeepEcho{{{1*/
+void DoubleMatExternalResult::DeepEcho(void){
+
+	int i,j;
+	
+	printf("DoubleMatExternalResult:\n");
+	printf("   id: %i\n",this->id);
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   step: %i\n",this->step);
+	printf("   time: %g\n",this->time);
+	printf("   matrix size: %i-%i\n",this->M,this->N);
+	for (i=0;i<this->M;i++){  
+		printf("   [ ");
+		for (j=0;j<this->N;j++){
+			printf(" %12.6g ",this->values[i*this->N+j]);
+		}  
+		printf(" ]\n");
+	}  
+	printf("\n");
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::Id{{{1*/
+int    DoubleMatExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::MyRank{{{1*/
+int    DoubleMatExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION DoubleMatExternalResult::Marshall{{{1*/
+void  DoubleMatExternalResult::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of DoubleMatExternalResult: */
+	enum_value=DoubleMatExternalResultEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall DoubleMatExternalResult data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&M,sizeof(M));marshalled_dataset+=sizeof(M);
+	memcpy(marshalled_dataset,&N,sizeof(N));marshalled_dataset+=sizeof(N);
+	memcpy(marshalled_dataset,values,M*sizeof(double));marshalled_dataset+=M*sizeof(double);
+	memcpy(marshalled_dataset,&step,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(marshalled_dataset,&time,sizeof(time));marshalled_dataset+=sizeof(time);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::MarshallSize{{{1*/
+int   DoubleMatExternalResult::MarshallSize(){
+	
+	return sizeof(M)
+		+sizeof(N)
+		+M*N*sizeof(double)
+		+sizeof(id)
+		+sizeof(enum_type)
+		+sizeof(step)
+		+sizeof(time)
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::Demarshall{{{1*/
+void  DoubleMatExternalResult::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*data: */
+	memcpy(&M,marshalled_dataset,sizeof(M));marshalled_dataset+=sizeof(M);
+	memcpy(&N,marshalled_dataset,sizeof(N));marshalled_dataset+=sizeof(N);
+	values=(double*)xmalloc(M*N*sizeof(double));
+	memcpy(values,marshalled_dataset,M*N*sizeof(double));marshalled_dataset+=M*N*sizeof(double);
+	memcpy(&step,marshalled_dataset,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(&time,marshalled_dataset,sizeof(time));marshalled_dataset+=sizeof(time);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION DoubleMatExternalResult::ObjectEnum{{{1*/
+int DoubleMatExternalResult::ObjectEnum(void){
+
+	return DoubleMatExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::copy{{{1*/
+Object* DoubleMatExternalResult::copy() {
+	
+	return new DoubleMatExternalResult(this->id,this->enum_type,this->values,this->M,this->N,this->step,this->time);
+
+}
+/*}}}*/
+
+/*DoubleMatExternalResult management: */
+/*FUNCTION DoubleMatExternalResult::WriteData{{{1*/
+void   DoubleMatExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	int     rows,cols;
+	char   *name    = NULL;
+	extern  int my_rank;
+
+	if(io_gather){
+		/*we are gathering the data on cpu 0, don't write on other cpus: */
+		if(my_rank) return;
+	}
+
+	/*First write enum: */
+	EnumToStringx(&name,this->enum_type);
+	length=(strlen(name)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(name,length,1,fid);
+	xfree((void**)&name);
+
+	/*Now write time and step: */
+	fwrite(&time,sizeof(double),1,fid);
+	fwrite(&step,sizeof(int),1,fid);
+
+	/*writing a double 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(this->values,cols*rows*sizeof(double),1,fid);
+
+}
+/*}}}1*/
+/*FUNCTION DoubleMatExternalResult::GetResultName{{{1*/
+void DoubleMatExternalResult::GetResultName(char** pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void DoubleMatExternalResult::SetMatlabField(mxArray* dataref){
+
+	mxArray* pfield=NULL;
+	mxArray* pfield2=NULL;
+	char* name=NULL;
+	double* doublemat=NULL;
+
+	/*Make a copy of the value, to be used by matlab: */
+	doublemat=(double*)xmalloc(M*N*sizeof(double));
+	memcpy(doublemat,values,M*N*sizeof(double));
+
+	/*recover name: */
+	this->GetResultName(&name);
+				
+	/*create matlab matrix: */
+	pfield=mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pfield,N);
+	mxSetN(pfield,M);
+	mxSetPr(pfield,doublemat);
+	
+	/*transpose the matrix, from c to matlab format */
+	mexCallMATLAB(1,&pfield2, 1, &pfield, "transpose");
+
+	/*set tranpose matrix inside the dataref structure: */
+	mxSetField( dataref, this->step-1, name,pfield2);
+	mxSetField( dataref, this->step-1, "time",mxCreateDoubleScalar((double)this->time));
+	mxSetField( dataref, this->step-1, "step",mxCreateDoubleScalar((double)this->step));
+
+}
+#endif
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::GetStep{{{1*/
+int DoubleMatExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleMatExternalResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleMatExternalResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleMatExternalResult.h	(revision 11330)
@@ -0,0 +1,69 @@
+/*! \file DoubleMatExternalResult.h 
+ */
+
+
+#ifndef _DOUBLEMATEXTERNALRESULT_H_
+#define _DOUBLEMATEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{1*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+
+#include "./ExternalResult.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../include/include.h"
+/*}}}*/
+
+class DoubleMatExternalResult: public ExternalResult{
+
+	private: 
+		int id;
+		int enum_type;
+		double* values;
+		int M;
+		int N;
+		int step;
+		double time;
+
+	public:
+		/*DoubleMatExternalResult constructors, destructors: {{{1*/
+		DoubleMatExternalResult();
+		DoubleMatExternalResult(int id,int enum_type,double* values,int M,int N,int step, double time);
+		~DoubleMatExternalResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult managemnet: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif  /* _DOUBLEMATEXTERNALRESULT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleVecExternalResult.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleVecExternalResult.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleVecExternalResult.cpp	(revision 11330)
@@ -0,0 +1,241 @@
+/*!\file DoubleVecExternalResult.c
+ * \brief: implementation of the DoubleVecExternalResult object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*DoubleVecExternalResult constructors and destructor*/
+/*FUNCTION DoubleVecExternalResult::DoubleVecExternalResult(){{{1*/
+DoubleVecExternalResult::DoubleVecExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::DoubleVecExternalResult(int enum_type,IssmDoubleVec values,int M,int in_step,double in_time){{{1*/
+DoubleVecExternalResult::DoubleVecExternalResult(int in_id, int in_enum_type,double* in_values, int in_M,int in_step,double in_time){
+
+	id=in_id;
+	enum_type=in_enum_type;
+	M=in_M;
+
+	if(M){
+		values=(double*)xmalloc(M*sizeof(double));
+		memcpy(values,in_values,M*sizeof(double));
+	}
+	else values=NULL;
+
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::~DoubleVecExternalResult(){{{1*/
+DoubleVecExternalResult::~DoubleVecExternalResult(){
+	xfree((void**)&values);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleVecExternalResult::Echo {{{1*/
+void DoubleVecExternalResult::Echo(void){
+
+	printf("DoubleVecExternalResult:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   vector size: %i\n",this->M);
+	printf("   step: %i\n",this->step);
+	printf("   time: %g\n",this->time);
+
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::DeepEcho{{{1*/
+void DoubleVecExternalResult::DeepEcho(void){
+
+	int i;
+	
+	printf("DoubleVecExternalResult:\n");
+	printf("   id: %i\n",this->id);
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   vector size: %i\n",this->M);
+	for(i=0;i<this->M;i++){
+		printf("%i %g\n",i,this->values[i]);
+	}
+	printf("   step: %i\n",this->step);
+	printf("   time: %g\n",this->time);
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::Id{{{1*/
+int    DoubleVecExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::MyRank{{{1*/
+int    DoubleVecExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION DoubleVecExternalResult::Marshall{{{1*/
+void  DoubleVecExternalResult::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of DoubleVecExternalResult: */
+	enum_value=DoubleVecExternalResultEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall DoubleVecExternalResult data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&M,sizeof(M));marshalled_dataset+=sizeof(M);
+	memcpy(marshalled_dataset,values,M*sizeof(double));marshalled_dataset+=M*sizeof(double);
+	memcpy(marshalled_dataset,&step,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(marshalled_dataset,&time,sizeof(time));marshalled_dataset+=sizeof(time);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::MarshallSize{{{1*/
+int   DoubleVecExternalResult::MarshallSize(){
+	
+	return sizeof(M)
+		+M*sizeof(double)
+		+sizeof(id)
+		+sizeof(enum_type)
+		+sizeof(step)
+		+sizeof(time)
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::Demarshall{{{1*/
+void  DoubleVecExternalResult::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*data: */
+	memcpy(&M,marshalled_dataset,sizeof(M));marshalled_dataset+=sizeof(M);
+	values=(double*)xmalloc(M*sizeof(double));
+	memcpy(values,marshalled_dataset,M*sizeof(double));marshalled_dataset+=M*sizeof(double);
+	memcpy(&step,marshalled_dataset,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(&time,marshalled_dataset,sizeof(time));marshalled_dataset+=sizeof(time);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION DoubleVecExternalResult::ObjectEnum{{{1*/
+int DoubleVecExternalResult::ObjectEnum(void){
+
+	return DoubleVecExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::copy{{{1*/
+Object* DoubleVecExternalResult::copy() {
+	
+	return new DoubleVecExternalResult(this->id,this->enum_type,this->values,this->M,this->step,this->time);
+
+}
+/*}}}*/
+
+/*DoubleVecExternalResult management: */
+/*FUNCTION DoubleVecExternalResult::WriteData{{{1*/
+void   DoubleVecExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	int     size;
+	char   *name    = NULL;
+	extern  int my_rank;
+
+	/*return if now on cpu 0: */
+	if(my_rank)return;
+
+	/*First write enum: */
+	EnumToStringx(&name,this->enum_type);
+	length=(strlen(name)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(name,length,1,fid);
+	xfree((void**)&name);
+
+	/*Now write time and step: */
+	fwrite(&time,sizeof(double),1,fid);
+	fwrite(&step,sizeof(int),1,fid);
+
+	/*writing a double, type is 1, size is 1: */
+	type=1;
+	size=this->M;
+	fwrite(&type,sizeof(int),1,fid);
+	fwrite(&size,sizeof(int),1,fid);
+	fwrite(this->values,size*sizeof(double),1,fid);
+
+}
+/*}}}1*/
+/*FUNCTION DoubleVecExternalResult::GetResultName{{{1*/
+void DoubleVecExternalResult::GetResultName(char** pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void DoubleVecExternalResult::SetMatlabField(mxArray* dataref){
+
+	mxArray *pfield    = NULL;
+	double  *doublemat = NULL;
+	char    *name      = NULL;
+	double  *doublevec = NULL;
+
+	/*Make a copy of the value, to be used by matlab: */
+	doublevec=(double*)xmalloc(M*sizeof(double));
+	memcpy(doublevec,values,M*sizeof(double));
+
+	/*recover name: */
+	this->GetResultName(&name);
+				
+	/*create matlab matrix: */
+	pfield=mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pfield,M);
+	mxSetN(pfield,1);
+	mxSetPr(pfield,doublevec);
+
+	mxSetField( dataref, this->step-1, name,pfield);
+	mxSetField( dataref, this->step-1, "time",mxCreateDoubleScalar((double)this->time)); 
+	mxSetField( dataref, this->step-1, "step",mxCreateDoubleScalar((double)this->step)); 
+}
+#endif
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::GetStep{{{1*/
+int DoubleVecExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleVecExternalResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleVecExternalResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/DoubleVecExternalResult.h	(revision 11330)
@@ -0,0 +1,68 @@
+/*! \file DoubleVecExternalResult.h 
+ */
+
+
+#ifndef _DOUBLEVECEXTERNALRESULT_H_
+#define _DOUBLEVECEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{1*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+
+#include "./ExternalResult.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../include/include.h"
+/*}}}*/
+
+class DoubleVecExternalResult: public ExternalResult{
+
+	private: 
+		int id;
+		int enum_type;
+		double* values;
+		int M;
+		int step;
+		double time;
+
+	public:
+		/*DoubleVecExternalResult constructors, destructors: {{{1*/
+		DoubleVecExternalResult();
+		DoubleVecExternalResult(int id,int enum_type,double* values,int M,int step, double time);
+		~DoubleVecExternalResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult management: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif  /* _DOUBLEVECEXTERNALRESULT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/ExternalResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/ExternalResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/ExternalResult.h	(revision 11330)
@@ -0,0 +1,41 @@
+/*!\file:  ExternalResult.h
+ * \brief abstract class for ExternalResult object
+ */ 
+
+
+#ifndef _EXTERNALRESULT_H_
+#define _EXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{1*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "../Object.h"
+#include "../Node.h"
+/*}}}*/
+
+class ExternalResult: public Object{
+
+	public: 
+		
+		virtual        ~ExternalResult(){};
+		/*Virtual functions:{{{1*/
+		virtual int   InstanceEnum()=0;
+		virtual void  WriteData(FILE* fid,bool io_gather)=0;
+		virtual void  GetResultName(char**)=0;
+		#ifdef _SERIAL_
+		virtual void  SetMatlabField(mxArray* dataref)=0;
+		#endif
+		virtual int   GetStep(void)=0;
+		/*}}}*/
+};
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/IntExternalResult.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/IntExternalResult.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/IntExternalResult.cpp	(revision 11330)
@@ -0,0 +1,206 @@
+/*!\file IntExternalResult.c
+ * \brief: implementation of the IntExternalResult object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*IntExternalResult constructors and destructor*/
+/*FUNCTION IntExternalResult::IntExternalResult(){{{1*/
+IntExternalResult::IntExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::IntExternalResult(int in_id, int in_enum_type,int in_value,int in_step, double in_time){{{1*/
+IntExternalResult::IntExternalResult(int in_id, int in_enum_type,int in_value,int in_step, double in_time){
+
+	id=in_id;
+	enum_type=in_enum_type;
+	value=in_value;
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::~IntExternalResult(){{{1*/
+IntExternalResult::~IntExternalResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION IntExternalResult::Echo {{{1*/
+void IntExternalResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::DeepEcho{{{1*/
+void IntExternalResult::DeepEcho(void){
+
+	printf("IntExternalResult:\n");
+	printf("   id: %i\n",this->id);
+	printf("   enum:  %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %i\n",this->value);
+	printf("   step: %i\n",this->step);
+	printf("   time: %g\n",this->time);
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::Id{{{1*/
+int    IntExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntExternalResult::MyRank{{{1*/
+int    IntExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION IntExternalResult::Marshall{{{1*/
+void  IntExternalResult::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of IntExternalResult: */
+	enum_value=IntExternalResultEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall IntExternalResult data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&value,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(marshalled_dataset,&step,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(marshalled_dataset,&time,sizeof(time));marshalled_dataset+=sizeof(time);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::MarshallSize{{{1*/
+int   IntExternalResult::MarshallSize(){
+	
+	return sizeof(value)+
+		+sizeof(id)
+		+sizeof(enum_type)
+		+sizeof(step)
+		+sizeof(time)
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::Demarshall{{{1*/
+void  IntExternalResult::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&value,marshalled_dataset,sizeof(value));marshalled_dataset+=sizeof(value);
+	memcpy(&step,marshalled_dataset,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(&time,marshalled_dataset,sizeof(time));marshalled_dataset+=sizeof(time);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION IntExternalResult::ObjectEnum{{{1*/
+int IntExternalResult::ObjectEnum(void){
+
+	return IntExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::copy{{{1*/
+Object* IntExternalResult::copy() {
+	
+	return new IntExternalResult(this->id,this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*IntExternalResult management: */
+/*FUNCTION IntExternalResult::WriteData{{{1*/
+void   IntExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	int     size;
+	char   *name    = NULL;
+	double  integer;
+	extern  int my_rank;
+
+	/*return if now on cpu 0: */
+	if(my_rank)return;
+
+	/*First write enum: */
+	EnumToStringx(&name,this->enum_type);
+	length=(strlen(name)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(name,length,1,fid);
+	xfree((void**)&name);
+
+	/*Now write time and step: */
+	fwrite(&time,sizeof(double),1,fid);
+	fwrite(&step,sizeof(int),1,fid);
+
+	/*cast to a double: */
+	integer=(double)this->value;
+
+	/*writing a double, type is 1, size is 1: */
+	type=1;
+	size=1;
+	fwrite(&type,sizeof(int),1,fid);
+	fwrite(&size,sizeof(int),1,fid);
+	fwrite(&integer,size*sizeof(double),1,fid);
+
+}
+/*}}}1*/
+/*FUNCTION IntExternalResult::GetResultName{{{1*/
+void IntExternalResult::GetResultName(char** pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void IntExternalResult::SetMatlabField(mxArray* dataref){
+
+	char* name=NULL;
+	this->GetResultName(&name);
+
+	mxSetField( dataref, this->step-1, name,mxCreateDoubleScalar(value));
+	mxSetField( dataref, this->step-1, "time",mxCreateDoubleScalar((double)this->time)); 
+	mxSetField( dataref, this->step-1, "step",mxCreateDoubleScalar((double)this->step)); 
+
+}
+#endif
+/*}}}*/
+/*FUNCTION IntExternalResult::GetStep{{{1*/
+int IntExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/IntExternalResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/IntExternalResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/IntExternalResult.h	(revision 11330)
@@ -0,0 +1,66 @@
+/*! \file IntExternalResult.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _INTEXTERNALRESULT_H_
+#define _INTEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{1*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./ExternalResult.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class IntExternalResult: public ExternalResult{
+
+	public:
+		int    id;
+		int    enum_type;
+		int    value;
+		int    step;
+		double time;
+
+
+		/*IntExternalResult constructors, destructors: {{{1*/
+		IntExternalResult();
+		IntExternalResult(int id,int enum_type,int value,int step,double time);
+		~IntExternalResult();
+
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult managemnet: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif  /* _INTEXTERNALRESULT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/PetscVecExternalResult.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/PetscVecExternalResult.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/PetscVecExternalResult.cpp	(revision 11330)
@@ -0,0 +1,276 @@
+/*!\file PetscVecExternalResult.c
+ * \brief: implementation of the PetscVecExternalResult object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*PetscVecExternalResult constructors and destructor*/
+/*FUNCTION PetscVecExternalResult::PetscVecExternalResult(){{{1*/
+PetscVecExternalResult::PetscVecExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::PetscVecExternalResult(int enum_type,IssmPetscVec value){{{1*/
+PetscVecExternalResult::PetscVecExternalResult(int in_id, int in_enum_type,Vec in_value,int in_step, double in_time){
+
+	id=in_id;
+	enum_type=in_enum_type;
+
+	value=NULL;
+
+	if(in_value){
+		VecDuplicate(in_value,&value);
+		VecCopy(in_value,value);
+	}
+	else value=NULL;
+
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::~PetscVecExternalResult(){{{1*/
+PetscVecExternalResult::~PetscVecExternalResult(){
+	VecFree(&value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION PetscVecExternalResult::Echo {{{1*/
+void PetscVecExternalResult::Echo(void){
+
+	printf("PetscVecExternalResult:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::DeepEcho{{{1*/
+void PetscVecExternalResult::DeepEcho(void){
+
+	int i;
+	printf("PetscVecExternalResult:\n");
+	printf("   id: %i\n",this->id);
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   step: %i\n",this->step);
+	printf("   time: %g\n",this->time);
+	VecView(value,PETSC_VIEWER_STDOUT_WORLD);
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::Id{{{1*/
+int    PetscVecExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::MyRank{{{1*/
+int    PetscVecExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION PetscVecExternalResult::Marshall{{{1*/
+void  PetscVecExternalResult::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+	int   M;
+	double* serial_value=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of PetscVecExternalResult: */
+	enum_value=PetscVecExternalResultEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall PetscVecExternalResult data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&step,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(marshalled_dataset,&time,sizeof(time));marshalled_dataset+=sizeof(time);
+	
+	if(value){
+		VecGetSize(value,&M);
+		VecToMPISerial(&serial_value,value);
+		memcpy(marshalled_dataset,&M,sizeof(M));marshalled_dataset+=sizeof(M);
+		memcpy(marshalled_dataset,serial_value,M*sizeof(double));marshalled_dataset+=(M*sizeof(double));
+	}
+	else{
+		M=0;
+		memcpy(marshalled_dataset,&M,sizeof(M));marshalled_dataset+=sizeof(M);
+	}
+	/*Free ressources:*/
+	xfree((void**)&serial_value);
+
+	/*return:*/
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::MarshallSize{{{1*/
+int   PetscVecExternalResult::MarshallSize(){
+
+	int M=0;
+	if(value)VecGetSize(value,&M);
+
+	return sizeof(M)+M*sizeof(double)
+		+sizeof(id)
+		+sizeof(enum_type)
+		+sizeof(step)
+		+sizeof(time)
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::Demarshall{{{1*/
+void  PetscVecExternalResult::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+	int   M;
+	double* serial_vec=NULL;
+	int*    idxm=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*data: */
+	memcpy(&step,marshalled_dataset,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(&time,marshalled_dataset,sizeof(time));marshalled_dataset+=sizeof(time);
+	
+	memcpy(&M,marshalled_dataset,sizeof(M));marshalled_dataset+=sizeof(M);
+	if(M){
+		serial_vec=(double*)xmalloc(M*sizeof(double));
+		memcpy(serial_vec,marshalled_dataset,M*sizeof(double));marshalled_dataset+=(M*sizeof(double));
+
+		value=NewVec(M);
+		idxm=(int*)xmalloc(M*sizeof(int));
+		for(i=0;i<M;i++)idxm[i]=i;
+		VecSetValues(value,M,idxm,serial_vec,INSERT_VALUES);
+
+		VecAssemblyBegin(value);
+		VecAssemblyEnd(value);
+
+		
+	}
+	else{
+		value=NULL;
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&serial_vec);
+	xfree((void**)&idxm);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+#endif
+/*FUNCTION PetscVecExternalResult::ObjectEnum{{{1*/
+int PetscVecExternalResult::ObjectEnum(void){
+
+	return PetscVecExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::copy{{{1*/
+Object* PetscVecExternalResult::copy() {
+	
+	return new PetscVecExternalResult(this->id,this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*PetscVecExternalResult management: */
+/*FUNCTION PetscVecExternalResult::WriteData{{{1*/
+void   PetscVecExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	int     size;
+	char   *name      = NULL;
+	double *serialvec = NULL;
+	extern int my_rank;
+
+	/*serialize: */
+	VecGetSize(this->value,&size);
+	VecToMPISerial(&serialvec,this->value);
+
+	/*now, exit if we are not on cpu 0: */
+	if(my_rank)return;
+
+	/*First write enum: */
+	EnumToStringx(&name,this->enum_type);
+	length=(strlen(name)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(name,length,1,fid);
+	xfree((void**)&name);
+
+	/*Now write time and step: */
+	fwrite(&time,sizeof(double),1,fid);
+	fwrite(&step,sizeof(int),1,fid);
+
+	/*writing a double, type is 1, size is 1: */
+	type=1;
+	
+	fwrite(&type,sizeof(int),1,fid);
+	fwrite(&size,sizeof(int),1,fid);
+	fwrite(serialvec,size*sizeof(double),1,fid);
+
+	/*Free ressources:*/
+	xfree((void**)&serialvec);
+}
+/*}}}1*/
+/*FUNCTION PetscVecExternalResult::GetResultName{{{1*/
+void PetscVecExternalResult::GetResultName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  PetscVecExternalResult::SetMatlabField(mxArray* dataref){
+
+	mxArray* pfield=NULL;
+	char* name=NULL;
+	double* doublevec=NULL;
+	int M;
+	
+	VecToMPISerial(&doublevec,value);
+	VecGetSize(value,&M);
+	this->GetResultName(&name);
+	
+	pfield=mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pfield,M);
+	mxSetN(pfield,1);
+	mxSetPr(pfield,doublevec);
+	
+	mxSetField( dataref, this->step-1, name, pfield);
+	mxSetField( dataref, this->step-1, "time",mxCreateDoubleScalar((double)this->time)); 
+	mxSetField( dataref, this->step-1, "step",mxCreateDoubleScalar((double)this->step)); 
+
+}
+#endif
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::GetStep{{{1*/
+int PetscVecExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/PetscVecExternalResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/PetscVecExternalResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/PetscVecExternalResult.h	(revision 11330)
@@ -0,0 +1,68 @@
+/*! \file PetscVecExternalResult.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _PETSCVECEXTERNALRESULT_H_
+#define _PETSCVECEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{1*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+
+#include "./ExternalResult.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../include/include.h"
+/*}}}*/
+
+class PetscVecExternalResult: public ExternalResult{
+
+	private: 
+		int id;
+		int enum_type;
+		Vec value;
+		int step;
+		double time;
+
+	public:
+		/*PetscVecExternalResult constructors, destructors: {{{1*/
+		PetscVecExternalResult();
+		PetscVecExternalResult(int id,int enum_type,Vec value, int step, double time);
+		~PetscVecExternalResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult management: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif  /* _PETSCVECEXTERNALRESULT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/StringExternalResult.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/StringExternalResult.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/StringExternalResult.cpp	(revision 11330)
@@ -0,0 +1,219 @@
+/*!\file StringExternalResult.c
+ * \brief: implementation of the StringExternalResult object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*StringExternalResult constructors and destructor*/
+/*FUNCTION StringExternalResult::StringExternalResult(){{{1*/
+StringExternalResult::StringExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::StringExternalResult(int enum_type,IssmString value){{{1*/
+StringExternalResult::StringExternalResult(int in_id, int in_enum_type,char* in_value,int in_step, double in_time){
+
+	id=in_id;
+	enum_type=in_enum_type;
+	value=(char*)xmalloc((strlen(in_value)+1)*sizeof(char));
+	memcpy(value,in_value,(strlen(in_value)+1)*sizeof(char));
+
+	step=in_step;
+	time=in_time;
+	
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::~StringExternalResult(){{{1*/
+StringExternalResult::~StringExternalResult(){
+	xfree((void**)&value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION StringExternalResult::Echo {{{1*/
+void StringExternalResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::DeepEcho{{{1*/
+void StringExternalResult::DeepEcho(void){
+
+	printf("StringExternalResult:\n");
+	printf("   id: %i\n",this->id);
+	printf("   enum:  %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %s\n",this->value);
+	printf("   step: %i\n",this->step);
+	printf("   time: %g\n",this->time);
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::Id{{{1*/
+int    StringExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION StringExternalResult::MyRank{{{1*/
+int    StringExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION StringExternalResult::Marshall{{{1*/
+void  StringExternalResult::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+	int   stringsize;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of StringExternalResult: */
+	enum_value=StringExternalResultEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+
+	/*marshall data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	stringsize=strlen(this->value)+1;
+	
+	memcpy(marshalled_dataset,&stringsize,sizeof(stringsize));marshalled_dataset+=sizeof(stringsize);
+	memcpy(marshalled_dataset,this->value,stringsize*sizeof(char));marshalled_dataset+=stringsize*sizeof(char);
+	memcpy(marshalled_dataset,&step,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(marshalled_dataset,&time,sizeof(time));marshalled_dataset+=sizeof(time);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::MarshallSize{{{1*/
+int   StringExternalResult::MarshallSize(){
+
+	int stringsize;
+	stringsize=strlen(this->value)+1;
+	
+	return sizeof(int)+
+		+stringsize*sizeof(char)
+		+sizeof(id)
+		+sizeof(enum_type)
+		+sizeof(step)
+		+sizeof(time)
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::Demarshall{{{1*/
+void  StringExternalResult::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+	int   stringsize;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+
+	memcpy(&stringsize,marshalled_dataset,sizeof(int));marshalled_dataset+=sizeof(int);
+	
+	this->value=(char*)xmalloc(stringsize*sizeof(char));
+	memcpy(value,marshalled_dataset,stringsize*sizeof(char));marshalled_dataset+=stringsize*sizeof(char);
+	memcpy(&step,marshalled_dataset,sizeof(step));marshalled_dataset+=sizeof(step);
+	memcpy(&time,marshalled_dataset,sizeof(time));marshalled_dataset+=sizeof(time);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION StringExternalResult::ObjectEnum{{{1*/
+int StringExternalResult::ObjectEnum(void){
+
+	return StringExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::copy{{{1*/
+Object* StringExternalResult::copy() {
+	
+	return new StringExternalResult(this->id,this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*StringExternalResult management: */
+/*FUNCTION StringExternalResult::WriteData{{{1*/
+void   StringExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	char   *name      = NULL;
+	extern  int my_rank;
+
+	/*return if now on cpu 0: */
+	if(my_rank)return;
+
+	/*First write enum: */
+	EnumToStringx(&name,this->enum_type);
+	length=(strlen(name)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(name,length,1,fid);
+	xfree((void**)&name);
+
+	/*Now write time and step: */
+	fwrite(&time,sizeof(double),1,fid);
+	fwrite(&step,sizeof(int),1,fid);
+
+	/*writing a string, type is 2: */
+	type=2;
+	fwrite(&type,sizeof(int),1,fid);
+	
+	length=(strlen(this->value)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(this->value,length,1,fid);
+
+}
+/*}}}1*/
+/*FUNCTION StringExternalResult::GetResultName{{{1*/
+void StringExternalResult::GetResultName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  StringExternalResult::SetMatlabField(mxArray* dataref){
+	
+	char* name=NULL;
+
+	this->GetResultName(&name);
+
+	mxSetField( dataref, this->step-1, name, mxCreateString(value));
+	mxSetField( dataref, this->step-1, "time",mxCreateDoubleScalar((double)this->time)); 
+	mxSetField( dataref, this->step-1, "step",mxCreateDoubleScalar((double)this->step)); 
+
+}
+#endif
+/*}}}*/
+/*FUNCTION StringExternalResult::GetStep{{{1*/
+int StringExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/ExternalResults/StringExternalResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/ExternalResults/StringExternalResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/ExternalResults/StringExternalResult.h	(revision 11330)
@@ -0,0 +1,66 @@
+/*! \file StringExternalResult.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _STRINGEXTERNALRESULT_H_
+#define _STRINGEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{1*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+
+#include "./ExternalResult.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../include/include.h"
+/*}}}*/
+
+class StringExternalResult: public ExternalResult{
+
+	private: 
+		int    id;
+		int    enum_type;
+		char*  value;
+		int    step;
+		double time;
+
+	public:
+		/*StringExternalResult constructors, destructors: {{{1*/
+		StringExternalResult();
+		StringExternalResult(int id,int enum_type,char* value,int step, double time);
+		~StringExternalResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult management: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif  /* _STRINGEXTERNALRESULT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/FemModel.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/FemModel.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/FemModel.cpp	(revision 11330)
@@ -0,0 +1,160 @@
+/*!\file FemModel.c
+ * \brief: implementation of the FemModel object
+ */
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include "../Container/Container.h"
+#include "../modules/ModelProcessorx/ModelProcessorx.h"
+#include "../io/io.h"
+#include "./objects.h"
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../modules/modules.h"
+
+/*Object constructors and destructor*/
+/*FUNCTION FemModel::constructor {{{1*/
+FemModel::FemModel(char* inputfilename, char* outputfilename, const int in_solution_type,const int* analyses,const int nummodels){
+#ifdef _PARALLEL_
+
+	/*intermediary*/
+	int i;
+	int analysis_type;
+	FILE* IOMODEL;
+	extern int my_rank;
+
+	/*Open input file on cpu 0: */
+	if(my_rank==0) IOMODEL= pfopen(inputfilename ,"rb");
+
+	/*Initialize internal data: */
+	this->nummodels=nummodels;
+	this->solution_type=in_solution_type;
+	this->analysis_counter=nummodels-1; //point to last analysis_type carried out.
+	this->results=new Results(); //not initialized by CreateDataSets
+	
+	/*Dynamically allocate whatever is a list of length nummodels: */
+	analysis_type_list=(int*)xmalloc(nummodels*sizeof(int));
+
+	/*Initialize: */
+	for(i=0;i<nummodels;i++)analysis_type_list[i]=analyses[i];
+
+	/*create datasets for all analyses*/
+	ModelProcessorx(&this->elements,&this->nodes,&this->vertices,&this->materials,&this->constraints,&this->loads,&this->parameters,IOMODEL,this->solution_type,nummodels,analyses);
+
+	/*do the post-processing of the datasets to get an FemModel that can actually run analyses: */
+	for(i=0;i<nummodels;i++){
+
+		_printf_(VerboseMProcessor(),"   Processing finite element model of analysis %s:\n",EnumToStringx(analysis_type_list[i]));
+		analysis_type=analysis_type_list[i];
+		this->SetCurrentConfiguration(analysis_type);
+	
+		if(i==0){
+			_printf_(VerboseMProcessor(),"      creating vertex degrees of freedom\n");
+			VerticesDofx(vertices,parameters); //only call once, we only have one set of vertices
+		}
+
+		_printf_(VerboseMProcessor(),"      resolving node constraints\n");
+		SpcNodesx(nodes,constraints,parameters,analysis_type); 
+
+		_printf_(VerboseMProcessor(),"      creating nodal degrees of freedom\n");
+		NodesDofx(nodes,parameters,analysis_type);
+	
+		_printf_(VerboseMProcessor(),"      configuring element and loads\n");
+		ConfigureObjectsx(elements, loads, nodes, vertices, materials,parameters);
+	}
+	
+	/*Close input file descriptors: */
+	if(my_rank==0) pfclose(IOMODEL,inputfilename);
+
+	/*Add output file name to parameters: */
+	this->parameters->AddObject(new StringParam(OutputfilenameEnum,outputfilename));
+
+#endif
+
+}
+
+/*}}}1*/
+/*FUNCTION FemModel::destructor {{{1*/
+FemModel::~FemModel(){
+
+	/*Intermediary*/
+	int i;
+
+	/*Delete all the datasets: */
+	xfree((void**)&analysis_type_list);
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete constraints;
+	delete loads;
+	delete materials;
+	delete parameters;
+	delete results;
+
+}
+/*}}}1*/
+
+/*Object management*/
+/*FUNCTION FemModel::Echo {{{1*/
+void FemModel::Echo(void){
+
+	printf("FemModel echo: \n");
+	printf("   number of fem models: %i\n",nummodels);
+	printf("   analysis_type_list: \n");
+	for(int i=0;i<nummodels;i++)printf("     %i: %s\n",i,EnumToStringx(analysis_type_list[i]));
+	printf("   current analysis_type: \n");
+	printf("     %i: %s\n",analysis_counter,EnumToStringx(analysis_type_list[analysis_counter]));
+
+}
+/*}}}*/
+
+/*Numerics: */
+/*FUNCTION FemModel::SetCurrentConfiguration(int configuration_type,int analysis_type){{{1*/
+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 %s in list of FemModel analyses",EnumToStringx(configuration_type));
+
+	/*Now, plug analysis_counter and analysis_type inside the parameters: */
+	this->parameters->SetParam(analysis_counter,AnalysisCounterEnum);
+	this->parameters->SetParam(analysis_type,AnalysisTypeEnum);
+	this->parameters->SetParam(configuration_type,ConfigurationTypeEnum);
+
+	/*configure elements, loads and nodes, for this new analysis: */
+	this->elements->SetCurrentConfiguration(elements,loads, nodes,vertices, materials,parameters);
+	this->nodes->SetCurrentConfiguration(elements,loads, nodes,vertices, materials,parameters);
+	this->loads->SetCurrentConfiguration(elements, loads, nodes,vertices, materials,parameters);
+
+	/*take care of petsc options, that depend on this analysis type (present only after model processor)*/
+	if(this->parameters->Exist(PetscOptionsStringsEnum)){
+		PetscOptionsFromAnalysis(this->parameters,analysis_type);
+		_printf_(VerboseSolver(),"      petsc Options set for analysis type: %s\n",EnumToStringx(analysis_type));
+	}
+
+}
+/*}}}1*/
+/*FUNCTION FemModel::SetCurrentConfiguration(int configuration_type){{{1*/
+void FemModel::SetCurrentConfiguration(int configuration_type){
+
+	/*overload: analysis_type = configuration_type: */
+	this->SetCurrentConfiguration(configuration_type,configuration_type);
+}
+/*}}}1*/
Index: /issm/trunk-jpl-damage/src/c/objects/FemModel.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/FemModel.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/FemModel.h	(revision 11330)
@@ -0,0 +1,51 @@
+/*
+ * FemModel.h: 
+ */
+
+#ifndef _FEMMODEL_H_
+#define _FEMMODEL_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Object.h"
+#include "../toolkits/toolkits.h"
+class DataSet;
+class Parameters;
+class NodeSets;
+/*}}}*/
+
+
+class FemModel {
+
+	/*no private members, as we need access to these datasets quite often!:*/
+
+	public:
+
+		int                 nummodels;
+		int                 solution_type;
+		int*                analysis_type_list; //list of analyses this femmodel is going to carry out
+		int                 analysis_counter; //counter into analysis_type_list
+		
+		Elements*           elements; //elements (one set for all analyses)
+		Nodes*              nodes; //one set of nodes
+		Vertices*           vertices; //one set of vertices
+		Constraints*        constraints; //one set of constraints. each constraint knows which analysis_type it handles
+		Loads*              loads;  //one set of constraints. each constraint knows which analysis_type it handles
+		Materials*          materials;  //one set of materials, for each element
+		Parameters*         parameters; //one set of parameters, independent of the analysis_type
+		Results*            results; //results that cannot be fit into the elements (such as one time constants, arrays, strings, etc ...)
+
+		/*constructors, destructors: */
+		FemModel(char* inputfilename, char* outputfilename, const int solution_type,const int* analyses,const int nummodels);
+		~FemModel();
+
+		/*Methods: */
+		void Echo();
+
+		/*Fem: */
+		void  SetCurrentConfiguration(int configuration_type);
+		void  SetCurrentConfiguration(int configuration_type,int analysis_type);
+
+};
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Gauss/GaussPenta.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Gauss/GaussPenta.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Gauss/GaussPenta.cpp	(revision 11330)
@@ -0,0 +1,406 @@
+/*!\file GaussPenta.c
+ * \brief: implementation of the GaussPenta object
+ */
+
+/*Include files: {{{1*/
+#include "./../objects.h"
+/*}}}*/
+
+/*GaussPenta constructors and destructors:*/
+/*FUNCTION GaussPenta::GaussPenta() {{{1*/
+GaussPenta::GaussPenta(){
+
+	numgauss=-1;
+
+	weights=NULL;
+	coords1=NULL;
+	coords2=NULL;
+	coords3=NULL;
+	coords4=NULL;
+
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+	coord4=UNDEF;
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussPenta(int order_horiz,int order_vert) {{{1*/
+GaussPenta::GaussPenta(int order_horiz,int order_vert){
+
+	/*Intermediaries*/
+	int     ighoriz,igvert;
+	int     numgauss_horiz;
+	int     numgauss_vert;
+	double *coords1_horiz = NULL;
+	double *coords2_horiz = NULL;
+	double *coords3_horiz = NULL;
+	double *weights_horiz  = NULL;
+	double *coords_vert = NULL;
+	double *weights_vert   = NULL;
+
+	/*Get gauss points*/
+	GaussLegendreTria(&numgauss_horiz,&coords1_horiz,&coords2_horiz,&coords3_horiz,&weights_horiz,order_horiz);
+	GaussLegendreLinear(&coords_vert,&weights_vert,order_vert);
+	numgauss_vert=order_vert;
+
+	/*Allocate GaussPenta fields*/
+	numgauss=numgauss_horiz*numgauss_vert;
+	coords1=(double*)xmalloc(numgauss*sizeof(double));
+	coords2=(double*)xmalloc(numgauss*sizeof(double));
+	coords3=(double*)xmalloc(numgauss*sizeof(double));
+	coords4=(double*)xmalloc(numgauss*sizeof(double));
+	weights=(double*)xmalloc(numgauss*sizeof(double));
+
+	/*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*/
+	xfree((void**)&coords1_horiz);
+	xfree((void**)&coords2_horiz);
+	xfree((void**)&coords3_horiz);
+	xfree((void**)&coords_vert);
+	xfree((void**)&weights_horiz);
+	xfree((void**)&weights_vert);
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussPenta(int index1, int index2, int order){{{1*/
+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=(double*)xmalloc(numgauss*sizeof(double));
+	coords2=(double*)xmalloc(numgauss*sizeof(double));
+	coords3=(double*)xmalloc(numgauss*sizeof(double));
+	coords4=(double*)xmalloc(numgauss*sizeof(double));
+	weights=(double*)xmalloc(numgauss*sizeof(double));
+
+	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*/
+	xfree((void**)&seg_coords);
+	xfree((void**)&seg_weights);
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussPenta(int index1, int index2, int index3, int order){{{1*/
+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=(double*)xmalloc(numgauss*sizeof(double));
+		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=(double*)xmalloc(numgauss*sizeof(double));
+		for(int i=0;i<numgauss;i++) coords4[i]=1.0;
+	}
+	else{
+		_error_("Tria not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussPenta(int index1, int index2, int index3, int index4,int order_horiz,int order_vert){{{1*/
+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=(double*)xmalloc(numgauss*sizeof(double));
+	coords2=(double*)xmalloc(numgauss*sizeof(double));
+	coords3=(double*)xmalloc(numgauss*sizeof(double));
+	coords4=(double*)xmalloc(numgauss*sizeof(double));
+	weights=(double*)xmalloc(numgauss*sizeof(double));
+
+	/*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 %i %i %i %i)",index1,index2,index3,index4);
+	}
+
+	/*clean-up*/
+	xfree((void**)&seg_horiz_coords);
+	xfree((void**)&seg_horiz_weights);
+	xfree((void**)&seg_vert_coords);
+	xfree((void**)&seg_vert_weights);
+}
+/*}}}*/
+/*FUNCTION GaussPenta::~GaussPenta(){{{1*/
+GaussPenta::~GaussPenta(){
+	xfree((void**)&weights);
+	xfree((void**)&coords1);
+	xfree((void**)&coords2);
+	xfree((void**)&coords3);
+	xfree((void**)&coords4);
+}
+/*}}}*/
+
+/*Methods*/
+/*FUNCTION GaussPenta::Echo{{{1*/
+void GaussPenta::Echo(void){
+
+	printf("GaussPenta:\n");
+	printf("   numgauss: %i\n",numgauss);
+
+	if (weights){
+	 printf("   weights = ["); 
+	 for(int i=0;i<numgauss;i++) printf(" %g\n",weights[i]);
+	 printf("]\n");
+	}
+	else printf("weights = NULL\n");
+	if (coords1){
+	 printf("   coords1 = ["); 
+	 for(int i=0;i<numgauss;i++) printf(" %g\n",coords1[i]);
+	 printf("]\n");
+	}
+	else printf("coords1 = NULL\n");
+	if (coords2){
+	 printf("   coords2 = ["); 
+	 for(int i=0;i<numgauss;i++) printf(" %g\n",coords2[i]);
+	 printf("]\n");
+	}
+	else printf("coords2 = NULL\n");
+	if (coords3){
+	 printf("   coords3 = ["); 
+	 for(int i=0;i<numgauss;i++) printf(" %g\n",coords3[i]);
+	 printf("]\n");
+	}
+	else printf("coords3 = NULL\n");
+	if (coords4){
+		printf("   coords4 = ["); 
+		for(int i=0;i<numgauss;i++) printf(" %g\n",coords4[i]);
+		printf("]\n");
+	}
+	else printf("coords4 = NULL\n");
+
+	printf("   weight = %g\n",weight);
+	printf("   coord1 = %g\n",coord1);
+	printf("   coord2 = %g\n",coord2);
+	printf("   coord3 = %g\n",coord3);
+	printf("   coord4 = %g\n",coord4);
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussCenter{{{1*/
+void GaussPenta::GaussCenter(void){
+
+	/*update static arrays*/
+	coord1=ONETHIRD;
+	coord2=ONETHIRD;
+	coord3=ONETHIRD;
+	coord4=0.0;
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussPoint{{{1*/
+void GaussPenta::GaussPoint(int ig){
+
+	/*Check input in debugging mode*/
+	 _assert_(ig>=0 && ig< numgauss);
+
+	 /*update static arrays*/
+	 weight=weights[ig];
+	 coord1=coords1[ig];
+	 coord2=coords2[ig];
+	 coord3=coords3[ig];
+	 coord4=coords4[ig];
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussVertex{{{1*/
+void GaussPenta::GaussVertex(int iv){
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	switch(iv){
+		case 0:
+			coord1=1; coord2=0; coord3=0; coord4= -1;
+			break;
+		case 1:
+			coord1=0; coord2=1; coord3=0; coord4= -1;
+			break;
+		case 2:
+			coord1=0; coord2=0; coord3=1; coord4= -1;
+			break;
+		case 3:
+			coord1=1; coord2=0; coord3=0; coord4= +1;
+			break;
+		case 4:
+			coord1=0; coord2=1; coord3=0; coord4= +1;
+			break;
+		case 5:
+			coord1=0; coord2=0; coord3=1; coord4= +1;
+			break;
+		default:
+			_error_("vertex index should be in [0 5]");
+
+	}
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussFaceTria{{{1*/
+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=(double*)xmalloc(numgauss*sizeof(double));
+		for(int i=0;i<numgauss;i++) coords4[i]=-1.0;
+	}
+	else{
+		_error_("Tria not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::begin{{{1*/
+int GaussPenta::begin(void){
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+	_assert_(coords4);
+
+	/*return first gauss index*/
+	return 0;
+}
+/*}}}*/
+/*FUNCTION GaussPenta::end{{{1*/
+int GaussPenta::end(void){
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+	_assert_(coords4);
+
+	/*return last gauss index +1*/
+	return numgauss;
+}
+/*}}}*/
+/*FUNCTION GaussPenta::SynchronizeGaussTria{{{1*/
+void GaussPenta::SynchronizeGaussTria(GaussTria* gauss_tria){
+
+	gauss_tria->coord1=this->coord1;
+	gauss_tria->coord2=this->coord2;
+	gauss_tria->coord3=this->coord3;
+	gauss_tria->weight=UNDEF;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Gauss/GaussPenta.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Gauss/GaussPenta.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Gauss/GaussPenta.h	(revision 11330)
@@ -0,0 +1,51 @@
+/*!\file GaussPenta.h
+ * \brief: header file for node object
+ */
+
+#ifndef _GAUSSPENTA_H_
+#define _GAUSSPENTA_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./../../shared/shared.h"
+class GaussTria;
+/*}}}*/
+
+class GaussPenta{
+
+	private:
+		int numgauss;
+		double* weights;
+		double* coords1;
+		double* coords2;
+		double* coords3;
+		double* coords4;
+
+	public:
+		double weight;
+		double coord1;
+		double coord2;
+		double coord3;
+		double coord4;
+		
+	public:
+
+		/*GaussPenta constructors, destructors*/
+		GaussPenta();
+		GaussPenta(int order_horiz,int order_vert);
+		GaussPenta(int index1, int index2,int order);
+		GaussPenta(int index1, int index2, int index3, int order);
+		GaussPenta(int index1, int index2, int index3, int index4,int order_horiz,int order_vert);
+		~GaussPenta();
+
+		/*Methods*/
+		int  begin(void);
+		int  end(void);
+		void Echo(void);
+		void GaussPoint(int ig);
+		void GaussVertex(int iv);
+		void GaussFaceTria(int index1, int index2, int index3, int order);
+		void GaussCenter(void);
+		void SynchronizeGaussTria(GaussTria* gauss_tria);
+};
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Gauss/GaussTria.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Gauss/GaussTria.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Gauss/GaussTria.cpp	(revision 11330)
@@ -0,0 +1,278 @@
+/*!\file GaussTria.c
+ * \brief: implementation of the GaussTria object
+ */
+
+/*Include files: {{{1*/
+#include "./../objects.h"
+/*}}}*/
+
+/*GaussTria constructors and destructors:*/
+/*FUNCTION GaussTria::GaussTria() {{{1*/
+GaussTria::GaussTria(){
+
+	numgauss=-1;
+
+	weights=NULL;
+	coords1=NULL;
+	coords2=NULL;
+	coords3=NULL;
+
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussTria(int order) {{{1*/
+GaussTria::GaussTria(int order){
+
+	/*Get gauss points*/
+	GaussLegendreTria(&numgauss,&coords1,&coords2,&coords3,&weights,order);
+
+	/*Initialize static fields as undefinite*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussTria(int index1,int index2,int order) {{{1*/
+GaussTria::GaussTria(int index1,int index2,int order){
+
+	/*Intermediaties*/
+	double *seg_coords  = NULL;
+	double *seg_weights = NULL;
+	int     i,index3;
+
+	/*Get Segment gauss points*/
+	numgauss=order;
+	GaussLegendreLinear(&seg_coords,&seg_weights,numgauss);
+
+	/*Allocate GaussTria fields*/
+	coords1=(double*)xmalloc(numgauss*sizeof(double));
+	coords2=(double*)xmalloc(numgauss*sizeof(double));
+	coords3=(double*)xmalloc(numgauss*sizeof(double));
+	weights=(double*)xmalloc(numgauss*sizeof(double));
+
+	/*Reverse index1 and 2 if necessary*/
+	if (index1>index2){
+		index3=index1; index1=index2; index2=index3;
+		for(i=0;i<numgauss;i++) seg_coords[i]=-seg_coords[i];
+	}
+
+	/*Build Triangle Gauss point*/
+	if (index1==0 && index2==1){
+		for(i=0;i<numgauss;i++) coords1[i]=  0.5*(1-seg_coords[i]);
+		for(i=0;i<numgauss;i++) coords2[i]=1-0.5*(1.-seg_coords[i]);
+		for(i=0;i<numgauss;i++) coords3[i]=0;
+		for(i=0;i<numgauss;i++) weights[i]=seg_weights[i];
+	}
+	else if (index1==0 && index2==2){
+		for(i=0;i<numgauss;i++) coords1[i]=  0.5*(1-seg_coords[i]);
+		for(i=0;i<numgauss;i++) coords2[i]=0;
+		for(i=0;i<numgauss;i++) coords3[i]=1-0.5*(1.-seg_coords[i]);
+		for(i=0;i<numgauss;i++) weights[i]=seg_weights[i];
+	}
+	else if (index1==1 && index2==2){
+		for(i=0;i<numgauss;i++) coords1[i]=0;
+		for(i=0;i<numgauss;i++) coords2[i]=  0.5*(1-seg_coords[i]);
+		for(i=0;i<numgauss;i++) coords3[i]=1-0.5*(1.-seg_coords[i]);
+		for(i=0;i<numgauss;i++) weights[i]=seg_weights[i];
+	}
+	else
+	 _error_("The 2 indices provided are not supported yet (user provided %i and %i)",index1,index2);
+
+	/*Initialize static fields as undefined*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+
+	/*clean up*/
+	xfree((void**)&seg_coords);
+	xfree((void**)&seg_weights);
+}
+/*}}}*/
+/*FUNCTION GaussTria::~GaussTria(){{{1*/
+GaussTria::~GaussTria(){
+	xfree((void**)&weights);
+	xfree((void**)&coords1);
+	xfree((void**)&coords2);
+	xfree((void**)&coords3);
+}
+/*}}}*/
+
+/*Methods*/
+/*FUNCTION GaussTria::Echo{{{1*/
+void GaussTria::Echo(void){
+
+	printf("GaussTria:\n");
+	printf("   numgauss: %i\n",numgauss);
+
+	if (weights){
+	 printf("   weights = ["); 
+	 for(int i=0;i<numgauss;i++) printf(" %g\n",weights[i]);
+	 printf("]\n");
+	}
+	else printf("weights = NULL\n");
+	if (coords1){
+	 printf("   coords1 = ["); 
+	 for(int i=0;i<numgauss;i++) printf(" %g\n",coords1[i]);
+	 printf("]\n");
+	}
+	else printf("coords1 = NULL\n");
+	if (coords2){
+	 printf("   coords2 = ["); 
+	 for(int i=0;i<numgauss;i++) printf(" %g\n",coords2[i]);
+	 printf("]\n");
+	}
+	else printf("coords2 = NULL\n");
+	if (coords3){
+	 printf("   coords3 = ["); 
+	 for(int i=0;i<numgauss;i++) printf(" %g\n",coords3[i]);
+	 printf("]\n");
+	}
+	else printf("coords3 = NULL\n");
+
+	printf("   weight = %g\n",weight);
+	printf("   coord1 = %g\n",coord1);
+	printf("   coord2 = %g\n",coord2);
+	printf("   coord3 = %g\n",coord3);
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussCenter{{{1*/
+void GaussTria::GaussCenter(void){
+
+	/*update static arrays*/
+	coord1=ONETHIRD;
+	coord2=ONETHIRD;
+	coord3=ONETHIRD;
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussEdgeCenter{{{1*/
+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 %i and %i)",index1,index2);
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussPoint{{{1*/
+void GaussTria::GaussPoint(int ig){
+
+	/*Check input in debugging mode*/
+	 _assert_(ig>=0 && ig< numgauss);
+
+	 /*update static arrays*/
+	 weight=weights[ig];
+	 coord1=coords1[ig];
+	 coord2=coords2[ig];
+	 coord3=coords3[ig];
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussFromCoords{{{1*/
+void GaussTria::GaussFromCoords(double x,double y,double* xyz_list){
+
+	/*Intermediaries*/
+	double    area = 0;
+	double    x1,y1,x2,y2,x3,y3;
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	x1=*(xyz_list+3*0+0); y1=*(xyz_list+3*0+1);
+	x2=*(xyz_list+3*1+0); y2=*(xyz_list+3*1+1);
+	x3=*(xyz_list+3*2+0); y3=*(xyz_list+3*2+1);
+
+	area=(x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1)/2;
+
+	/*Get first area coordinate = det(x-x3  x2-x3 ; y-y3   y2-y3)/area*/
+	coord1=((x-x3)*(y2-y3)-(x2-x3)*(y-y3))/area;
+
+	/*Get second area coordinate = det(x1-x3  x-x3 ; y1-y3   y-y3)/area*/
+	coord2=((x1-x3)*(y-y3)-(x-x3)*(y1-y3))/area;
+
+	/*Get third  area coordinate 1-area1-area2: */
+	coord3=1-coord1-coord2;
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussVertex{{{1*/
+void GaussTria::GaussVertex(int iv){
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	switch(iv){
+		case 0:
+			coord1=1; coord2=0; coord3=0;
+			break;
+		case 1:
+			coord1=0; coord2=1; coord3=0;
+			break;
+		case 2:
+			coord1=0; coord2=0; coord3=1;
+			break;
+		default:
+			_error_("vertex index should be in [0 2]");
+
+	}
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::begin{{{1*/
+int GaussTria::begin(void){
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+
+	/*return first gauss index*/
+	return 0;
+}
+/*}}}*/
+/*FUNCTION GaussTria::end{{{1*/
+int GaussTria::end(void){
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+
+	/*return last gauss index +1*/
+	return numgauss;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Gauss/GaussTria.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Gauss/GaussTria.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Gauss/GaussTria.h	(revision 11330)
@@ -0,0 +1,46 @@
+/*!\file GaussTria.h
+ * \brief: header file for node object
+ */
+
+#ifndef _GAUSSTRIA_H_
+#define _GAUSSTRIA_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./../../shared/shared.h"
+/*}}}*/
+
+class GaussTria{
+
+	private:
+		int numgauss;
+		double* weights;
+		double* coords1;
+		double* coords2;
+		double* coords3;
+
+	public:
+		double weight;
+		double coord1;
+		double coord2;
+		double coord3;
+		
+	public:
+
+		/*GaussTria constructors, destructors*/
+		GaussTria();
+		GaussTria(int order);
+		GaussTria(int index1,int index2,int order);
+		~GaussTria();
+
+		/*Methods*/
+		int  begin(void);
+		int  end(void);
+		void Echo(void);
+		void GaussFromCoords(double x1,double y1,double* xyz_list);
+		void GaussPoint(int ig);
+		void GaussVertex(int iv);
+		void GaussCenter(void);
+		void GaussEdgeCenter(int index1,int index2);
+};
+#endif  /* _GAUSSTRIA_H_ */
Index: /issm/trunk-jpl-damage/src/c/objects/Hook.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Hook.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Hook.cpp	(revision 11330)
@@ -0,0 +1,353 @@
+/*!\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 "./objects.h"
+#include "../Container/Container.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+
+
+/*Constructor/Destructors*/
+/*FUNCTION Hook::Hook(){{{1*/
+Hook::Hook(){
+	this->num=0;
+	this->objects=NULL;
+	this->ids=NULL;
+	this->offsets=NULL;
+	return;
+}
+/*}}}*/
+/*FUNCTION Hook::Hook(int* ids, int num){{{1*/
+Hook::Hook(int* in_ids, int in_num){
+
+	/*Intermediaries*/
+	int i;
+
+	/*Get number of objects to hook*/
+	this->num=in_num;
+
+	/*Get out if num=0*/
+	if (num==0){
+		/*Empty hook*/
+		this->ids=NULL;
+		this->objects=NULL;
+		this->offsets=NULL;
+	}
+	else{
+		/*Allocate: */
+		this->objects=(Object**)xmalloc(this->num*sizeof(Object*));
+		this->ids=(int*)xmalloc(this->num*sizeof(int));
+		this->offsets=(int*)xmalloc(this->num*sizeof(int));
+
+		/*Copy ids: */
+		for (i=0;i<this->num;i++){
+			this->ids[i]=in_ids[i];
+			this->objects[i]=NULL;
+			this->offsets[i]=0;
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION Hook::~Hook(){{{1*/
+Hook::~Hook(){
+	/*deallocate: */
+	xfree((void**)&this->objects);
+	xfree((void**)&this->ids);
+	xfree((void**)&this->offsets);
+	return;
+}
+/*}}}*/
+
+/*Some of the Object functionality: */
+/*FUNCTION Hook::Echo{{{1*/
+void Hook::Echo(void){
+
+	int i;
+	if (num){
+		printf("   Hook: \n");
+		printf("      num=%i\n",this->num);
+		printf("      ids: ");
+		for (i=0;i<this->num;i++) printf("%i ",this->ids[i]);
+		printf("\n");
+		printf("      offsets: ");
+		for (i=0;i<this->num;i++) printf("%i ",this->offsets[i]);
+		printf("\n");
+	}
+	else{
+		printf("   Hook: num=0 \n");
+	}
+}
+/*}}}*/
+/*FUNCTION Hook::DeepEcho{{{1*/
+void Hook::DeepEcho(void){
+
+	int i;
+	if (num){
+		printf("   Hook: \n");
+		printf("      num=%i\n",this->num);
+		printf("      ids: ");
+		for (i=0;i<this->num;i++) printf("%i ",this->ids[i]);
+		printf("\n");
+		printf("      offsets: ");
+		for (i=0;i<this->num;i++) printf("%i ",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",i);
+				if(objects[i]) objects[i]->DeepEcho();
+				else           printf("            no object hooked yet (not configured)\n");
+			}
+		}
+	}
+	else{
+		printf("   Hook: num=0 \n");
+	}
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION Hook::Marshall{{{1*/
+void Hook::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of Hook: */
+	enum_type=HookEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*marshall Hook data: */
+	memcpy(marshalled_dataset,&num,sizeof(num));marshalled_dataset+=sizeof(num);
+	for(i=0;i<num;i++){
+		memcpy(marshalled_dataset,&this->ids[i],sizeof(int));marshalled_dataset+=sizeof(int);
+		memcpy(marshalled_dataset,&this->offsets[i],sizeof(int));marshalled_dataset+=sizeof(int);
+	}
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+/*FUNCTION Hook::MarshallSize{{{1*/
+int Hook::MarshallSize(){
+
+	return 
+		sizeof(num)+
+		num*sizeof(int)+
+		num*sizeof(int)+
+		sizeof(int); //sizeof(int) for enum type
+}
+/*}}}*/
+/*FUNCTION Hook::Demarshall{{{1*/
+void Hook::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+	int   enum_type;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of object since Hook is not directly called by DataSet: */
+	memcpy(&enum_type,marshalled_dataset,sizeof(int)); marshalled_dataset+=sizeof(int);
+
+	memcpy(&num,marshalled_dataset,sizeof(num));marshalled_dataset+=sizeof(num);
+	
+	/*allocate: */
+	if (num<0){
+		_error_("cannot demarshall Hook as num<=0");
+	}
+	else if (num==0){
+		this->ids=NULL;
+		this->offsets=NULL;
+		this->objects=NULL;
+	}
+	else{
+
+		this->ids=(int*)xmalloc(num*sizeof(int));
+		this->offsets=(int*)xmalloc(num*sizeof(int));
+
+		/*demarshall allocated ids and offsets: */
+		_assert_(num<1000);
+		for (i=0;i<num;i++){
+			memcpy(&this->ids[i],marshalled_dataset,sizeof(int));marshalled_dataset+=sizeof(int);
+			memcpy(&this->offsets[i],marshalled_dataset,sizeof(int));marshalled_dataset+=sizeof(int);
+		}
+
+		/*nullify object pointers */
+		this->objects=(Object**)xmalloc(num*sizeof(Object*));
+		for (i=0;i<num;i++){
+			this->objects[i]=NULL;
+		}
+	}
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION Hook::copy {{{1*/
+Object* Hook::copy(void){
+
+	int i;
+
+	/*output: */
+	Hook* output=NULL;
+
+	/*initalize output: */
+	output=new Hook();
+
+	/*copy in the fields: */
+	output->num=this->num;
+	if(output->num){
+		output->objects=(Object**)xmalloc(output->num*sizeof(Object*));
+		output->ids=(int*)xmalloc(output->num*sizeof(int));
+		output->offsets=(int*)xmalloc(output->num*sizeof(int));
+	}
+	
+	for(i=0;i<output->num;i++){
+		output->objects[i]=this->objects[i];
+		output->offsets[i]=this->offsets[i];
+		output->ids[i]=this->ids[i];
+	}
+
+	return (Object*)output;
+}
+/*}}}*/
+
+/*Hook management: */
+/*FUNCTION Hook::configure{{{1*/
+void Hook::configure(DataSet* dataset){
+
+	/*intermediary: */
+	Object* object=NULL;
+	int i;
+
+	/*Checks if debugging mode*/
+	_assert_(this->num==0 || this->ids!=NULL);
+
+	for(i=0;i<this->num;i++){
+
+		/*is this object id -1? If so, drop this search, it was not requested: */
+		if (this->ids[i]==-1) continue;
+
+		/*Check whether existing this->objects are correct: */
+		if(this->objects[i]){
+			if(this->objects[i]->Id()==this->ids[i]) continue; //this node is good.
+			else this->objects[i]=NULL; //this node was incorrect, reset it.
+		}
+
+		/*May be the object this->offsets into this->objects are valid?: */
+		if(this->offsets[i]!=UNDEF){
+			/* Look at the this->offsets[i]'th node in the nodes dataset. If it has the correct id, 
+			 * we are good: */
+			object=(Object*)dataset->GetObjectByOffset(this->offsets[i]);
+			if (object->Id()==this->ids[i]){
+				this->objects[i]=object;
+				continue;
+			}
+			else this->offsets[i]=UNDEF; //object offset was wrong, reset it.
+		}
+
+		/*Now, for this->objects that did not get resolved, and for which we have no offset, chase them in the dataset, by id: */
+		if(this->objects[i]==NULL){
+			this->objects[i]=(Object*)dataset->GetObjectById(this->offsets+i,this->ids[i]); //remember the offset for later on.
+			/*check the id is correct!: */
+			if (this->objects[i]->Id()!=this->ids[i]) _error_("%s%i%s%i%s"," wrong id: ",this->objects[i]->Id()," vs ",this->ids[i],"  in resolved pointer!");
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION Hook::delivers{{{1*/
+Object* Hook::delivers(void){
+	
+	/*first, check that we only have one T object in our object list: */
+	if (this->num!=1) _error_("%s%i%s\n"," trying to delivery a single hook object when hook holds ",this->num," objects");
+
+	/*check NULL: */
+	if (this->objects==NULL) _error_("hook is not pointing to any object, objects pointer is NULL");
+
+	return *objects;
+}
+
+/*}}}*/
+/*FUNCTION Hook::deliverp{{{1*/
+Object** Hook::deliverp(void){
+	return objects;
+}
+/*}}}*/
+/*FUNCTION Hook::Ids{{{1*/
+int* Hook::Ids(void){
+	return this->ids;
+}
+/*}}}*/
+/*FUNCTION Hook::GetNum{{{1*/
+int Hook::GetNum(void){
+	return this->num;
+}
+/*}}}*/
+/*FUNCTION Hook::GetObjects{{{1*/
+Object** Hook::GetObjects(void){
+	return this->objects;
+}
+/*}}}*/
+/*FUNCTION Hook::GetOffsets{{{1*/
+int* Hook::GetOffsets(void){
+	return this->offsets;
+}
+/*}}}*/
+/*FUNCTION Hook::Spawn{{{1*/
+Hook* Hook::Spawn(int* indices, int numindices){
+
+	int i;
+
+	/*output: */
+	Hook* output=NULL;
+
+	/*allocate: */
+	output=new Hook();
+
+	/*If this Hook is empty, simply return*/
+	if(this->num==0){
+		output->num=0;
+		return output;
+	}
+
+	/*Else, check that we are requesting a half of num*/
+	if (numindices>this->num) _error_("Cannot spawn hook with %i objects from a Hook of %i objects",numindices,this->num);
+
+	/*go pickup the correct objects, ids and offsets :*/
+	output->num=numindices;
+	if(output->num<1) _error_("Trying to spawn an empty ElementProperties!");
+
+	output->objects=(Object**)xmalloc(output->num*sizeof(Object*));
+	output->ids=(int*)xmalloc(output->num*sizeof(int));
+	output->offsets=(int*)xmalloc(output->num*sizeof(int));
+
+	for(i=0;i<output->num;i++){
+		output->objects[i]=this->objects[indices[i]];
+		output->ids[i]=this->ids[indices[i]];
+		output->offsets[i]=this->offsets[indices[i]];
+	}
+
+	return output;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Hook.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Hook.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Hook.h	(revision 11330)
@@ -0,0 +1,55 @@
+/*!\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:*/
+/*{{{1*/
+#include "./Object.h"
+class DataSet;
+/*}}}*/
+
+class Hook{
+
+	private: 
+
+		int	   num; //number of objects being hooked onto
+		Object**	   objects; //list of object pointers. we do not allocate objects, just a list a pointers, that will get to point to the real objects from a dataset.
+		int*   ids;     //list of object ids, to go look for them in datasets.
+		int*   offsets;  //list of object offsets into datasets, to speed up lookup.
+
+	public:
+
+		/*Hook constructors, destructors: {{{*/
+		Hook();
+		Hook(int* ids, int num);
+		~Hook();
+		/*}}}*/
+		/*Object like functionality:{{{1*/
+		void       Echo(void);
+		void       DeepEcho(void);
+		#ifdef _SERIAL_
+		void       Marshall(char** pmarshalled_dataset);
+		int        MarshallSize();
+		void       Demarshall(char** pmarshalled_dataset);
+		#endif
+		Object*    copy(void);
+		/*}}}*/
+		/*Hook management: {{{1*/
+		Object*    delivers(void); //single object deliver
+		Object**   deliverp(void); //deliver all objects
+		void       configure(DataSet* dataset);
+		Hook*      Spawn(int* indices, int numindices);
+		Object**   GetObjects(void);
+		int*       Ids(void);
+		int*       GetOffsets(void);
+		int        GetNum(void);
+		/*}}}*/
+};
+
+#endif  /* _HOOK_H_ */
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/BoolInput.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/BoolInput.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/BoolInput.cpp	(revision 11330)
@@ -0,0 +1,252 @@
+/*!\file BoolInput.c
+ * \brief: implementation of the BoolInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+/*BoolInput constructors and destructor*/
+/*FUNCTION BoolInput::BoolInput(){{{1*/
+BoolInput::BoolInput(){
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolInput::BoolInput(double* values){{{1*/
+BoolInput::BoolInput(int in_enum_type,IssmBool in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION BoolInput::~BoolInput(){{{1*/
+BoolInput::~BoolInput(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION BoolInput::Echo {{{1*/
+void BoolInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION BoolInput::DeepEcho{{{1*/
+void BoolInput::DeepEcho(void){
+
+	printf("BoolInput:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %s\n",value?"true":"false");
+}
+/*}}}*/
+/*FUNCTION BoolInput::Id{{{1*/
+int    BoolInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION BoolInput::MyRank{{{1*/
+int    BoolInput::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION BoolInput::Marshall{{{1*/
+void  BoolInput::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of BoolInput: */
+	enum_value=BoolInputEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall BoolInput data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&value,sizeof(value));marshalled_dataset+=sizeof(value);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION BoolInput::MarshallSize{{{1*/
+int   BoolInput::MarshallSize(){
+	
+	return sizeof(value)+
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION BoolInput::Demarshall{{{1*/
+void  BoolInput::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&value,marshalled_dataset,sizeof(value));marshalled_dataset+=sizeof(value);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION BoolInput::ObjectEnum{{{1*/
+int BoolInput::ObjectEnum(void){
+
+	return BoolInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::copy{{{1*/
+Object* BoolInput::copy() {
+	
+	return new BoolInput(this->enum_type,this->value);
+
+}
+/*}}}*/
+	
+/*BoolInput management*/
+/*FUNCTION BoolInput::InstanceEnum{{{1*/
+int BoolInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::SpawnTriaInput{{{1*/
+Input* BoolInput::SpawnTriaInput(int* indices){
+
+		/*output*/
+		BoolInput* outinput=new BoolInput();
+
+		/*only copy current value*/
+		outinput->enum_type=this->enum_type;
+		outinput->value=this->value;
+
+		/*Assign output*/
+		return outinput;
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::SpawnResult{{{1*/
+ElementResult* BoolInput::SpawnResult(int step, double time){
+	
+	return new BoolElementResult(this->enum_type,this->value,step,time);
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION BoolInput::GetInputValue(bool* pvalue) {{{1*/
+void BoolInput::GetInputValue(bool* pvalue){
+	*pvalue=value;
+}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(int* pvalue){{{1*/
+void BoolInput::GetInputValue(int* pvalue){_error_(" not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(double* pvalue){{{1*/
+void BoolInput::GetInputValue(double* pvalue){_error_(" not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(double* pvalue,GaussTria* gauss){{{1*/
+void BoolInput::GetInputValue(double* pvalue,GaussTria* gauss){_error_(" not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(double* pvalue,GaussPenta* gauss){{{1*/
+void BoolInput::GetInputValue(double* pvalue,GaussPenta* gauss){_error_(" not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss){{{1*/
+void BoolInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss){_error_(" not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss){{{1*/
+void BoolInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss){_error_(" not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::ChangeEnum{{{1*/
+void BoolInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION BoolInput::SquareMin{{{1*/
+void BoolInput::SquareMin(double* psquaremin, bool process_units,Parameters* parameters){
+	/*square of a bool is the bool itself: */
+	*psquaremin=value;
+}
+/*}}}*/
+/*FUNCTION BoolInput::Scale{{{1*/
+void BoolInput::Scale(double scale_factor){
+	/*a bool cannot be scaled: */
+}
+/*}}}*/
+/*FUNCTION BoolInput::AXPY{{{1*/
+void BoolInput::AXPY(Input* xinput,double 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=(bool)(this->value+scalar*xboolinput->value);
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::Constrain{{{1*/
+void BoolInput::Constrain(double cm_min, double cm_max){
+
+	if(!isnan(cm_min)) if (this->value<cm_min)this->value=cm_min;
+	if(!isnan(cm_max)) if (this->value>cm_max)this->value=cm_max;
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::Extrude{{{1*/
+void BoolInput::Extrude(void){
+
+	/*do nothing*/
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolInput::GetVectorFromInputs{{{1*/
+void BoolInput::GetVectorFromInputs(Vec vector,int* doflist){
+
+	_error_(" not supporte yet!");
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::GetValuesPtr{{{1*/
+void BoolInput::GetValuesPtr(double** pvalues,int* pnum_values){
+
+	_error_(" not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::Configure{{{1*/
+void BoolInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/BoolInput.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/BoolInput.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/BoolInput.h	(revision 11330)
@@ -0,0 +1,88 @@
+/*! \file BoolInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _BOOLINPUT_H_
+#define _BOOLINPUT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Input.h"
+#include "../../include/include.h"
+class GaussTria;
+/*}}}*/
+
+class BoolInput: public Input{
+
+	public:
+		/*just hold 3 values for 3 vertices: */
+		int    enum_type;
+		IssmBool value;
+
+		/*BoolInput constructors, destructors: {{{1*/
+		BoolInput();
+		BoolInput(int enum_type,IssmBool value);
+		~BoolInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*BoolInput management: {{{1*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, double time);
+		void Configure(Parameters* parameters);
+		void AddTimeValues(double* values,int step,double time){_error_("not supported yet");};
+		/*}}}*/
+		/*numerics: {{{1*/
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(double* pvalue);
+		void GetInputValue(double* pvalue,GaussTria* gauss);
+		void GetInputValue(double* pvalue,GaussPenta* gauss);
+		void GetInputValue(double* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(double* pvalue){_error_("not implemented yet");};
+		void GetVxStrainRate2d(double* epsilonvx,double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(double* epsilonvy,double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(double* epsilonvx,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(double* epsilonvy,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(double* epsilonvz,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(double* epsilonvx,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(double* epsilonvy,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+		void SquareMin(double* psquaremin, bool process_units,Parameters* parameters);
+		void ConstrainMin(double minimum){_error_("not implemented yet");};
+		double InfinityNorm(void){_error_("InfinityNorm not implemented for booleans");};
+		double Max(void){_error_("Max not implemented for booleans");};
+		double MaxAbs(void){_error_("Max not implemented for booleans");};
+		double Min(void){_error_("Min not implemented for booleans");};
+		double MinAbs(void){_error_("Min not implemented for booleans");};
+		void Scale(double scale_factor);
+		void ArtificialNoise(double min,double max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,double scalar);
+		void Constrain(double cm_min, double cm_max);
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vec vector,int* doflist);
+		void GetValuesPtr(double** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _BOOLINPUT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/ControlInput.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/ControlInput.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/ControlInput.cpp	(revision 11330)
@@ -0,0 +1,460 @@
+/*!\file ControlInput.c
+ * \brief: implementation of the ControlInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+/*ControlInput constructors and destructor*/
+/*FUNCTION ControlInput::ControlInput(){{{1*/
+ControlInput::ControlInput(){
+	control_id  = 0;
+	values      = NULL;
+	savedvalues = NULL;
+	minvalues   = NULL;
+	maxvalues   = NULL;
+	gradient    = NULL;
+}
+/*}}}*/
+/*FUNCTION ControlInput::ControlInput(int enum_type,int enum_input,double* pvalues,double* pmin,double* pmax,int id){{{1*/
+ControlInput::ControlInput(int in_enum_type,int enum_input,double* pvalues,double* pmin,double* pmax,int id){
+
+	control_id=id;
+	enum_type=in_enum_type;
+
+	switch(enum_input){
+		case TriaP1InputEnum:
+			values     =new TriaP1Input(enum_type,pvalues);
+			savedvalues=new TriaP1Input(enum_type,pvalues);
+			minvalues  =new TriaP1Input(enum_type,pmin);
+			maxvalues  =new TriaP1Input(enum_type,pmax);
+			break;
+		case PentaP1InputEnum:
+			values     =new PentaP1Input(enum_type,pvalues);
+			savedvalues=new PentaP1Input(enum_type,pvalues);
+			minvalues  =new PentaP1Input(enum_type,pmin);
+			maxvalues  =new PentaP1Input(enum_type,pmax);
+			break;
+		default:
+			_error_("Input of Enum %s not supported yet by ControlInput",EnumToStringx(enum_input));
+	}
+	gradient   =NULL;
+}
+/*}}}*/
+/*FUNCTION ControlInput::~ControlInput(){{{1*/
+ControlInput::~ControlInput(){
+	delete values;
+	delete savedvalues;
+	delete minvalues;
+	delete maxvalues;
+	delete gradient;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+		/*FUNCTION ControlInput::Echo {{{1*/
+void ControlInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION ControlInput::DeepEcho{{{1*/
+void ControlInput::DeepEcho(void){
+
+	printf("ControlInput:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("---values: \n");     if (values)      values->Echo();
+	printf("---savedvalues: \n");if (savedvalues) savedvalues->Echo();
+	printf("---minvalues: \n");  if (minvalues)   minvalues->Echo();
+	printf("---maxvalues: \n");  if (maxvalues)   maxvalues->Echo();
+	printf("---gradient: \n");   if (gradient)    gradient->Echo();
+}
+/*}}}*/
+/*FUNCTION ControlInput::Id{{{1*/
+int    ControlInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION ControlInput::MyRank{{{1*/
+int    ControlInput::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION ControlInput::Marshall{{{1*/
+void  ControlInput::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+	int   flag;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of ControlInput: */
+	enum_value=ControlInputEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall enum_type: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&control_id,sizeof(control_id));marshalled_dataset+=sizeof(control_id);
+
+	/*marshal values*/
+	if(!values){
+		flag=0;
+		memcpy(marshalled_dataset,&flag,sizeof(flag));marshalled_dataset+=sizeof(flag);
+	}
+	else{
+		flag=1;
+		memcpy(marshalled_dataset,&flag,sizeof(flag));marshalled_dataset+=sizeof(flag);
+		this->values->Marshall(&marshalled_dataset);
+	}
+
+	/*marshal savedvalues*/
+	if(!savedvalues){
+		flag=0;
+		memcpy(marshalled_dataset,&flag,sizeof(flag));marshalled_dataset+=sizeof(flag);
+	}
+	else{
+		flag=1;
+		memcpy(marshalled_dataset,&flag,sizeof(flag));marshalled_dataset+=sizeof(flag);
+		this->savedvalues->Marshall(&marshalled_dataset);
+	}
+
+	/*marshal minvalues*/
+	if(!minvalues){
+		flag=0;
+		memcpy(marshalled_dataset,&flag,sizeof(flag));marshalled_dataset+=sizeof(flag);
+	}
+	else{
+		flag=1;
+		memcpy(marshalled_dataset,&flag,sizeof(flag));marshalled_dataset+=sizeof(flag);
+		this->minvalues->Marshall(&marshalled_dataset);
+	}
+
+	/*marshal maxvalues*/
+	if(!maxvalues){
+		flag=0;
+		memcpy(marshalled_dataset,&flag,sizeof(flag));marshalled_dataset+=sizeof(flag);
+	}
+	else{
+		flag=1;
+		memcpy(marshalled_dataset,&flag,sizeof(flag));marshalled_dataset+=sizeof(flag);
+		this->maxvalues->Marshall(&marshalled_dataset);
+	}
+
+	/*marshal gradient*/
+	if(!gradient){
+		flag=0;
+		memcpy(marshalled_dataset,&flag,sizeof(flag));marshalled_dataset+=sizeof(flag);
+	}
+	else{
+		flag=1;
+		memcpy(marshalled_dataset,&flag,sizeof(flag));marshalled_dataset+=sizeof(flag);
+		this->gradient->Marshall(&marshalled_dataset);
+	}
+
+	/*clean up and assign output pointer*/
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION ControlInput::MarshallSize{{{1*/
+int   ControlInput::MarshallSize(){
+	
+	int size=0;
+
+	size=sizeof(enum_type)+
+	  +sizeof(control_id)
+	  +5*sizeof(int) //5 flags
+	  +sizeof(int); //sizeof(int) for enum value
+
+	if(values)     size+=values->MarshallSize();
+	if(savedvalues)size+=savedvalues->MarshallSize();
+	if(minvalues)size+=minvalues->MarshallSize();
+	if(maxvalues)size+=maxvalues->MarshallSize();
+	if(gradient)   size+=gradient->MarshallSize();
+	return size;
+}
+/*}}}*/
+/*FUNCTION ControlInput::Demarshall{{{1*/
+void  ControlInput::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   flag,input_enum_type;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&control_id,marshalled_dataset,sizeof(control_id));marshalled_dataset+=sizeof(control_id);
+
+	/*Demarshal values*/
+	memcpy(&flag,marshalled_dataset,sizeof(int));marshalled_dataset+=sizeof(int);
+	if(flag){
+		memcpy(&input_enum_type,marshalled_dataset,sizeof(int)); marshalled_dataset+=sizeof(int);
+		if(input_enum_type==PentaP1InputEnum){
+			values=new PentaP1Input();
+			values->Demarshall(&marshalled_dataset);
+		}
+		else if(input_enum_type==TriaP1InputEnum){
+			values=new TriaP1Input();
+			values->Demarshall(&marshalled_dataset);
+		}
+		else _error_("Not supported yet");
+	}
+	else{
+		values=NULL;
+	}
+
+	/*Demarshal savedvalues*/
+	memcpy(&flag,marshalled_dataset,sizeof(int));marshalled_dataset+=sizeof(int);
+	if(flag){
+		memcpy(&input_enum_type,marshalled_dataset,sizeof(int)); marshalled_dataset+=sizeof(int);
+		if(input_enum_type==PentaP1InputEnum){
+			savedvalues=new PentaP1Input();
+			savedvalues->Demarshall(&marshalled_dataset);
+		}
+		else if(input_enum_type==TriaP1InputEnum){
+			savedvalues=new TriaP1Input();
+			savedvalues->Demarshall(&marshalled_dataset);
+		}
+		else _error_("Not supported yet");
+	}
+	else{
+		savedvalues=NULL;
+	}
+
+	/*Demarshal minvalues*/
+	memcpy(&flag,marshalled_dataset,sizeof(int));marshalled_dataset+=sizeof(int);
+	if(flag){
+		memcpy(&input_enum_type,marshalled_dataset,sizeof(int)); marshalled_dataset+=sizeof(int);
+		if(input_enum_type==PentaP1InputEnum){
+			minvalues=new PentaP1Input();
+			minvalues->Demarshall(&marshalled_dataset);
+		}
+		else if(input_enum_type==TriaP1InputEnum){
+			minvalues=new TriaP1Input();
+			minvalues->Demarshall(&marshalled_dataset);
+		}
+		else _error_("Not supported yet");
+	}
+	else{
+		minvalues=NULL;
+	}
+
+	/*Demarshal maxvalues*/
+	memcpy(&flag,marshalled_dataset,sizeof(int));marshalled_dataset+=sizeof(int);
+	if(flag){
+		memcpy(&input_enum_type,marshalled_dataset,sizeof(int)); marshalled_dataset+=sizeof(int);
+		if(input_enum_type==PentaP1InputEnum){
+			maxvalues=new PentaP1Input();
+			maxvalues->Demarshall(&marshalled_dataset);
+		}
+		else if(input_enum_type==TriaP1InputEnum){
+			maxvalues=new TriaP1Input();
+			maxvalues->Demarshall(&marshalled_dataset);
+		}
+		else _error_("Not supported yet");
+	}
+	else{
+		maxvalues=NULL;
+	}
+
+	/*Demarshal gradient*/
+	memcpy(&flag,marshalled_dataset,sizeof(int));marshalled_dataset+=sizeof(int);
+	if(flag){
+		memcpy(&input_enum_type,marshalled_dataset,sizeof(int)); marshalled_dataset+=sizeof(int);
+		if(input_enum_type==PentaP1InputEnum){
+			gradient=new PentaP1Input();
+			gradient->Demarshall(&marshalled_dataset);
+		}
+		else if(input_enum_type==TriaP1InputEnum){
+			gradient=new TriaP1Input();
+			gradient->Demarshall(&marshalled_dataset);
+		}
+		else _error_("Not supported yet");
+	}
+	else{
+		gradient=NULL;
+	}
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION ControlInput::ObjectEnum{{{1*/
+int ControlInput::ObjectEnum(void){
+
+	return ControlInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION ControlInput::copy{{{1*/
+Object* ControlInput::copy() {
+	
+	ControlInput* output=NULL;
+
+	output = new ControlInput();
+	output->enum_type=this->enum_type;
+	output->control_id=this->control_id;
+
+	if(values)      output->values=(Input*)this->values->copy();
+	if(savedvalues) output->savedvalues=(Input*)this->savedvalues->copy();
+	if(minvalues)   output->minvalues=(Input*)this->minvalues->copy();
+	if(maxvalues)   output->maxvalues=(Input*)this->maxvalues->copy();
+	if(gradient)    output->gradient=(Input*)this->gradient->copy();
+
+	return output;
+}
+/*}}}*/
+	
+/*ControlInput management*/
+/*FUNCTION ControlInput::InstanceEnum{{{1*/
+int ControlInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION ControlInput::Constrain(){{{1*/
+void ControlInput::Constrain(void){
+
+	Input* newvalues=NULL;
+
+	newvalues=this->values->PointwiseMin(maxvalues);
+	delete values; this->values=newvalues;
+	newvalues=this->values->PointwiseMax(minvalues);
+	delete values; this->values=newvalues;
+}/*}}}*/
+/*FUNCTION ControlInput::Constrain(double min, double max){{{1*/
+void ControlInput::Constrain(double min, double max){
+	   values->Constrain(min,max);
+}/*}}}*/
+/*FUNCTION ControlInput::Extrude{{{1*/
+void ControlInput::Extrude(void){
+	values->Extrude();
+	savedvalues->Extrude();
+	//gradient->Extrude();
+}/*}}}*/
+/*FUNCTION ControlInput::GetGradient{{{1*/
+void ControlInput::GetGradient(Vec gradient_vec,int* doflist){
+	if(gradient) gradient->GetVectorFromInputs(gradient_vec,doflist);
+}/*}}}*/
+/*FUNCTION ControlInput::ScaleGradient{{{1*/
+void ControlInput::ScaleGradient(double scaling_factor){
+	if(!gradient) _error_("Gradient of ControlInput %s not found",EnumToStringx(enum_type));
+	gradient->Scale(scaling_factor);
+}/*}}}*/
+/*FUNCTION ControlInput::SetGradient{{{1*/
+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 %i was requested). EnumDefinitions.h needs to be updated.",this->control_id);
+	}
+
+	/*Delete old gradient and assign new gradient*/
+	if(gradient) delete gradient;
+	gradient=gradient_in;
+
+}/*}}}*/
+/*FUNCTION ControlInput::SpawnResult{{{1*/
+ElementResult* ControlInput::SpawnResult(int step, double time){
+	return savedvalues->SpawnResult(step,time);
+}/*}}}*/
+/*FUNCTION ControlInput::SpawnTriaInput{{{1*/
+Input* ControlInput::SpawnTriaInput(int* indices){
+	return values->SpawnTriaInput(indices);
+}/*}}}*/
+/*FUNCTION ControlInput::SpawnGradient{{{1*/
+ElementResult* ControlInput::SpawnGradient(int step, double time){
+	return gradient->SpawnResult(step,time);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(bool* pvalue){{{1*/
+void ControlInput::GetVectorFromInputs(Vec vector,int* doflist){
+	values->GetVectorFromInputs(vector,doflist);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputAverage(double* pvalue){{{1*/
+void ControlInput::GetInputAverage(double* pvalue){
+	values->GetInputAverage(pvalue);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(bool* pvalue){{{1*/
+void ControlInput::GetInputValue(bool* pvalue){
+	values->GetInputValue(pvalue);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(int* pvalue){{{1*/
+void ControlInput::GetInputValue(int* pvalue){
+	values->GetInputValue(pvalue);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(double* pvalue){{{1*/
+void ControlInput::GetInputValue(double* pvalue){
+	values->GetInputValue(pvalue);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(double* pvalue){{{1*/
+void ControlInput::GetInputValue(double* pvalue,GaussTria* gauss){
+	values->GetInputValue(pvalue,gauss);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(double* pvalue){{{1*/
+void ControlInput::GetInputValue(double* pvalue,GaussPenta* gauss){
+	values->GetInputValue(pvalue,gauss);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss){{{1*/
+void ControlInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss){
+	values->GetInputDerivativeValue(derivativevalues,xyz_list,gauss);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss){{{1*/
+void ControlInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss){
+	values->GetInputDerivativeValue(derivativevalues,xyz_list,gauss);
+}/*}}}*/
+/*FUNCTION ControlInput::SaveValue{{{1*/
+void ControlInput::SaveValue(void){
+	if(!values) _error_("Values of %s not found",EnumToStringx(this->enum_type));
+
+	if(savedvalues) delete this->savedvalues;
+	this->savedvalues=(Input*)this->values->copy();
+}/*}}}*/
+/*FUNCTION ControlInput::UpdateValue{{{1*/
+void ControlInput::UpdateValue(double scalar){
+	if(!gradient)    _error_("Gradient of %s not found",EnumToStringx(this->enum_type));
+	if(!savedvalues) _error_("Values of %s not found",EnumToStringx(this->enum_type));
+
+	if(values) delete this->values;
+	this->values=(Input*)this->savedvalues->copy();
+	this->values->AXPY(gradient,scalar);
+}/*}}}*/
+/*FUNCTION ControlInput::VerticallyIntegrate{{{1*/
+void ControlInput::VerticallyIntegrate(Input* thickness_input){
+	values->VerticallyIntegrate(thickness_input);
+}/*}}}*/
+/*FUNCTION ControlInput::Configure{{{1*/
+void ControlInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/ControlInput.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/ControlInput.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/ControlInput.h	(revision 11330)
@@ -0,0 +1,99 @@
+/*! \file ControlInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _CONTROLINPUT_H_
+#define _CONTROLINPUT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Input.h"
+#include "../../include/include.h"
+class GaussTria;
+/*}}}*/
+
+class ControlInput: public Input{
+
+	public:
+		int    enum_type;
+		int    control_id;
+		Input* values;
+		Input* savedvalues;
+		Input* minvalues;
+		Input* maxvalues;
+		Input* gradient;
+
+		/*ControlInput constructors, destructors: {{{1*/
+		ControlInput();
+		ControlInput(int enum_type,int enum_input,double* pvalues,double* pmin,double* pmax,int id);
+		~ControlInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ControlInput management: {{{1*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, double time);
+		void AddTimeValues(double* values,int step,double time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{1*/
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(double* pvalue);
+		void GetInputValue(double* pvalue,GaussTria* gauss);
+		void GetInputValue(double* pvalue,GaussPenta* gauss);
+		void GetInputValue(double* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(double* pvalue);
+		void GetVxStrainRate2d(double* epsilonvx,double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(double* epsilonvy,double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(double* epsilonvx,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(double* epsilonvy,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(double* epsilonvz,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(double* epsilonvx,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(double* epsilonvy,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
+		void SquareMin(double* psquaremin, bool process_units,Parameters* parameters){_error_("not implemented yet");};
+		void ConstrainMin(double minimum){_error_("not implemented yet");};
+		void Scale(double scale_factor){_error_("not implemented yet");};
+		void ArtificialNoise(double min,double max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,double scalar){_error_("not implemented yet");};
+		void Constrain(void);
+		void Constrain(double min,double max);
+		double InfinityNorm(void){_error_("not implemented yet");};
+		double Max(void){_error_("not implemented yet");};
+		double MaxAbs(void){_error_("not implemented yet");};
+		double Min(void){_error_("not implemented yet");};
+		double MinAbs(void){_error_("not implemented yet");};
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vec vector,int* doflist);
+		void GetValuesPtr(double** pvalues,int* pnum_values){_error_("not implemented yet");};
+		ElementResult* SpawnGradient(int step, double time);
+		void GetGradient(Vec gradient_vec,int* doflist);
+		void ScaleGradient(double scale);
+		void SetGradient(Input* gradient_in);
+		void UpdateValue(double scalar);
+		void SaveValue(void);
+		/*}}}*/
+
+};
+#endif  /* _CONTROLINPUT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/DatasetInput.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/DatasetInput.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/DatasetInput.cpp	(revision 11330)
@@ -0,0 +1,186 @@
+/*!\file DatasetInput.c
+ * \brief: implementation of the datasetinput object
+ */
+/*Headers{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*DatasetInput constructors and destructor*/
+/*FUNCTION DatasetInput::DatasetInput(){{{1*/
+DatasetInput::DatasetInput(){
+	enum_type=UNDEF;
+	inputs=NULL;
+}
+/*}}}*/
+/*FUNCTION DatasetInput::DatasetInput(int in_enum_type) {{{1*/
+DatasetInput::DatasetInput(int in_enum_type){
+
+	enum_type  = in_enum_type;
+	inputs     = new Inputs();
+}
+/*}}}*/
+/*FUNCTION DatasetInput::~DatasetInput(){{{1*/
+DatasetInput::~DatasetInput(){
+	delete inputs;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+		/*FUNCTION DatasetInput::Echo {{{1*/
+void DatasetInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION DatasetInput::DeepEcho{{{1*/
+void DatasetInput::DeepEcho(void){
+
+	printf("DatasetInput:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("---inputs: \n"); inputs->Echo();
+}
+/*}}}*/
+/*FUNCTION DatasetInput::Id{{{1*/
+int    DatasetInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DatasetInput::MyRank{{{1*/
+int    DatasetInput::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION DatasetInput::Marshall{{{1*/
+void  DatasetInput::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	char* marshalled_inputs=NULL;
+	int   marshalled_inputs_size;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of DatasetInput: */
+	enum_value=DatasetInputEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall enum_type: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+
+	/*marshal inputs*/
+	marshalled_inputs_size=inputs->MarshallSize();
+	marshalled_inputs=inputs->Marshall();
+	memcpy(marshalled_dataset,marshalled_inputs,marshalled_inputs_size*sizeof(char));
+	marshalled_dataset+=marshalled_inputs_size;
+
+	/*clean up and assign output pointer*/
+	xfree((void**)&marshalled_inputs);
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION DatasetInput::MarshallSize{{{1*/
+int   DatasetInput::MarshallSize(){
+	
+	int size=0;
+
+	size=sizeof(enum_type)+
+	  +inputs->MarshallSize()
+	  +sizeof(int); //sizeof(int) for enum value
+
+	return size;
+}
+/*}}}*/
+/*FUNCTION DatasetInput::Demarshall{{{1*/
+void  DatasetInput::Demarshall(char** pmarshalled_dataset){
+	char* marshalled_dataset=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+
+	/*Demarshal values*/
+	inputs=(Inputs*)DataSetDemarshallRaw(&marshalled_dataset); 
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION DatasetInput::ObjectEnum{{{1*/
+int DatasetInput::ObjectEnum(void){
+
+	return DatasetInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION DatasetInput::copy{{{1*/
+Object* DatasetInput::copy() {
+	
+	DatasetInput* output=NULL;
+
+	output = new DatasetInput();
+	output->enum_type=this->enum_type;
+	output->inputs=(Inputs*)this->inputs->Copy();
+
+	return output;
+}
+/*}}}*/
+/*FUNCTION DatasetInput::SpawnTriaInput{{{1*/
+Input* DatasetInput::SpawnTriaInput(int* indices){
+
+	/*output*/
+	DatasetInput* outinput=NULL;
+
+	/*Create new Datasetinput (copy of current input)*/
+	outinput=new DatasetInput();
+	outinput->enum_type=this->enum_type;
+	outinput->inputs=(Inputs*)this->inputs->SpawnTriaInputs(indices);
+
+	/*Assign output*/
+	return outinput;
+}
+/*}}}*/
+	
+/*DatasetInput management*/
+/*FUNCTION DatasetInput::InstanceEnum{{{1*/
+int DatasetInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION DatasetInput::Configure{{{1*/
+void DatasetInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
+/*FUNCTION DatasetInput::GetInputValue(double* pvalue,GaussTria* gauss,int index){{{1*/
+void DatasetInput::GetInputValue(double* pvalue,GaussTria* gauss,int index){
+
+	/*Get requested input within dataset*/
+	if(index<0 || index > inputs->Size()-1) _error_("index requested (%i) exceeds dataset size (%i)",index,inputs->Size());
+	Input* input=(Input*)this->inputs->GetObjectByOffset(index);
+	
+	input->GetInputValue(pvalue,gauss);
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/DatasetInput.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/DatasetInput.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/DatasetInput.h	(revision 11330)
@@ -0,0 +1,95 @@
+/*! \file DatasetInput.h 
+ *  \brief: header file for datasetinput object
+ */
+
+
+#ifndef _DATASETINPUT_H_
+#define _DATASETINPUT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Input.h"
+#include "../../include/include.h"
+class GaussTria;
+/*}}}*/
+
+class DatasetInput: public Input{
+
+	public:
+		int    enum_type;
+
+		Inputs*     inputs;
+
+		/*DatasetInput constructors, destructors: {{{1*/
+		DatasetInput();
+		DatasetInput(int enum_type);
+		~DatasetInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id();
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*DatasetInput management: {{{1*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, double time){_error_("not implemented yet");};
+		void AddTimeValues(double* values,int step,double time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numeriics: {{{1*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussTria* gauss ,int index);
+		void GetInputValue(double* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputAverage(double* pvalue){_error_("not implemented yet");};
+		void GetVxStrainRate2d(double* epsilonvx,double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(double* epsilonvy,double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(double* epsilonvx,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(double* epsilonvy,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(double* epsilonvz,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(double* epsilonvx,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(double* epsilonvy,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
+		void SquareMin(double* psquaremin, bool process_units,Parameters* parameters){_error_("not implemented yet");};
+		void ConstrainMin(double minimum){_error_("not implemented yet");};
+		void Scale(double scale_factor){_error_("not implemented yet");};
+		void ArtificialNoise(double min,double max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,double scalar){_error_("not implemented yet");};
+		void Constrain(void){_error_("not implemented yet");};
+		void Constrain(double min,double max){_error_("not implemented yet");};
+		double InfinityNorm(void){_error_("not implemented yet");};
+		double Max(void){_error_("not implemented yet");};
+		double MaxAbs(void){_error_("not implemented yet");};
+		double Min(void){_error_("not implemented yet");};
+		double MinAbs(void){_error_("not implemented yet");};
+		void Extrude(void){_error_("not implemented yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not implemented yet");};
+		void GetVectorFromInputs(Vec vector,int* doflist){_error_("not implemented yet");};
+		void GetValuesPtr(double** pvalues,int* pnum_values){_error_("not implemented yet");};
+		ElementResult* SpawnGradient(int step, double time){_error_("not implemented yet");};
+		void GetGradient(Vec gradient_vec,int* doflist){_error_("not implemented yet");};
+		void ScaleGradient(double scale){_error_("not implemented yet");};
+		void SetGradient(Input* gradient_in){_error_("not implemented yet");};
+		void UpdateValue(double scalar){_error_("not implemented yet");};
+		void SaveValue(void){_error_("not implemented yet");};
+		/*}}}*/
+
+};
+#endif  /* _DATASETINPUT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/DoubleInput.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/DoubleInput.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/DoubleInput.cpp	(revision 11330)
@@ -0,0 +1,418 @@
+/*!\file DoubleInput.c
+ * \brief: implementation of the DoubleInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+/*DoubleInput constructors and destructor*/
+/*FUNCTION DoubleInput::DoubleInput(){{{1*/
+DoubleInput::DoubleInput(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::DoubleInput(double value){{{1*/
+DoubleInput::DoubleInput(int in_enum_type,IssmDouble in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::~DoubleInput(){{{1*/
+DoubleInput::~DoubleInput(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+		/*FUNCTION DoubleInput::Echo {{{1*/
+void DoubleInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION DoubleInput::DeepEcho{{{1*/
+void DoubleInput::DeepEcho(void){
+
+	printf("DoubleInput:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %g\n",this->value);
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Id{{{1*/
+int    DoubleInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleInput::MyRank{{{1*/
+int    DoubleInput::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION DoubleInput::Marshall{{{1*/
+void  DoubleInput::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of DoubleInput: */
+	enum_value=DoubleInputEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall DoubleInput data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&value,sizeof(value));marshalled_dataset+=sizeof(value);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::MarshallSize{{{1*/
+int   DoubleInput::MarshallSize(){
+	
+	return sizeof(value)+
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Demarshall{{{1*/
+void  DoubleInput::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&value,marshalled_dataset,sizeof(value));marshalled_dataset+=sizeof(value);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION DoubleInput::ObjectEnum{{{1*/
+int DoubleInput::ObjectEnum(void){
+
+	return DoubleInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::copy{{{1*/
+Object* DoubleInput::copy() {
+	
+	return new DoubleInput(this->enum_type,this->value);
+
+}
+/*}}}*/
+	
+/*DoubleInput management*/
+/*FUNCTION DoubleInput::InstanceEnum{{{1*/
+int DoubleInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::SpawnTriaInput{{{1*/
+Input* DoubleInput::SpawnTriaInput(int* indices){
+
+	/*output*/
+	DoubleInput* outinput=new DoubleInput();
+
+	/*only copy current value*/
+	outinput->enum_type=this->enum_type;
+	outinput->value=this->value;
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::SpawnResult{{{1*/
+ElementResult* DoubleInput::SpawnResult(int step, double time){
+
+	return new DoubleElementResult(this->enum_type,this->value,step,time);
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION DoubleInput::GetInputValue(bool* pvalue) {{{1*/
+void DoubleInput::GetInputValue(bool* pvalue){
+#ifdef _SERIAL_
+	*pvalue=(bool)value;
+#else
+	_error_("Double input of enum %s cannot return a boolean",EnumToStringx(enum_type));
+#endif
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputValue(int* pvalue){{{1*/
+void DoubleInput::GetInputValue(int* pvalue){
+#ifdef _SERIAL_
+	*pvalue=(int)value;
+#else
+	_error_("Double input of enum %i (%s) cannot return an integer",enum_type,EnumToStringx(enum_type));
+#endif
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputValue(double* pvalue){{{1*/
+void DoubleInput::GetInputValue(double* pvalue){
+
+	/*return value*/
+	*pvalue=value;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputValue(double* pvalue,GaussTria* gauss){{{1*/
+void DoubleInput::GetInputValue(double* pvalue,GaussTria* gauss){*pvalue=this->value;}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputValue(double* pvalue,GaussPenta* gauss){{{1*/
+void DoubleInput::GetInputValue(double* pvalue,GaussPenta* gauss){*pvalue=this->value;}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss){{{1*/
+void DoubleInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss){_error_(" not supported yet!");}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss){{{1*/
+void DoubleInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss){_error_(" not supported yet!");}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVxStrainRate2d(double* epsilonvx,double* xyz_list, GaussTria* gauss){{{1*/
+void DoubleInput::GetVxStrainRate2d(double* epsilonvx,double* xyz_list, GaussTria* gauss){
+	/*Epsilon is zero as vx is constant over the element*/
+	for(int i=0;i<3;i++) epsilonvx[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVyStrainRate2d(double* epsilonvy,double* xyz_list, GaussTria* gauss){{{1*/
+void DoubleInput::GetVyStrainRate2d(double* epsilonvy,double* xyz_list, GaussTria* gauss){
+	/*Epsilon is zero as vy is constant over the element*/
+	for(int i=0;i<3;i++) epsilonvy[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVxStrainRate3d(double* epsilonvx,double* xyz_list, GaussPenta* gauss){{{1*/
+void DoubleInput::GetVxStrainRate3d(double* epsilonvx,double* xyz_list, GaussPenta* gauss){
+	/*Epsilon is zero as vx is constant over the element*/
+	for(int i=0;i<6;i++) epsilonvx[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVyStrainRate3d(double* epsilonvy,double* xyz_list, GaussPenta* gauss){{{1*/
+void DoubleInput::GetVyStrainRate3d(double* epsilonvy,double* xyz_list, GaussPenta* gauss){
+	/*Epsilon is zero as vy is constant over the element*/
+	for(int i=0;i<6;i++) epsilonvy[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVzStrainRate3d(double* epsilonvz,double* xyz_list, GaussPenta* gauss){{{1*/
+void DoubleInput::GetVzStrainRate3d(double* epsilonvz,double* xyz_list, GaussPenta* gauss){
+	/*Epsilon is zero as vz is constant over the element*/
+	for(int i=0;i<6;i++) epsilonvz[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVxStrainRate3dPattyn(double* epsilonvx,double* xyz_list, GaussPenta* gauss){{{1*/
+void DoubleInput::GetVxStrainRate3dPattyn(double* epsilonvx,double* xyz_list, GaussPenta* gauss){
+	/*Epsilon is zero as vx is constant over the element*/
+	for(int i=0;i<5;i++) epsilonvx[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVyStrainRate3dPattyn(double* epsilonvy,double* xyz_list, GaussPenta* gauss){{{1*/
+void DoubleInput::GetVyStrainRate3dPattyn(double* epsilonvy,double* xyz_list, GaussPenta* gauss){
+	/*Epsilon is zero as vy is constant over the element*/
+	for(int i=0;i<5;i++) epsilonvy[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::ChangeEnum{{{1*/
+void DoubleInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::SquareMin{{{1*/
+void DoubleInput::SquareMin(double* psquaremin, bool process_units,Parameters* parameters){
+
+	/*square min of a double is the square of the double itself: */
+	*psquaremin=pow(value,2);
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Scale{{{1*/
+void DoubleInput::Scale(double scale_factor){
+	value=value*scale_factor;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::ConstrainMin{{{1*/
+void DoubleInput::ConstrainMin(double minimum){
+	if (value<minimum) value=minimum;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::AXPY{{{1*/
+void DoubleInput::AXPY(Input* xinput,double scalar){
+
+	DoubleInput*  xdoubleinput=NULL;
+
+	/*xinput is of the same type, so cast it: */
+	xdoubleinput=(DoubleInput*)xinput;
+
+	/*Carry out the AXPY operation depending on type:*/
+	switch(xinput->ObjectEnum()){
+
+		case DoubleInputEnum:
+			this->value=this->value+scalar*xdoubleinput->value;
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Constrain{{{1*/
+void DoubleInput::Constrain(double cm_min, double cm_max){
+
+	if(!isnan(cm_min)) if (this->value<cm_min)this->value=cm_min;
+	if(!isnan(cm_max)) if (this->value>cm_max)this->value=cm_max;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Max{{{1*/
+double DoubleInput::Max(void){
+	return this->value;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::MaxAbs{{{1*/
+double DoubleInput::MaxAbs(void){
+	return fabs(this->value);
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Min{{{1*/
+double DoubleInput::Min(void){
+	return this->value;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::MinAbs{{{1*/
+double DoubleInput::MinAbs(void){
+	return fabs(this->value);
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVectorFromInputs{{{1*/
+void DoubleInput::GetVectorFromInputs(Vec vector,int* doflist){
+
+	_error_(" not supporte yet!");
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetValuesPtr{{{1*/
+void DoubleInput::GetValuesPtr(double** pvalues,int* pnum_values){
+
+	_error_(" not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputAverage{{{1*/
+void DoubleInput::GetInputAverage(double* pvalue){
+	*pvalue=value;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::VerticallyIntegrate{{{1*/
+void DoubleInput::VerticallyIntegrate(Input* thickness_input){
+
+	/*Intermediaries*/
+	double thickness_value;
+
+	/*Check that input provided is a thickness*/
+	if (thickness_input->InstanceEnum()!=ThicknessEnum) _error_("Input provided is not a Thickness (enum_type is %s)",EnumToStringx(thickness_input->InstanceEnum()));
+
+	/*vertically integrate depending on type:*/
+	switch(thickness_input->ObjectEnum()){
+
+		case PentaP1InputEnum:
+			thickness_input->GetInputAverage(&thickness_value);
+			this->value=this->value*thickness_value;
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleInput::PointwiseDivide{{{1*/
+Input* DoubleInput::PointwiseDivide(Input* inputB){
+
+	/*Ouput*/
+	DoubleInput* outinput=NULL;
+
+	/*Intermediaries*/
+	double       Bvalue;
+
+	/*Check that inputB is of the same type*/
+	inputB->GetInputAverage(&Bvalue);
+
+	/*Create new DoubleInput*/
+	outinput=new DoubleInput(this->enum_type,this->value/Bvalue);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::PointwiseMin{{{1*/
+Input* DoubleInput::PointwiseMin(Input* input){
+
+	/*Ouput*/
+	DoubleInput* outinput=NULL;
+
+	/*Intermediaries*/
+	double       min;
+
+	/*Check that inputB is of the same type*/
+	if (input->Min() < this->Min()) min=input->Min();
+	else min=this->Min();
+
+	/*Create new DoubleInput*/
+	outinput=new DoubleInput(this->enum_type,min);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::PointwiseMax{{{1*/
+Input* DoubleInput::PointwiseMax(Input* input){
+
+	/*Ouput*/
+	DoubleInput* outinput=NULL;
+
+	/*Intermediaries*/
+	double       max;
+
+	/*Check that inputB is of the same type*/
+	if (input->Max() > this->Max()) max=input->Max();
+	else max=this->Max();
+
+	/*Create new DoubleInput*/
+	outinput=new DoubleInput(this->enum_type,max);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Configure{{{1*/
+void DoubleInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/DoubleInput.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/DoubleInput.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/DoubleInput.h	(revision 11330)
@@ -0,0 +1,87 @@
+/*! \file DoubleInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _DOUBLEINPUT_H_
+#define _DOUBLEINPUT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Input.h"
+#include "../../include/include.h"
+class GaussTria;
+/*}}}*/
+
+class DoubleInput: public Input{
+
+	public:
+		int    enum_type;
+		double value;
+
+		/*DoubleInput constructors, destructors: {{{1*/
+		DoubleInput();
+		DoubleInput(int enum_type,IssmDouble value);
+		~DoubleInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*DoubleInput management: {{{1*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB);
+		Input* PointwiseMin(Input* inputB);
+		Input* PointwiseMax(Input* inputB);
+		ElementResult* SpawnResult(int step, double time);
+		void AddTimeValues(double* values,int step,double time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{1*/
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(double* pvalue);
+		void GetInputValue(double* pvalue,GaussTria* gauss);
+		void GetInputValue(double* pvalue,GaussPenta* gauss);
+		void GetInputValue(double* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(double* pvalue);
+		void GetVxStrainRate2d(double* epsilonvx,double* xyz_list, GaussTria* gauss);
+		void GetVyStrainRate2d(double* epsilonvy,double* xyz_list, GaussTria* gauss);
+		void GetVxStrainRate3d(double* epsilonvx,double* xyz_list, GaussPenta* gauss);
+		void GetVyStrainRate3d(double* epsilonvy,double* xyz_list, GaussPenta* gauss);
+		void GetVzStrainRate3d(double* epsilonvz,double* xyz_list, GaussPenta* gauss);
+		void GetVxStrainRate3dPattyn(double* epsilonvx,double* xyz_list, GaussPenta* gauss);
+		void GetVyStrainRate3dPattyn(double* epsilonvy,double* xyz_list, GaussPenta* gauss);
+		void ChangeEnum(int newenumtype);
+		void SquareMin(double* psquaremin, bool process_units,Parameters* parameters);
+		void ConstrainMin(double minimum);
+		void Scale(double scale_factor);
+		void ArtificialNoise(double min,double max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,double scalar);
+		void Constrain(double cm_min, double cm_max);
+		double InfinityNorm(void){_error_("not implemented yet");};
+		double Max(void);
+		double MaxAbs(void);
+		double Min(void);
+		double MinAbs(void);
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vec vector,int* doflist);
+		void GetValuesPtr(double** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _DOUBLEINPUT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/Input.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/Input.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/Input.h	(revision 11330)
@@ -0,0 +1,70 @@
+/*!\file:  Input.h
+ * \brief abstract class for Input object
+ */ 
+
+
+#ifndef _INPUT_H_
+#define _INPUT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../Object.h"
+class Node;
+class ElementResult;
+class GaussTria;
+class Parameters;
+/*}}}*/
+
+class Input: public Object{
+
+	public: 
+		
+		virtual        ~Input(){};
+		/*Virtual functions:{{{1*/
+		virtual int  InstanceEnum()=0; 
+		virtual void GetInputValue(bool* pvalue)=0;
+		virtual void GetInputValue(int* pvalue)=0;
+		virtual void GetInputValue(double* pvalue)=0;
+		virtual void GetInputValue(double* pvalue,GaussTria* gauss)=0;
+		virtual void GetInputValue(double* pvalue,GaussPenta* gauss)=0;
+		virtual void GetInputValue(double* pvalue,GaussTria* gauss ,int index)=0;
+		virtual void GetInputValue(double* pvalue,GaussPenta* gauss,int index)=0;
+		virtual void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss)=0;
+		virtual void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss)=0;
+		virtual void GetInputAverage(double* pvalue)=0;
+		virtual void GetVxStrainRate2d(double* epsilonvx,double* xyz_list, GaussTria* gauss)=0;
+		virtual void GetVyStrainRate2d(double* epsilonvy,double* xyz_list, GaussTria* gauss)=0;
+		virtual void GetVxStrainRate3d(double* epsilonvx,double* xyz_list, GaussPenta* gauss)=0;
+		virtual void GetVyStrainRate3d(double* epsilonvy,double* xyz_list, GaussPenta* gauss)=0;
+		virtual void GetVzStrainRate3d(double* epsilonvz,double* xyz_list, GaussPenta* gauss)=0;
+		virtual void GetVxStrainRate3dPattyn(double* epsilonvx,double* xyz_list, GaussPenta* gauss)=0;
+		virtual void GetVyStrainRate3dPattyn(double* epsilonvy,double* xyz_list, GaussPenta* gauss)=0;
+		virtual void ChangeEnum(int newenumtype)=0;
+		virtual void Configure(Parameters* parameters)=0;
+
+		virtual void   SquareMin(double* psquaremin, bool process_units,Parameters* parameters)=0;
+		virtual void   ConstrainMin(double minimum)=0;
+		virtual double InfinityNorm(void)=0;
+		virtual double MaxAbs(void)=0;
+		virtual double MinAbs(void)=0;
+		virtual double Max(void)=0;
+		virtual double Min(void)=0;
+		virtual void   Scale(double scale_factor)=0;
+		virtual void   ArtificialNoise(double min,double max)=0;
+		virtual void   AXPY(Input* xinput,double scalar)=0;
+		virtual void   Constrain(double cm_min, double cm_max)=0;
+		virtual void   VerticallyIntegrate(Input* thickness_input)=0;
+		virtual void   Extrude()=0;
+		virtual void   GetVectorFromInputs(Vec vector,int* doflist)=0;
+		virtual void   GetValuesPtr(double** pvalues,int* pnum_values)=0;
+		
+		virtual Input* SpawnTriaInput(int* indices)=0;
+		virtual Input* PointwiseDivide(Input* inputB)=0;
+		virtual Input* PointwiseMax(Input* inputmax)=0;
+		virtual Input* PointwiseMin(Input* inputmin)=0;
+		virtual ElementResult* SpawnResult(int step, double time)=0;
+
+		/*}}}*/
+
+};
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/IntInput.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/IntInput.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/IntInput.cpp	(revision 11330)
@@ -0,0 +1,250 @@
+/*!\file IntInput.c
+ * \brief: implementation of the IntInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+/*IntInput constructors and destructor*/
+/*FUNCTION IntInput::IntInput(){{{1*/
+IntInput::IntInput(){
+	return;
+}
+/*}}}*/
+/*FUNCTION IntInput::IntInput(double* values){{{1*/
+IntInput::IntInput(int in_enum_type,IssmInt in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION IntInput::~IntInput(){{{1*/
+IntInput::~IntInput(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION IntInput::DeepEcho{{{1*/
+void IntInput::DeepEcho(void){
+
+	printf("IntInput:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %i\n",(int)this->value);
+}
+/*}}}*/
+/*FUNCTION IntInput::Id{{{1*/
+int    IntInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntInput::MyRank{{{1*/
+int    IntInput::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION IntInput::Marshall{{{1*/
+void  IntInput::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of IntInput: */
+	enum_value=IntInputEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall IntInput data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&value,sizeof(value));marshalled_dataset+=sizeof(value);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION IntInput::MarshallSize{{{1*/
+int   IntInput::MarshallSize(){
+	
+	return sizeof(value)+
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION IntInput::Demarshall{{{1*/
+void  IntInput::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&value,marshalled_dataset,sizeof(value));marshalled_dataset+=sizeof(value);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION IntInput::ObjectEnum{{{1*/
+int IntInput::ObjectEnum(void){
+
+	return IntInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION IntInput::copy{{{1*/
+Object* IntInput::copy() {
+	
+	return new IntInput(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*IntInput management*/
+/*FUNCTION IntInput::Echo {{{1*/
+void IntInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION IntInput::InstanceEnum{{{1*/
+int IntInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION IntInput::SpawnTriaInput{{{1*/
+Input* IntInput::SpawnTriaInput(int* indices){
+
+	/*output*/
+	IntInput* outinput=new IntInput();
+
+	/*only copy current value*/
+	outinput->enum_type=this->enum_type;
+	outinput->value=this->value;
+
+	/*Assign output*/
+	return outinput;
+}
+/*}}}*/
+/*FUNCTION IntInput::SpawnResult{{{1*/
+ElementResult* IntInput::SpawnResult(int step, double time){
+	
+	_error_(" not supported yet!");
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION IntInput::GetInputValue(bool* pvalue) {{{1*/
+void IntInput::GetInputValue(bool* pvalue){_error_(" not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(int* pvalue){{{1*/
+void IntInput::GetInputValue(int* pvalue){
+	*pvalue=value;
+}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(double* pvalue){{{1*/
+void IntInput::GetInputValue(double* pvalue){
+	_error_("IntInput cannot return a double in parallel");
+}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(double* pvalue,GaussTria* gauss){{{1*/
+void IntInput::GetInputValue(double* pvalue,GaussTria* gauss){_error_(" not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(double* pvalue,GaussPenta* gauss){{{1*/
+void IntInput::GetInputValue(double* pvalue,GaussPenta* gauss){_error_(" not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss){{{1*/
+void IntInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss){_error_(" not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss){{{1*/
+void IntInput::GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss){_error_(" not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::ChangeEnum{{{1*/
+void IntInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION IntInput::SquareMin{{{1*/
+void IntInput::SquareMin(double* psquaremin, bool process_units,Parameters* parameters){
+
+	/*square min of an integer is the square of the integer itself: */
+	*psquaremin=pow((double)value,2);
+}
+/*}}}*/
+/*FUNCTION IntInput::Scale{{{1*/
+void IntInput::Scale(double scale_factor){
+	double dvalue=(double)value*scale_factor;
+	value=(int)dvalue;
+}
+/*}}}*/
+/*FUNCTION IntInput::AXPY{{{1*/
+void IntInput::AXPY(Input* xinput,double scalar){
+
+	double 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=(double)this->value+scalar*(double)xintinput->value;
+			this->value=(int)dvalue;
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION IntInput::Constrain{{{1*/
+void IntInput::Constrain(double cm_min, double cm_max){
+
+	if(!isnan(cm_min)) if (this->value<cm_min)this->value=(int)cm_min;
+	if(!isnan(cm_max)) if (this->value>cm_max)this->value=(int)cm_max;
+
+}
+/*}}}*/
+/*FUNCTION IntInput::GetVectorFromInputs{{{1*/
+void IntInput::GetVectorFromInputs(Vec vector,int* doflist){
+
+	_error_(" not supporte yet!");
+
+}
+/*}}}*/
+/*FUNCTION IntInput::GetValuesPtr{{{1*/
+void IntInput::GetValuesPtr(double** pvalues,int* pnum_values){
+
+	_error_(" not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION IntInput::Configure{{{1*/
+void IntInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/IntInput.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/IntInput.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/IntInput.h	(revision 11330)
@@ -0,0 +1,88 @@
+/*! \file IntInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _INTINPUT_H_
+#define _INTINPUT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Input.h"
+#include "../../include/include.h"
+class GaussTria;
+/*}}}*/
+
+class IntInput: public Input{
+
+	public:
+		/*just hold 3 values for 3 vertices: */
+		int    enum_type;
+		IssmInt value;
+
+		/*IntInput constructors, destructors: {{{1*/
+		IntInput();
+		IntInput(int enum_type,IssmInt value);
+		~IntInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*IntInput management: {{{1*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, double time);
+		void AddTimeValues(double* values,int step,double time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{1*/
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(double* pvalue);
+		void GetInputValue(double* pvalue,GaussTria* gauss);
+		void GetInputValue(double* pvalue,GaussPenta* gauss);
+		void GetInputValue(double* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(double* pvalue){_error_("not implemented yet");};
+		void GetVxStrainRate2d(double* epsilonvx,double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(double* epsilonvy,double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(double* epsilonvx,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(double* epsilonvy,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(double* epsilonvz,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(double* epsilonvx,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(double* epsilonvy,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+		void SquareMin(double* psquaremin, bool process_units,Parameters* parameters);
+		void ConstrainMin(double minimum){_error_("not implemented yet");};
+		void Scale(double scale_factor);
+		void ArtificialNoise(double min,double max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,double scalar);
+		void Constrain(double cm_min, double cm_max);
+		double InfinityNorm(void){_error_("InfinityNorm not implemented for integers");};
+		double Max(void){_error_("Max not implemented for integers");};
+		double MaxAbs(void){_error_("Max not implemented for integers");};
+		double Min(void){_error_("Min not implemented for integers");};
+		double 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(Vec vector,int* doflist);
+		void GetValuesPtr(double** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _INTINPUT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/PentaP1Input.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/PentaP1Input.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/PentaP1Input.cpp	(revision 11330)
@@ -0,0 +1,680 @@
+/*!\file PentaP1Input.c
+ * \brief: implementation of the PentaP1Input object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+/*PentaP1Input constructors and destructor*/
+/*FUNCTION PentaP1Input::PentaP1Input(){{{1*/
+PentaP1Input::PentaP1Input(){
+	return;
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::PentaP1Input(int in_enum_type,double* values){{{1*/
+PentaP1Input::PentaP1Input(int in_enum_type,double* in_values)
+		:PentaRef(1)
+{
+
+	/*Set PentaRef*/
+	this->SetElementType(P1Enum,0);
+	this->element_type=P1Enum;
+
+	enum_type=in_enum_type;
+	values[0]=in_values[0];
+	values[1]=in_values[1];
+	values[2]=in_values[2];
+	values[3]=in_values[3];
+	values[4]=in_values[4];
+	values[5]=in_values[5];
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::~PentaP1Input(){{{1*/
+PentaP1Input::~PentaP1Input(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION PentaP1Input::Echo {{{1*/
+void PentaP1Input::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::DeepEcho{{{1*/
+void PentaP1Input::DeepEcho(void){
+
+	printf("PentaP1Input:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   values: [%g %g %g %g %g %g]\n",this->values[0],this->values[1],this->values[2],this->values[3],this->values[4],this->values[5]);
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::Id{{{1*/
+int    PentaP1Input::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION PentaP1Input::MyRank{{{1*/
+int    PentaP1Input::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION PentaP1Input::Marshall{{{1*/
+void  PentaP1Input::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of PentaP1Input: */
+	enum_value=PentaP1InputEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall PentaP1Input data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&values,sizeof(values));marshalled_dataset+=sizeof(values);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::MarshallSize{{{1*/
+int   PentaP1Input::MarshallSize(){
+	
+	return sizeof(values)+
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::Demarshall{{{1*/
+void  PentaP1Input::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&values,marshalled_dataset,sizeof(values));marshalled_dataset+=sizeof(values);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION PentaP1Input::ObjectEnum{{{1*/
+int PentaP1Input::ObjectEnum(void){
+
+	return PentaP1InputEnum;
+
+}
+/*}}}*/
+	
+/*PentaP1Input management*/
+/*FUNCTION PentaP1Input::copy{{{1*/
+Object* PentaP1Input::copy() {
+	
+	return new PentaP1Input(this->enum_type,this->values);
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::InstanceEnum{{{1*/
+int PentaP1Input::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::SpawnTriaInput{{{1*/
+Input* PentaP1Input::SpawnTriaInput(int* indices){
+
+	/*output*/
+	TriaP1Input* outinput=NULL;
+	double newvalues[3];
+
+	/*Loop over the new indices*/
+	for(int i=0;i<3;i++){
+
+		/*Check index value*/
+		_assert_(indices[i]>=0 && indices[i]<6);
+
+		/*Assign value to new input*/
+		newvalues[i]=this->values[indices[i]];
+	}
+
+	/*Create new Tria input*/
+	outinput=new TriaP1Input(this->enum_type,&newvalues[0]);
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::SpawnResult{{{1*/
+ElementResult* PentaP1Input::SpawnResult(int step, double time){
+
+	return new PentaP1ElementResult(this->enum_type,this->values,step,time);
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION PentaP1Input::GetInputValue(double* pvalue,GaussPenta* gauss){{{1*/
+void PentaP1Input::GetInputValue(double* pvalue,GaussPenta* gauss){
+
+	/*Call PentaRef function*/
+	PentaRef::GetInputValue(pvalue,&values[0],gauss);
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::GetInputDerivativeValue(double* p, double* xyz_list, GaussPenta* gauss){{{1*/
+void PentaP1Input::GetInputDerivativeValue(double* p, double* xyz_list, GaussPenta* gauss){
+
+	/*Call PentaRef function*/
+	PentaRef::GetInputDerivativeValue(p,&values[0],xyz_list,gauss);
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::GetVxStrainRate3d{{{1*/
+void PentaP1Input::GetVxStrainRate3d(double* epsilonvx,double* xyz_list, GaussPenta* gauss){
+	int i,j;
+
+	const int numnodes=6;
+	const int DOFVELOCITY=3;
+	double B[8][27];
+	double B_reduced[6][DOFVELOCITY*numnodes];
+	double velocity[numnodes][DOFVELOCITY];
+
+	/*Get B matrix: */
+	GetBStokes(&B[0][0], xyz_list, gauss);
+	/*Create a reduced matrix of B to get rid of pressure */
+	for (i=0;i<6;i++){
+		for (j=0;j<3;j++){
+			B_reduced[i][j]=B[i][j];
+		}
+		for (j=4;j<7;j++){
+			B_reduced[i][j-1]=B[i][j];
+		}
+		for (j=8;j<11;j++){
+			B_reduced[i][j-2]=B[i][j];
+		}
+		for (j=12;j<15;j++){
+			B_reduced[i][j-3]=B[i][j];
+		}
+		for (j=16;j<19;j++){
+			B_reduced[i][j-4]=B[i][j];
+		}
+		for (j=20;j<23;j++){
+			B_reduced[i][j-5]=B[i][j];
+		}
+	}
+
+	/*Here, we are computing the strain rate of (vx,0,0)*/
+	for(i=0;i<numnodes;i++){
+		velocity[i][0]=this->values[i];
+		velocity[i][1]=0.0;
+		velocity[i][2]=0.0;
+	}
+	/*Multiply B by velocity, to get strain rate: */
+	MatrixMultiply(&B_reduced[0][0],6,DOFVELOCITY*numnodes,0,&velocity[0][0],DOFVELOCITY*numnodes,1,0,epsilonvx,0);
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::GetVyStrainRate3d{{{1*/
+void PentaP1Input::GetVyStrainRate3d(double* epsilonvy,double* xyz_list, GaussPenta* gauss){
+	int i,j;
+
+	const int numnodes=6;
+	const int DOFVELOCITY=3;
+	double B[8][27];
+	double B_reduced[6][DOFVELOCITY*numnodes];
+	double velocity[numnodes][DOFVELOCITY];
+
+	/*Get B matrix: */
+	GetBStokes(&B[0][0], xyz_list, gauss);
+	/*Create a reduced matrix of B to get rid of pressure */
+	for (i=0;i<6;i++){
+		for (j=0;j<3;j++){
+			B_reduced[i][j]=B[i][j];
+		}
+		for (j=4;j<7;j++){
+			B_reduced[i][j-1]=B[i][j];
+		}
+		for (j=8;j<11;j++){
+			B_reduced[i][j-2]=B[i][j];
+		}
+		for (j=12;j<15;j++){
+			B_reduced[i][j-3]=B[i][j];
+		}
+		for (j=16;j<19;j++){
+			B_reduced[i][j-4]=B[i][j];
+		}
+		for (j=20;j<23;j++){
+			B_reduced[i][j-5]=B[i][j];
+		}
+	}
+
+	/*Here, we are computing the strain rate of (0,vy,0)*/
+	for(i=0;i<numnodes;i++){
+		velocity[i][0]=0.0;
+		velocity[i][1]=this->values[i];
+		velocity[i][2]=0.0;
+	}
+	/*Multiply B by velocity, to get strain rate: */
+	MatrixMultiply(&B_reduced[0][0],6,DOFVELOCITY*numnodes,0,&velocity[0][0],DOFVELOCITY*numnodes,1,0,epsilonvy,0);
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::GetVzStrainRate3d{{{1*/
+void PentaP1Input::GetVzStrainRate3d(double* epsilonvz,double* xyz_list, GaussPenta* gauss){
+	int i,j;
+
+	const int numnodes=6;
+	const int DOFVELOCITY=3;
+	double B[8][27];
+	double B_reduced[6][DOFVELOCITY*numnodes];
+	double velocity[numnodes][DOFVELOCITY];
+
+	/*Get B matrix: */
+	GetBStokes(&B[0][0], xyz_list, gauss);
+	/*Create a reduced matrix of B to get rid of pressure */
+	for (i=0;i<6;i++){
+		for (j=0;j<3;j++){
+			B_reduced[i][j]=B[i][j];
+		}
+		for (j=4;j<7;j++){
+			B_reduced[i][j-1]=B[i][j];
+		}
+		for (j=8;j<11;j++){
+			B_reduced[i][j-2]=B[i][j];
+		}
+		for (j=12;j<15;j++){
+			B_reduced[i][j-3]=B[i][j];
+		}
+		for (j=16;j<19;j++){
+			B_reduced[i][j-4]=B[i][j];
+		}
+		for (j=20;j<23;j++){
+			B_reduced[i][j-5]=B[i][j];
+		}
+	}
+
+	/*Here, we are computing the strain rate of (0,0,vz)*/
+	for(i=0;i<numnodes;i++){
+		velocity[i][0]=0.0;
+		velocity[i][1]=0.0;
+		velocity[i][2]=this->values[i];
+	}
+
+	/*Multiply B by velocity, to get strain rate: */
+	MatrixMultiply(&B_reduced[0][0],6,DOFVELOCITY*numnodes,0,&velocity[0][0],DOFVELOCITY*numnodes,1,0,epsilonvz,0);
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::GetVxStrainRate3dPattyn{{{1*/
+void PentaP1Input::GetVxStrainRate3dPattyn(double* epsilonvx,double* xyz_list, GaussPenta* gauss){
+
+	int i;
+	const int numnodes=6;
+	double B[5][NDOF2*numnodes];
+	double velocity[numnodes][NDOF2];
+
+	/*Get B matrix: */
+	GetBPattyn(&B[0][0], xyz_list, gauss);
+
+	/*Here, we are computing the strain rate of (vx,0)*/
+	for(i=0;i<numnodes;i++){
+		velocity[i][0]=this->values[i];
+		velocity[i][1]=0.0;
+	}
+
+	/*Multiply B by velocity, to get strain rate: */
+	MatrixMultiply( &B[0][0],5,NDOF2*numnodes,0,
+				&velocity[0][0],NDOF2*numnodes,1,0,
+				epsilonvx,0);
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::GetVyStrainRate3dPattyn{{{1*/
+void PentaP1Input::GetVyStrainRate3dPattyn(double* epsilonvy,double* xyz_list, GaussPenta* gauss){
+
+	int i;
+	const int numnodes=6;
+	double B[5][NDOF2*numnodes];
+	double velocity[numnodes][NDOF2];
+
+	/*Get B matrix: */
+	GetBPattyn(&B[0][0], xyz_list, gauss);
+
+	/*Here, we are computing the strain rate of (0,vy)*/
+	for(i=0;i<numnodes;i++){
+		velocity[i][0]=0.0;
+		velocity[i][1]=this->values[i];
+	}
+
+	/*Multiply B by velocity, to get strain rate: */
+	MatrixMultiply( &B[0][0],5,NDOF2*numnodes,0,
+				&velocity[0][0],NDOF2*numnodes,1,0,
+				epsilonvy,0);
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::ChangeEnum{{{1*/
+void PentaP1Input::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::GetInputAverage{{{1*/
+void PentaP1Input::GetInputAverage(double* pvalue){
+	*pvalue=1./6.*(values[0]+values[1]+values[2]+values[3]+values[4]+values[5]);
+}
+/*}}}*/
+
+/*Intermediary*/
+/*FUNCTION PentaP1Input::SquareMin{{{1*/
+void PentaP1Input::SquareMin(double* psquaremin, bool process_units,Parameters* parameters){
+
+	int i;
+	const int numnodes=6;
+	double valuescopy[numnodes];
+	double squaremin;
+
+	/*First,  copy values, to process units if requested: */
+	for(i=0;i<numnodes;i++)valuescopy[i]=this->values[i];
+
+	/*Process units if requested: */
+	if(process_units)UnitConversion(&valuescopy[0],numnodes,IuToExtEnum,enum_type);
+
+	/*Now, figure out minimum of valuescopy: */
+	squaremin=pow(valuescopy[0],2);
+	for(i=1;i<numnodes;i++){
+		if(pow(valuescopy[i],2)<squaremin)squaremin=pow(valuescopy[i],2);
+	}
+	/*Assign output pointers:*/
+	*psquaremin=squaremin;
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::ConstrainMin{{{1*/
+void PentaP1Input::ConstrainMin(double minimum){
+	
+	int i;
+	const int numnodes=6;
+
+	for(i=0;i<numnodes;i++) if (values[i]<minimum) values[i]=minimum;
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::InfinityNorm{{{1*/
+double PentaP1Input::InfinityNorm(void){
+
+	/*Output*/
+	const int numnodes=6;
+	double norm=0;
+
+	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
+	return norm;
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::Max{{{1*/
+double PentaP1Input::Max(void){
+
+	const int numnodes=6;
+	double    max=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]>max) max=values[i];
+	}
+	return max;
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::MaxAbs{{{1*/
+double PentaP1Input::MaxAbs(void){
+
+	const int numnodes=6;
+	double    max=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])>max) max=fabs(values[i]);
+	}
+	return max;
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::Min{{{1*/
+double PentaP1Input::Min(void){
+
+	const int numnodes=6;
+	double    min=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]<min) min=values[i];
+	}
+	return min;
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::MinAbs{{{1*/
+double PentaP1Input::MinAbs(void){
+
+	const int numnodes=6;
+	double    min=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])<min) min=fabs(values[i]);
+	}
+	return min;
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::Scale{{{1*/
+void PentaP1Input::Scale(double scale_factor){
+	
+	int i;
+	const int numnodes=6;
+
+	for(i=0;i<numnodes;i++)values[i]=values[i]*scale_factor;
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::AXPY{{{1*/
+void PentaP1Input::AXPY(Input* xinput,double scalar){
+
+	int i;
+	const int numnodes=6;
+
+	/*xinput is of the same type, so cast it: */
+
+	/*Carry out the AXPY operation depending on type:*/
+	switch(xinput->ObjectEnum()){
+
+		case PentaP1InputEnum:{
+			PentaP1Input* cast_input=(PentaP1Input*)xinput;
+			for(i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*(cast_input->values[i]);}
+			return;
+		case ControlInputEnum:{
+			ControlInput* cont_input=(ControlInput*)xinput;
+			if(cont_input->values->ObjectEnum()!=PentaP1InputEnum) _error_("not supported yet");
+			PentaP1Input* cast_input=(PentaP1Input*)cont_input->values;
+			for(i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*(cast_input->values[i]);}
+			return;
+		default:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::Constrain{{{1*/
+void PentaP1Input::Constrain(double cm_min, double cm_max){
+
+	int i;
+	const int numnodes=6;
+		
+	if(!isnan(cm_min)) for(i=0;i<numnodes;i++)if (this->values[i]<cm_min)this->values[i]=cm_min;
+	if(!isnan(cm_max)) for(i=0;i<numnodes;i++)if (this->values[i]>cm_max)this->values[i]=cm_max;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::Extrude{{{1*/
+void PentaP1Input::Extrude(void){
+
+	int i;
+
+	/*First 3 values copied on 3 last values*/
+	for(i=0;i<3;i++) this->values[3+i]=this->values[i];
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::VerticallyIntegrate{{{1*/
+void PentaP1Input::VerticallyIntegrate(Input* thickness_input){
+
+	/*Intermediaries*/
+	int i;
+	const int  numnodes = 6;
+	int        num_thickness_values;
+	double    *thickness_values = NULL;
+
+	/*Check that input provided is a thickness*/
+	if (thickness_input->InstanceEnum()!=ThicknessEnum) _error_("Input provided is not a Thickness (enum_type is %s)",EnumToStringx(thickness_input->InstanceEnum()));
+
+	/*Get Thickness value pointer*/
+	thickness_input->GetValuesPtr(&thickness_values,&num_thickness_values);
+
+	/*vertically integrate depending on type:*/
+	switch(thickness_input->ObjectEnum()){
+
+		case PentaP1InputEnum:
+			for(i=0;i<3;i++){
+				this->values[i]=0.5*(this->values[i]+this->values[i+3]) * thickness_values[i];
+				this->values[i+3]=this->values[i];
+			}
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::PointwiseDivide{{{1*/
+Input* PentaP1Input::PointwiseDivide(Input* inputB){
+
+	/*Ouput*/
+	PentaP1Input* outinput=NULL;
+
+	/*Intermediaries*/
+	int               i;
+	PentaP1Input *xinputB     = NULL;
+	int               B_numvalues;
+	const int         numnodes    = 6;
+	double            AdotBvalues[numnodes];
+
+	/*Check that inputB is of the same type*/
+	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error_("Operation not permitted because inputB is of type %s",EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(PentaP1Input*)inputB;
+
+	/*Create point wise sum*/
+	for(i=0;i<numnodes;i++){
+		_assert_(xinputB->values[i]!=0);
+		AdotBvalues[i]=this->values[i]/xinputB->values[i];
+	}
+
+	/*Create new Penta vertex input (copy of current input)*/
+	outinput=new PentaP1Input(this->enum_type,&AdotBvalues[0]);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::PointwiseMin{{{1*/
+Input* PentaP1Input::PointwiseMin(Input* inputB){
+
+	/*Ouput*/
+	PentaP1Input* outinput=NULL;
+
+	/*Intermediaries*/
+	int               i;
+	PentaP1Input *xinputB     = NULL;
+	int               B_numvalues;
+	const int         numnodes    = 6;
+	double            minvalues[numnodes];
+
+	/*Check that inputB is of the same type*/
+	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error_("Operation not permitted because inputB is of type %s",EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(PentaP1Input*)inputB;
+
+	/*Create point wise min*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] > xinputB->values[i]) minvalues[i]=xinputB->values[i];
+		else minvalues[i]=this->values[i];
+	}
+
+	/*Create new Penta vertex input (copy of current input)*/
+	outinput=new PentaP1Input(this->enum_type,&minvalues[0]);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::PointwiseMax{{{1*/
+Input* PentaP1Input::PointwiseMax(Input* inputB){
+
+	/*Ouput*/
+	PentaP1Input* outinput=NULL;
+
+	/*Intermediaries*/
+	int               i;
+	PentaP1Input *xinputB     = NULL;
+	int               B_numvalues;
+	const int         numnodes    = 6;
+	double            maxvalues[numnodes];
+
+	/*Check that inputB is of the same type*/
+	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error_("Operation not permitted because inputB is of type %s",EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(PentaP1Input*)inputB;
+
+	/*Create point wise max*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] < xinputB->values[i]) maxvalues[i]=xinputB->values[i];
+		else maxvalues[i]=this->values[i];
+	}
+
+	/*Create new Penta vertex input (copy of current input)*/
+	outinput=new PentaP1Input(this->enum_type,&maxvalues[0]);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::GetVectorFromInputs{{{1*/
+void PentaP1Input::GetVectorFromInputs(Vec vector,int* doflist){
+
+	const int numvertices=6;
+	VecSetValues(vector,numvertices,doflist,(const double*)this->values,INSERT_VALUES);
+
+} /*}}}*/
+/*FUNCTION PentaP1Input::GetValuesPtr{{{1*/
+void PentaP1Input::GetValuesPtr(double** pvalues,int* pnum_values){
+
+	*pvalues=this->values;
+	*pnum_values=6;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::Configure{{{1*/
+void PentaP1Input::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/PentaP1Input.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/PentaP1Input.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/PentaP1Input.h	(revision 11330)
@@ -0,0 +1,89 @@
+/*! \file PentaP1Input.h 
+ *  \brief: header file for PentaP1Input object
+ */
+
+
+#ifndef _PENTAP1INPUT_H_
+#define _PENTAP1INPUT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Input.h"
+#include "../Elements/PentaRef.h"
+class GaussTria;
+/*}}}*/
+
+class PentaP1Input: public Input, public PentaRef{
+
+	public:
+		/*just hold 6 values for 6 vertices: */
+		int    enum_type;
+		double values[6];
+
+		/*PentaP1Input constructors, destructors: {{{1*/
+		PentaP1Input();
+		PentaP1Input(int enum_type,double* values);
+		~PentaP1Input();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*PentaP1Input management: {{{1*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB);
+		Input* PointwiseMin(Input* inputB);
+		Input* PointwiseMax(Input* inputB);
+		ElementResult* SpawnResult(int step, double time);
+		void AddTimeValues(double* values,int step,double time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{1*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussPenta* gauss);
+		void GetInputValue(double* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(double* pvalue);
+		void GetVxStrainRate2d(double* epsilonvx,double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(double* epsilonvy,double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(double* epsilonvx,double* xyz_list, GaussPenta* gauss);
+		void GetVyStrainRate3d(double* epsilonvy,double* xyz_list, GaussPenta* gauss);
+		void GetVzStrainRate3d(double* epsilonvz,double* xyz_list, GaussPenta* gauss);
+		void GetVxStrainRate3dPattyn(double* epsilonvx,double* xyz_list, GaussPenta* gauss);
+		void GetVyStrainRate3dPattyn(double* epsilonvy,double* xyz_list, GaussPenta* gauss);
+		void ChangeEnum(int newenumtype);
+
+		void SquareMin(double* psquaremin, bool process_units,Parameters* parameters);
+		void ConstrainMin(double minimum);
+		void Scale(double scale_factor);
+		void ArtificialNoise(double min,double max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,double scalar);
+		void Constrain(double cm_min, double cm_max);
+		double InfinityNorm(void);
+		double Max(void);
+		double MaxAbs(void);
+		double Min(void);
+		double MinAbs(void);
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vec vector,int* doflist);
+		void GetValuesPtr(double** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _PENTAP1INPUT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/TransientInput.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/TransientInput.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/TransientInput.cpp	(revision 11330)
@@ -0,0 +1,521 @@
+/*!\file TransientInput.c
+ * \brief: implementation of the TransientInput object
+ */
+/*Headers{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*TransientInput constructors and destructor*/
+/*FUNCTION TransientInput::TransientInput(){{{1*/
+TransientInput::TransientInput(){
+
+	enum_type=UNDEF;
+	inputs=NULL;
+	this->numtimesteps=0;
+	this->parameters=NULL;
+	this->timesteps=NULL;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::TransientInput(int in_enum_type){{{1*/
+TransientInput::TransientInput(int in_enum_type)
+{
+	/*Set Enum*/
+	enum_type=in_enum_type;
+
+	/*Allocate values and timesteps, and copy: */
+	this->numtimesteps=0;
+	this->timesteps=NULL;
+	inputs = new Inputs();
+	this->parameters=NULL;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::~TransientInput{{{1*/
+TransientInput::~TransientInput(){
+	xfree((void**)&this->timesteps);
+	this->timesteps=NULL;
+	this->numtimesteps=0;
+	parameters=NULL;
+	delete this->inputs;
+	return;
+}
+/*}}}*/
+/*FUNCTION void TransientInput::AddTimeInput(Input* input,double time){{{1*/
+void TransientInput::AddTimeInput(Input* input,double time){
+
+	/*insert values at time step: */
+	if (this->numtimesteps>0 && time<=this->timesteps[this->numtimesteps-1]) _assert_("timestep values must increase sequentially");
+
+	//copy timesteps, add the new time, delete previous timesteps, and add the new input: inputs->AddObject(input);
+   double* old_timesteps=NULL;
+
+	if (this->numtimesteps > 0){
+		old_timesteps=(double*)xmalloc(this->numtimesteps*sizeof(double));
+		memcpy(old_timesteps,this->timesteps,this->numtimesteps*sizeof(double));
+		xfree((void**)&this->timesteps); 
+	}
+
+	this->numtimesteps=this->numtimesteps+1;
+   this->timesteps=(double*)xmalloc(this->numtimesteps*sizeof(double));
+
+	if (this->numtimesteps > 1){
+		memcpy(this->timesteps,old_timesteps,(this->numtimesteps-1)*sizeof(double));
+		xfree((void**)&old_timesteps);
+	}
+
+	/*go ahead and plug: */
+	this->timesteps[this->numtimesteps-1]=time;
+	inputs->AddObject(input);
+
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION TransientInput::Echo {{{1*/
+void TransientInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION TransientInput::DeepEcho{{{1*/
+void TransientInput::DeepEcho(void){
+
+	int i;
+
+	printf("TransientInput:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   numtimesteps: %i\n",this->numtimesteps);
+	printf("---inputs: \n"); 
+	for(i=0;i<this->numtimesteps;i++){
+		printf("   time: %g  \n",this->timesteps[i]);
+		((Input*)this->inputs->GetObjectByOffset(i))->Echo();
+	}
+}
+/*}}}*/
+/*FUNCTION TransientInput::Id{{{1*/
+int    TransientInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION TransientInput::MyRank{{{1*/
+int    TransientInput::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION TransientInput::Marshall{{{1*/
+void  TransientInput::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	char* marshalled_inputs=NULL;
+	int   marshalled_inputs_size;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of TransientInput: */
+	enum_value=TransientInputEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+
+	/*marshall TransientInput data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&numtimesteps,sizeof(numtimesteps));marshalled_dataset+=sizeof(numtimesteps);
+	memcpy(marshalled_dataset,timesteps,numtimesteps*sizeof(double));marshalled_dataset+=numtimesteps*sizeof(double);
+
+	/*marshal inputs*/
+	marshalled_inputs_size=inputs->MarshallSize();
+	marshalled_inputs=inputs->Marshall();
+	memcpy(marshalled_dataset,marshalled_inputs,marshalled_inputs_size*sizeof(char));
+	marshalled_dataset+=marshalled_inputs_size;
+
+	/*clean up and assign output pointer*/
+	xfree((void**)&marshalled_inputs);
+	*pmarshalled_dataset=marshalled_dataset;
+
+}
+/*}}}*
+/*FUNCTION TransientInput::MarshallSize{{{1*/
+int   TransientInput::MarshallSize(){
+
+	return 
+		+sizeof(enum_type)+
+		+sizeof(numtimesteps)+
+		+inputs->MarshallSize()
+		+numtimesteps*sizeof(double)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION TransientInput::Demarshall{{{1*/
+void  TransientInput::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&numtimesteps,marshalled_dataset,sizeof(numtimesteps));marshalled_dataset+=sizeof(numtimesteps);
+
+	/*allocate: */
+	timesteps=(double*)xmalloc(numtimesteps*sizeof(double));
+	memcpy(timesteps,marshalled_dataset,numtimesteps*sizeof(double));marshalled_dataset+=numtimesteps*sizeof(double);
+
+	/*Demarshal values*/
+	inputs=(Inputs*)DataSetDemarshallRaw(&marshalled_dataset);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+
+}
+/*}}}*/
+#endif
+/*FUNCTION TransientInput::ObjectEnum{{{1*/
+int TransientInput::ObjectEnum(void){
+
+	return TransientInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::copy{{{1*/
+Object* TransientInput::copy() {
+
+	TransientInput* output=NULL;
+
+	output = new TransientInput();
+	output->enum_type=this->enum_type;
+	output->numtimesteps=this->numtimesteps;
+	output->timesteps=(double*)xmalloc(this->numtimesteps*sizeof(double));
+   memcpy(output->timesteps,this->timesteps,this->numtimesteps*sizeof(double));
+	output->inputs=(Inputs*)this->inputs->Copy();
+	output->parameters=this->parameters;
+
+	return output;
+
+}
+/*}}}*/
+	
+/*TransientInput management*/
+/*FUNCTION TransientInput::InstanceEnum{{{1*/
+int TransientInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::SpawnTriaInput{{{1*/
+Input* TransientInput::SpawnTriaInput(int* indices){
+
+	/*output*/
+	TransientInput* outinput=NULL;
+
+	/*Create new Transientinput (copy of current input)*/
+	outinput=new TransientInput();
+	outinput->enum_type=this->enum_type;
+	outinput->numtimesteps=this->numtimesteps;
+	outinput->timesteps=(double*)xmalloc(this->numtimesteps*sizeof(double));
+	memcpy(outinput->timesteps,this->timesteps,this->numtimesteps*sizeof(double));
+	outinput->inputs=(Inputs*)this->inputs->SpawnTriaInputs(indices);
+	outinput->parameters=this->parameters;
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::SpawnResult{{{1*/
+ElementResult* TransientInput::SpawnResult(int step, double time){
+
+	ElementResult* elementresult=NULL;
+
+	/*Ok, we want to spawn an ElementResult. We have the time, just get 
+	 *the correct values: */
+	Input* input=GetTimeInput(time);
+
+	elementresult=input->SpawnResult(step,time);
+
+   delete input;
+
+	return elementresult;
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION TransientInput::GetInputValue(double* pvalue,GaussTria* gauss){{{1*/
+void TransientInput::GetInputValue(double* pvalue,GaussTria* gauss){
+	
+	double time;
+
+	/*First, recover current time from parameters: */
+	this->parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputValue(pvalue,gauss);
+
+	delete input;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputDerivativeValue(double* p, double* xyz_list, GaussTria* gauss){{{1*/
+void TransientInput::GetInputDerivativeValue(double* p, double* xyz_list, GaussTria* gauss){
+
+	double time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+		   
+	/*Call input function*/
+	input->GetInputDerivativeValue(p,xyz_list,gauss);
+
+	delete input;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::ChangeEnum{{{1*/
+void TransientInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputAverage{{{1*/
+void TransientInput::GetInputAverage(double* pvalue){
+	
+	double time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputAverage(pvalue);
+			   
+	delete input;
+
+}
+/*}}}*/
+
+/*Intermediary*/
+/*FUNCTION TransientInput::SquareMin{{{1*/
+void TransientInput::SquareMin(double* psquaremin, bool process_units,Parameters* parameters){
+
+	double time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+   /*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+		   
+	/*Call input function*/
+	input->SquareMin(psquaremin,process_units,parameters);
+			   
+	delete input;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::InfinityNorm{{{1*/
+double TransientInput::InfinityNorm(void){
+
+	double time;
+	double infnorm;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+   /*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	infnorm=input->InfinityNorm();
+			   
+	/*Clean-up and return*/
+	delete input;
+	return infnorm;
+}
+/*}}}*/
+/*FUNCTION TransientInput::Max{{{1*/
+double TransientInput::Max(void){
+
+	double time;
+	double max;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+   /*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+		   
+	/*Call input function*/
+	max=input->Max();
+			   
+	delete input;
+
+	return max;
+}
+/*}}}*/
+/*FUNCTION TransientInput::MaxAbs{{{1*/
+double TransientInput::MaxAbs(void){
+
+	double time;
+	double maxabs;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	maxabs=input->MaxAbs();
+
+	/*Clean-up and return*/
+	delete input;
+	return maxabs;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::Min{{{1*/
+double TransientInput::Min(void){
+
+	double time;
+	double min;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+   /*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	min=input->Min();
+
+	/*Clean-up and return*/
+	delete input;
+	return min;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::MinAbs{{{1*/
+double TransientInput::MinAbs(void){
+
+	double time;
+	double minabs;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	minabs=input->MinAbs();
+			   
+	/*Clean-up and return*/
+	delete input;
+	return minabs;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetVectorFromInputs{{{1*/
+void TransientInput::GetVectorFromInputs(Vec vector,int* doflist){
+
+	double time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+		   
+	/*Call input function*/
+	input->GetVectorFromInputs(vector,doflist);
+			   
+	delete input;
+
+} /*}}}*/
+/*FUNCTION TransientInput::GetTimeInput{{{1*/
+Input* TransientInput::GetTimeInput(double intime){
+
+	int     i,j;
+	double  deltat;
+	double  alpha1,alpha2;
+	bool    found=false;
+	Input*  input=NULL;
+	Input*  input1=NULL;
+	Input*  input2=NULL;
+
+	/*Ok, we have the time, go through the timesteps, and figure out which interval we 
+	 *fall within. Then interpolate the values on this interval: */
+	if(intime<this->timesteps[0]){
+		/*get values for the first time: */
+		input=(Input*)((Input*)this->inputs->GetObjectByOffset(0))->copy();
+		found=true;
+	}
+	else if(intime>this->timesteps[this->numtimesteps-1]){
+		/*get values for the last time: */
+		input=(Input*)((Input*)this->inputs->GetObjectByOffset(numtimesteps-1))->copy();
+		found=true;
+	}
+	else{
+		/*Find which interval we fall within: */
+		for(i=0;i<this->numtimesteps;i++){
+			if(intime==this->timesteps[i]){
+				/*We are right on one step time: */
+				input=(Input*)((Input*)this->inputs->GetObjectByOffset(i))->copy();
+				found=true;
+				break; //we are done with the time interpolation.
+			}
+			else{
+				if(this->timesteps[i]<intime && intime<this->timesteps[i+1]){
+					/*ok, we have the interval ]i:i+1[. Interpolate linearly for now: */
+					deltat=this->timesteps[i+1]-this->timesteps[i];
+					alpha2=(intime-this->timesteps[i])/deltat;
+					alpha1=(1-alpha2);
+
+					input1=(Input*)this->inputs->GetObjectByOffset(i); 
+					input2=(Input*)this->inputs->GetObjectByOffset(i+1);
+
+					input=(Input*)input1->copy();
+					input->Scale(alpha1);
+					input->AXPY(input2,alpha2);
+
+					found=true;
+					break;
+				}
+				else continue; //keep looking on the next interval
+			}
+		}
+	}
+	if(!found)_error_("did not find time interval on which to interpolate forcing values!");
+
+	/*Assign output pointer*/
+	return input;
+}
+/*}}}*/
+/*FUNCTION TransientInput::Configure{{{1*/
+void TransientInput::Configure(Parameters* parameters){
+	this->parameters=parameters;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/TransientInput.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/TransientInput.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/TransientInput.h	(revision 11330)
@@ -0,0 +1,93 @@
+/*! \file TransientInput.h 
+ *  \brief: header file for transientinput object
+ */
+
+
+#ifndef _TRANSIENTINPUT_H_
+#define _TRANSIENTINPUT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Input.h"
+class GaussTria;
+class Parameters;
+/*}}}*/
+
+class TransientInput: public Input{
+
+	public:
+		int     enum_type;
+		int     numtimesteps;
+		Inputs* inputs;
+		double* timesteps;
+		Parameters* parameters; //to find current time.
+
+		/*TransientInput constructors, destructors: {{{1*/
+		TransientInput();
+		TransientInput(int enum_type);
+		~TransientInput();
+		void AddTimeInput(Input* input,double time);
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		int   Id();
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*TransientInput management: {{{1*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* forcingB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* forcingB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* forcingB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, double time);
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{1*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussTria* gauss);
+		void GetInputValue(double* pvalue,GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputAverage(double* pvalue);
+		void GetVxStrainRate2d(double* epsilonvx,double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(double* epsilonvy,double* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(double* epsilonvx,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(double* epsilonvy,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(double* epsilonvz,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(double* epsilonvx,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(double* epsilonvy,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+
+		void SquareMin(double* psquaremin, bool process_units,Parameters* parameters);
+		void ConstrainMin(double minimum){_error_("not implemented yet");};
+		void Scale(double scale_factor){_error_("not implemented yet");};
+		void ArtificialNoise(double min,double max){_error_("not implemented yet");};
+		void AXPY(Input* xforcing,double scalar){_error_("not implemented yet");};
+		void Constrain(double cm_min, double cm_max){_error_("not implemented yet");};
+		double InfinityNorm(void);
+		double Max(void);
+		double MaxAbs(void);
+		double Min(void);
+		double MinAbs(void);
+		void Extrude(void){_error_("not supported yet");}
+		void VerticallyIntegrate(Input* thickness_forcing){_error_("not supported yet");};
+		void GetVectorFromInputs(Vec vector,int* doflist);
+		void GetValuesPtr(double** pvalues,int* pnum_values){_error_("not supported yet");};
+      void GetTimeValues(double* values,double time){_error_("not implemented yet");};
+		Input* GetTimeInput(double time);
+		/*}}}*/
+
+};
+#endif  /* _TRANSIENTINPUT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/TriaP1Input.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/TriaP1Input.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/TriaP1Input.cpp	(revision 11330)
@@ -0,0 +1,473 @@
+/*!\file TriaP1Input.c
+ * \brief: implementation of the TriaP1Input object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+/*TriaP1Input constructors and destructor*/
+/*FUNCTION TriaP1Input::TriaP1Input(){{{1*/
+TriaP1Input::TriaP1Input(){
+	return;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::TriaP1Input(int in_enum_type,double* values){{{1*/
+TriaP1Input::TriaP1Input(int in_enum_type,double* in_values)
+	:TriaRef(1)
+{
+
+	/*Set TriaRef*/
+	this->SetElementType(P1Enum,0);
+	this->element_type=P1Enum;
+
+	/*Set Enum*/
+	enum_type=in_enum_type;
+
+	/*Set values*/
+	values[0]=in_values[0];
+	values[1]=in_values[1];
+	values[2]=in_values[2];
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::~TriaP1Input(){{{1*/
+TriaP1Input::~TriaP1Input(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION TriaP1Input::Echo {{{1*/
+void TriaP1Input::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::DeepEcho{{{1*/
+void TriaP1Input::DeepEcho(void){
+
+	printf("TriaP1Input:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   values: [%g %g %g]\n",this->values[0],this->values[1],this->values[2]);
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::Id{{{1*/
+int    TriaP1Input::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION TriaP1Input::MyRank{{{1*/
+int    TriaP1Input::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION TriaP1Input::Marshall{{{1*/
+void  TriaP1Input::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of TriaP1Input: */
+	enum_value=TriaP1InputEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall TriaP1Input data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&values,sizeof(values));marshalled_dataset+=sizeof(values);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::MarshallSize{{{1*/
+int   TriaP1Input::MarshallSize(){
+	
+	return sizeof(values)+
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::Demarshall{{{1*/
+void  TriaP1Input::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&values,marshalled_dataset,sizeof(values));marshalled_dataset+=sizeof(values);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION TriaP1Input::ObjectEnum{{{1*/
+int TriaP1Input::ObjectEnum(void){
+
+	return TriaP1InputEnum;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::copy{{{1*/
+Object* TriaP1Input::copy() {
+	
+	return new TriaP1Input(this->enum_type,this->values);
+
+}
+/*}}}*/
+	
+/*TriaP1Input management*/
+/*FUNCTION TriaP1Input::InstanceEnum{{{1*/
+int TriaP1Input::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::SpawnTriaInput{{{1*/
+Input* TriaP1Input::SpawnTriaInput(int* indices){
+
+	/*output*/
+	TriaP1Input* outinput=NULL;
+
+	/*Create new Tria input (copy of current input)*/
+	outinput=new TriaP1Input(this->enum_type,&this->values[0]);
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::SpawnResult{{{1*/
+ElementResult* TriaP1Input::SpawnResult(int step, double time){
+
+	return new TriaP1ElementResult(this->enum_type,this->values,step,time);
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION TriaP1Input::GetInputValue(double* pvalue,GaussTria* gauss){{{1*/
+void TriaP1Input::GetInputValue(double* pvalue,GaussTria* gauss){
+
+	/*Call TriaRef function*/
+	TriaRef::GetInputValue(pvalue,&values[0],gauss);
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::GetInputDerivativeValue(double* p, double* xyz_list, GaussTria* gauss){{{1*/
+void TriaP1Input::GetInputDerivativeValue(double* p, double* xyz_list, GaussTria* gauss){
+
+	/*Call TriaRef function*/
+	TriaRef::GetInputDerivativeValue(p,&values[0],xyz_list,gauss);
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::GetVxStrainRate2d{{{1*/
+void TriaP1Input::GetVxStrainRate2d(double* epsilonvx,double* xyz_list, GaussTria* gauss){
+
+	/*Intermediary*/
+	int       i;
+	const int numnodes=3;
+	double B[3][NDOF2*numnodes];
+	double velocity[3][NDOF2];
+
+	/*Get B matrix: */
+	GetBMacAyeal(&B[0][0], xyz_list, gauss);
+
+	/*Here, we are computing the strain rate of (vx,0)*/
+	for(i=0;i<3;i++){
+		velocity[i][0]=this->values[i];
+		velocity[i][1]=0.0;
+	}
+	/*Get epsilon(vx) = B*velocity*/
+	MatrixMultiply( &B[0][0],3,NDOF2*numnodes,0,
+				&velocity[0][0],NDOF2*numnodes,1,0,
+				epsilonvx,0);
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::GetVyStrainRate2d{{{1*/
+void TriaP1Input::GetVyStrainRate2d(double* epsilonvy,double* xyz_list, GaussTria* gauss){
+
+	/*Intermediary*/
+	int       i;
+	const int numnodes=3;
+	double B[3][NDOF2*numnodes];
+	double velocity[3][NDOF2];
+
+	/*Get B matrix: */
+	GetBMacAyeal(&B[0][0], xyz_list, gauss);
+
+	/*Here, we are computing the strain rate of (0,vy)*/
+	for(i=0;i<3;i++){
+		velocity[i][0]=0.0;
+		velocity[i][1]=this->values[i];
+	}
+	/*Get epsilon(vy) = B*velocity*/
+	MatrixMultiply( &B[0][0],3,NDOF2*numnodes,0,
+				&velocity[0][0],NDOF2*numnodes,1,0,
+				epsilonvy,0);
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::ChangeEnum{{{1*/
+void TriaP1Input::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::GetInputAverage{{{1*/
+void TriaP1Input::GetInputAverage(double* pvalue){
+	*pvalue=1./3.*(values[0]+values[1]+values[2]);
+}
+/*}}}*/
+
+/*Intermediary*/
+/*FUNCTION TriaP1Input::SquareMin{{{1*/
+void TriaP1Input::SquareMin(double* psquaremin, bool process_units,Parameters* parameters){
+
+	int i;
+	const int numnodes=3;
+	double valuescopy[numnodes];
+	double squaremin;
+
+	/*First,  copy values, to process units if requested: */
+	for(i=0;i<numnodes;i++)valuescopy[i]=this->values[i];
+
+	/*Process units if requested: */
+	if(process_units)UnitConversion(&valuescopy[0],numnodes,IuToExtEnum,enum_type);
+
+	/*Now, figure out minimum of valuescopy: */
+	squaremin=pow(valuescopy[0],2);
+	for(i=1;i<numnodes;i++){
+		if(pow(valuescopy[i],2)<squaremin)squaremin=pow(valuescopy[i],2);
+	}
+	/*Assign output pointers:*/
+	*psquaremin=squaremin;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::ContrainMin{{{1*/
+void TriaP1Input::ConstrainMin(double minimum){
+	
+	int i;
+	const int numnodes=3;
+
+	for(i=0;i<numnodes;i++) if (values[i]<minimum) values[i]=minimum;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::InfinityNorm{{{1*/
+double TriaP1Input::InfinityNorm(void){
+
+	/*Output*/
+	double norm=0;
+	const int numnodes=3;
+
+	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
+	return norm;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::Max{{{1*/
+double TriaP1Input::Max(void){
+
+	const int numnodes=3;
+	double    max=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]>max) max=values[i];
+	}
+	return max;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::MaxAbs{{{1*/
+double TriaP1Input::MaxAbs(void){
+
+	const int numnodes=3;
+	double    max=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])>max) max=fabs(values[i]);
+	}
+	return max;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::Min{{{1*/
+double TriaP1Input::Min(void){
+
+	const int numnodes=3;
+	double    min=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]<min) min=values[i];
+	}
+	return min;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::MinAbs{{{1*/
+double TriaP1Input::MinAbs(void){
+
+	const int numnodes=3;
+	double    min=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])<min) min=fabs(values[i]);
+	}
+	return min;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::Scale{{{1*/
+void TriaP1Input::Scale(double scale_factor){
+	
+	int i;
+	const int numnodes=3;
+
+	for(i=0;i<numnodes;i++)values[i]=values[i]*scale_factor;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::ArtificialNoise{{{1*/
+void TriaP1Input::ArtificialNoise(double min,double max){
+
+	int i;
+	const int numnodes=3;
+	double noise;
+
+	/*Compute random number between bounds:
+	 * rand() outputs an integer in [0 RAND_MAX]
+	 * (double)rand()/RAND_MAX is in [0 1]
+	 */
+	 noise=min+(max-min)*(double)rand()/RAND_MAX;
+
+	for(i=0;i<numnodes;i++)values[i]=values[i]+noise;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::AXPY{{{1*/
+void TriaP1Input::AXPY(Input* xinput,double scalar){
+
+	int i;
+	const int numnodes=3;
+	TriaP1Input*  xtriavertexinput=NULL;
+
+	/*xinput is of the same type, so cast it: */
+	xtriavertexinput=(TriaP1Input*)xinput;
+
+	/*Carry out the AXPY operation depending on type:*/
+	switch(xinput->ObjectEnum()){
+
+		case TriaP1InputEnum :
+			for(i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*xtriavertexinput->values[i];
+			return;
+
+		default :
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::Constrain{{{1*/
+void TriaP1Input::Constrain(double cm_min, double cm_max){
+
+	int i;
+	const int numnodes=3;
+		
+	if(!isnan(cm_min)) for(i=0;i<numnodes;i++)if (this->values[i]<cm_min)this->values[i]=cm_min;
+	if(!isnan(cm_max)) for(i=0;i<numnodes;i++)if (this->values[i]>cm_max)this->values[i]=cm_max;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::GetVectorFromInputs{{{1*/
+void TriaP1Input::GetVectorFromInputs(Vec vector,int* doflist){
+
+	const int numvertices=3;
+	VecSetValues(vector,numvertices,doflist,(const double*)this->values,INSERT_VALUES);
+
+} /*}}}*/
+/*FUNCTION TriaP1Input::GetValuesPtr{{{1*/
+void TriaP1Input::GetValuesPtr(double** pvalues,int* pnum_values){
+
+	*pvalues=this->values;
+	if(pnum_values)*pnum_values=3;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::PointwiseMin{{{1*/
+Input* TriaP1Input::PointwiseMin(Input* inputB){
+
+	/*Ouput*/
+	TriaP1Input* outinput=NULL;
+
+	/*Intermediaries*/
+	int               i;
+	TriaP1Input *xinputB     = NULL;
+	int               B_numvalues;
+	const int         numnodes    = 3;
+	double            minvalues[numnodes];
+
+	/*Check that inputB is of the same type*/
+	if (inputB->ObjectEnum()!=TriaP1InputEnum) _error_("Operation not permitted because inputB is of type %s",EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(TriaP1Input*)inputB;
+
+	/*Create point wise min*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] > xinputB->values[i]) minvalues[i]=xinputB->values[i];
+		else minvalues[i]=this->values[i];
+	}
+
+	/*Create new Tria vertex input (copy of current input)*/
+	outinput=new TriaP1Input(this->enum_type,&minvalues[0]);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::PointwiseMax{{{1*/
+Input* TriaP1Input::PointwiseMax(Input* inputB){
+
+	/*Ouput*/
+	TriaP1Input* outinput=NULL;
+
+	/*Intermediaries*/
+	int               i;
+	TriaP1Input *xinputB     = NULL;
+	int               B_numvalues;
+	const int         numnodes    = 3;
+	double            maxvalues[numnodes];
+
+	/*Check that inputB is of the same type*/
+	if (inputB->ObjectEnum()!=TriaP1InputEnum) _error_("Operation not permitted because inputB is of type %s",EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(TriaP1Input*)inputB;
+
+	/*Create point wise max*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] < xinputB->values[i]) maxvalues[i]=xinputB->values[i];
+		else maxvalues[i]=this->values[i];
+	}
+
+	/*Create new Tria vertex input (copy of current input)*/
+	outinput=new TriaP1Input(this->enum_type,&maxvalues[0]);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::Configure{{{1*/
+void TriaP1Input::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Inputs/TriaP1Input.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Inputs/TriaP1Input.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Inputs/TriaP1Input.h	(revision 11330)
@@ -0,0 +1,89 @@
+/*! \file TriaP1Input.h 
+ *  \brief: header file for TriaP1Input object
+ */
+
+
+#ifndef _TRIAP1INPUT_H_
+#define _TRIAP1INPUT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Input.h"
+#include "../Elements/TriaRef.h"
+class GaussTria;
+/*}}}*/
+
+class TriaP1Input: public Input,public TriaRef{
+
+	public:
+		/*just hold 3 values for 3 vertices: */
+		int    enum_type;
+		double values[3];
+
+		/*TriaP1Input constructors, destructors: {{{1*/
+		TriaP1Input();
+		TriaP1Input(int enum_type,double* values);
+		~TriaP1Input();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*TriaP1Input management: {{{1*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB);
+		Input* PointwiseMax(Input* inputB);
+		ElementResult* SpawnResult(int step, double time);
+		void AddTimeValues(double* values,int step,double time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{1*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");}
+		void GetInputValue(int* pvalue){_error_("not implemented yet");}
+		void GetInputValue(double* pvalue){_error_("not implemented yet");}
+		void GetInputValue(double* pvalue,GaussTria* gauss);
+		void GetInputValue(double* pvalue,GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(double* pvalue,GaussPenta* gauss,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(double* derivativevalues, double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputAverage(double* pvalue);
+		void GetVxStrainRate2d(double* epsilonvx,double* xyz_list, GaussTria* gauss);
+		void GetVyStrainRate2d(double* epsilonvy,double* xyz_list, GaussTria* gauss);
+		void GetVxStrainRate3d(double* epsilonvx,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(double* epsilonvy,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(double* epsilonvz,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(double* epsilonvx,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(double* epsilonvy,double* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+
+		void SquareMin(double* psquaremin, bool process_units,Parameters* parameters);
+		void ConstrainMin(double minimum);
+		void Scale(double scale_factor);
+		void ArtificialNoise(double min,double max);
+		void AXPY(Input* xinput,double scalar);
+		void Constrain(double cm_min, double cm_max);
+		double InfinityNorm(void);
+		double Max(void);
+		double MaxAbs(void);
+		double Min(void);
+		double MinAbs(void);
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vec vector,int* doflist);
+		void GetValuesPtr(double** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _TRIAP1INPUT_H */
Index: /issm/trunk-jpl-damage/src/c/objects/IoModel.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/IoModel.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/IoModel.cpp	(revision 11330)
@@ -0,0 +1,1063 @@
+/*! \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 "./objects.h"
+#include "../io/io.h"
+#include "./Container/Parameters.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../include/include.h"
+
+/*FUNCTION IoModel::IoModel(){{{1*/
+IoModel::IoModel(){
+	this->fid=NULL;
+	this->data=NULL;
+	this->constants=NULL;
+	
+	this->my_elements=NULL;
+	this->my_nodes=NULL;
+	this->my_vertices=NULL;
+	this->singlenodetoelementconnectivity=NULL;
+	this->numbernodetoelementconnectivity=NULL;
+	
+	this->nodecounter=0;
+	this->loadcounter=0;
+	this->constraintcounter=0;
+}
+/*}}}*/
+/*FUNCTION IoModel::IoModel(FILE*  iomodel_handle){{{1*/
+IoModel::IoModel(FILE* iomodel_handle){
+	
+	/*First, keep track of the file handle: */
+	this->fid=iomodel_handle;
+
+	/*Initialize and read constants:*/
+	this->constants=new Parameters();
+	this->FetchConstants(); /*this routine goes through the input file, and fetches bools, ints, doubles and strings only, nothing memory intensive*/
+
+	/*Initialize data: */
+	this->data=(double**)xmalloc(MaximumNumberOfEnums*sizeof(double*));
+	for(int i=0;i<MaximumNumberOfEnums;i++) this->data[i]=NULL;
+	
+	/*Initialize permanent data: */
+	this->my_elements=NULL;
+	this->my_nodes=NULL;
+	this->my_vertices=NULL;
+	this->singlenodetoelementconnectivity=NULL;
+	this->numbernodetoelementconnectivity=NULL;
+	
+	this->nodecounter=0;
+	this->loadcounter=0;
+	this->constraintcounter=0;
+}
+/*}}}*/
+/*FUNCTION IoModel::~IoModel(){{{1*/
+IoModel::~IoModel(){
+
+	delete this->constants;
+
+	/*Some checks in debugging mode*/
+	#ifdef _ISSM_DEBUG_
+	for(int i=0;i<MaximumNumberOfEnums;i++){
+		if(this->data[i]){
+			_printf_("Info: previous pointer of %s has not been freed (DeleteData has not been called)",EnumToStringx(i));
+		}
+	}
+	#endif
+
+	xfree((void**)&this->data);
+
+	xfree((void**)&this->my_elements);
+	xfree((void**)&this->my_nodes);
+	xfree((void**)&this->my_vertices);
+	xfree((void**)&this->singlenodetoelementconnectivity);
+	xfree((void**)&this->numbernodetoelementconnectivity);
+}
+/*}}}*/
+
+/*FUNCTION IoModel::Constant(bool* poutput,int constant_enum){{{1*/
+void IoModel::Constant(bool* poutput,int constant_enum){
+
+	_assert_(constant_enum>=0);
+	_assert_(this->constants);
+
+	this->constants->FindParam(poutput,constant_enum);
+}
+/*}}}*/
+/*FUNCTION IoModel::Constant(int* poutput,int constant_enum){{{1*/
+void IoModel::Constant(int* poutput,int constant_enum){
+
+	_assert_(constant_enum>=0);
+	_assert_(this->constants);
+
+	this->constants->FindParam(poutput,constant_enum);
+}
+/*}}}*/
+/*FUNCTION IoModel::Constant(double* poutput,int constant_enum){{{1*/
+void IoModel::Constant(double* poutput,int constant_enum){
+
+	_assert_(constant_enum>=0);
+	_assert_(this->constants);
+
+	this->constants->FindParam(poutput,constant_enum);
+}
+/*}}}*/
+/*FUNCTION IoModel::Constant(char** poutput,int constant_enum){{{1*/
+void IoModel::Constant(char** poutput,int constant_enum){
+
+	_assert_(constant_enum>=0);
+	_assert_(this->constants);
+
+	this->constants->FindParam(poutput,constant_enum);
+}
+/*}}}*/
+/*FUNCTION IoModel::CopyConstantObject{{{1*/
+Param* IoModel::CopyConstantObject(int constant_enum){
+
+	_assert_(this->constants);
+
+	/*Find constant*/
+	Param* param=(Param*)this->constants->FindParamObject(constant_enum);
+	if(!param) _error_("Constant %s not found in iomodel",EnumToStringx(constant_enum));
+
+	return (Param*)param->copy();
+}
+/*}}}*/
+/*FUNCTION IoModel::Data{{{1*/
+double* IoModel::Data(int data_enum){
+
+	_assert_(data_enum<MaximumNumberOfEnums);
+	_assert_(data_enum>=0);
+
+	return this->data[data_enum];
+}
+/*}}}*/
+/*FUNCTION IoModel::DeleteData{{{1*/
+void  IoModel::DeleteData(int num,...){
+
+	va_list ap;
+	int     dataenum;
+	int     i;
+	DoubleMatParam* parameter=NULL;
+
+	/*Go through the entire list of enums and delete the corresponding data from the iomodel-data dataset: */
+
+	va_start(ap,num);
+	for(i = 0; i <num; i++){
+		dataenum=va_arg(ap, int);
+		_assert_(dataenum<MaximumNumberOfEnums);
+		xfree((void**)&this->data[dataenum]);
+	}
+	va_end(ap);
+} /*}}}*/
+/*FUNCTION IoModel::FetchConstants{{{1*/
+void  IoModel::FetchConstants(void){
+
+	extern int my_rank;
+	extern int num_procs;
+	
+	/*record descriptions; */
+	int record_enum;
+	int record_length;
+	int record_code; //1 to 7 number
+
+	/*records: */
+	int  booleanint=0;
+	int  integer=0;
+	double scalar=0;
+	char* string=NULL;
+	int   string_size;
+
+	/*Check that some fields have been allocated*/
+	_assert_(this->fid || my_rank);
+	_assert_(this->constants);
+
+	/*Go find in the binary file, the position of the data we want to fetch: */
+	if(my_rank==0){ //cpu 0{{{2
+	
+		/*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,double 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
+				MPI_Bcast(&record_code,1,MPI_INT,0,MPI_COMM_WORLD);  /*tell others cpus we are bailing: */
+				break;
+			}
+			else{
+			
+				/* Read the record length and the data type code: */
+				fread(&record_length,sizeof(int),1,this->fid);
+				fread(&record_code,sizeof(int),1,this->fid);
+					
+				/*Tell other cpus what we are doing: */
+				MPI_Bcast(&record_code,1,MPI_INT,0,MPI_COMM_WORLD);  /*tell other cpus what we are going to do: */
+
+				/*Tell other cpus the name of the data, then branch according to the data type: */
+				MPI_Bcast(&record_enum,1,MPI_INT,0,MPI_COMM_WORLD);  
+				MPI_Bcast(&record_length,1,MPI_INT,0,MPI_COMM_WORLD);  
+				
+
+				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 ");
+						MPI_Bcast(&booleanint,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+						/*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 ");
+						MPI_Bcast(&integer,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+						/*create IntParam: */
+						this->constants->AddObject(new IntParam(record_enum,integer));
+
+						break;
+					case 3:
+						/*Read the scalar and broadcast it to other cpus:*/
+						if(fread(&scalar,sizeof(double),1,this->fid)!=1) _error_(" could not read scalar ");
+						MPI_Bcast(&scalar,1,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+
+						/*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 ");
+						MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+						if(string_size){
+							string=(char*)xmalloc((string_size+1)*sizeof(char));
+							string[string_size]='\0';
+
+							/*Read string, then broadcast: */
+							if(fread(string,string_size*sizeof(char),1,this->fid)!=1)_error_("  could not read string ");
+							MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD); 
+						}
+						else{
+							string=(char*)xmalloc(sizeof(char));
+							string[0]='\0';
+						}
+						
+						/*Add string to parameters: */
+						this->constants->AddObject(new StringParam(record_enum,string));
+
+						/*Free string*/
+						xfree((void**)&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_("%s%i","unknown record type:",record_code); 
+						break;;
+				}
+			}
+		}
+	} //}}}
+	else{ //cpu ~0 {{{2
+		for(;;){ //wait on cpu 0
+			MPI_Bcast(&record_code,1,MPI_INT,0,MPI_COMM_WORLD);  /*get from cpu 0 what we are going to do: */
+			if(record_code==0){
+				break; //we are done, break from the loop
+			}
+			else{
+				MPI_Bcast(&record_enum,1,MPI_INT,0,MPI_COMM_WORLD);   //get from cpu 0 name of the data
+				MPI_Bcast(&record_length,1,MPI_INT,0,MPI_COMM_WORLD);  
+				switch(record_code){
+				case 1: 
+					/*boolean. get it from cpu 0 */
+					MPI_Bcast(&booleanint,1,MPI_INT,0,MPI_COMM_WORLD); 
+						
+					/*create BoolParam: */
+					this->constants->AddObject(new BoolParam(record_enum,(bool)booleanint)); //cast to a boolean
+					break;
+
+				case 2:
+					/*integer. get it from cpu 0 */
+					MPI_Bcast(&integer,1,MPI_INT,0,MPI_COMM_WORLD); 
+						
+					/*create IntParam: */
+					this->constants->AddObject(new IntParam(record_enum,integer));
+
+					break;
+				case 3:
+					/*scalar. get it from cpu 0 */
+					MPI_Bcast(&scalar,1,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+						
+					/*create DoubleParam: */
+					this->constants->AddObject(new DoubleParam(record_enum,scalar));
+
+					break;
+				case 4: 
+					MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD); 
+					if(string_size){
+						string=(char*)xmalloc((string_size+1)*sizeof(char));
+						string[string_size]='\0';
+
+						/*Read string from cpu 0: */
+						MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD); 
+					}
+					else{
+						string=(char*)xmalloc(sizeof(char));
+						string[0]='\0';
+					}
+					/*Add string to parameters: */
+					this->constants->AddObject(new StringParam(record_enum,string));
+
+					/*Free string*/
+					xfree((void**)&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_("%s%i","unknown record type:",record_code); 
+					break;;
+				}
+
+
+			}
+		}
+	} //}}}
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(bool*     pbool,int data_enum){{{1*/
+void  IoModel::FetchData(bool* pboolean,int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+	
+
+	/*output: */
+	int   booleanint;
+	int   code;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
+
+	if(code!=1)_error_("expecting a boolean for enum %s",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 ");
+	}
+	MPI_Bcast(&booleanint,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+	/*cast to bool: */
+	/*Assign output pointers: */
+	*pboolean=(bool)booleanint;
+
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(int*      pinteger,int data_enum){{{1*/
+void  IoModel::FetchData(int* pinteger,int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+	
+
+	/*output: */
+	int   integer;
+	int   code;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
+	
+	if(code!=2)_error_("expecting an integer for enum %s",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 ");
+	}
+
+	MPI_Bcast(&integer,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+	/*Assign output pointers: */
+	*pinteger=integer;
+
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(double*   pscalar,int data_enum){{{1*/
+void  IoModel::FetchData(double* pscalar,int data_enum){
+
+
+	extern int my_rank;
+	extern int num_procs;
+	
+
+	/*output: */
+	double   scalar;
+	int      code;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
+	
+	if(code!=3)_error_("expecting a double for enum %s",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(double),1,fid)!=1)_error_(" could not read scalar ");
+	}
+	MPI_Bcast(&scalar,1,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+
+	/*Assign output pointers: */
+	*pscalar=scalar;
+		 
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(char**    pstring,int data_enum){{{1*/
+void  IoModel::FetchData(char** pstring,int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+	
+
+	/*output: */
+	char* string=NULL;
+	int   string_size;
+	int code=0;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
+	
+	if(code!=4)_error_("expecting a string for enum %s",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 ");
+	}
+
+	MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+	/*Now allocate string: */
+	if(string_size){
+		string=(char*)xmalloc((string_size+1)*sizeof(char));
+		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 ");
+		}
+		MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD); 
+	}
+	else{
+		string=(char*)xmalloc(sizeof(char));
+		string[0]='\0';
+	}
+
+
+	/*Assign output pointers: */
+	*pstring=string;
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(int**  pintegerematrix,int* pM,int* pN,int data_enum){{{1*/
+void  IoModel::FetchData(int** pmatrix,int* pM,int* pN,int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+	int i,j;
+
+	/*output: */
+	int M,N;
+	double* matrix=NULL;
+	int*    integer_matrix=NULL;
+	int code=0;
+	int vector_type=0;
+	
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,&vector_type,data_enum);
+
+	if((code!=5) && (code!=6) && (code!=7))_error_("expecting a double, integer or boolean matrix for enum %s",EnumToStringx(data_enum));
+	
+	/*Now fetch: */
+
+	/*We have to read a matrix from disk. First read the dimensions of the matrix, then the whole matrix: */
+	/*numberofelements: */
+	if(my_rank==0){  
+		if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows for matrix ");
+	}
+
+	MPI_Bcast(&M,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+	if(my_rank==0){  
+		if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
+	}
+	MPI_Bcast(&N,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+	/*Now allocate matrix: */
+	if(M*N){
+		matrix=(double*)xmalloc(M*N*sizeof(double));
+
+		/*Read matrix on node 0, then broadcast: */
+		if(my_rank==0){  
+			if(fread(matrix,M*N*sizeof(double),1,fid)!=1) _error_("could not read matrix ");
+		}
+		
+		MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+	}
+
+	/*Now cast to integer: */
+	if(M*N){
+		integer_matrix=(int*)xmalloc(M*N*sizeof(int));
+		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:*/
+	xfree((void**)&matrix);
+
+	/*Assign output pointers: */
+	*pmatrix=integer_matrix;
+	if (pM)*pM=M;
+	if (pN)*pN=N;
+
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(double**  pdoublematrix,int* pM,int* pN,int data_enum){{{1*/
+void  IoModel::FetchData(double** pmatrix,int* pM,int* pN,int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+
+	/*output: */
+	int M,N;
+	double* matrix=NULL;
+	int code=0;
+	int vector_type=0;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,&vector_type,data_enum);
+	if((code!=5) && (code!=6) && (code!=7))_error_("expecting a double, integer or boolean matrix for enum %s",EnumToStringx(data_enum));
+	
+	/*Now fetch: */
+
+	/*We have to read a matrix from disk. First read the dimensions of the matrix, then the whole matrix: */
+	/*numberofelements: */
+	if(my_rank==0){  
+		if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows for matrix ");
+	}
+	MPI_Bcast(&M,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+	if(my_rank==0){  
+		if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
+	}
+	MPI_Bcast(&N,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+	/*Now allocate matrix: */
+	if(M*N){
+		matrix=(double*)xmalloc(M*N*sizeof(double));
+
+		/*Read matrix on node 0, then broadcast: */
+		if(my_rank==0){  
+			if(fread(matrix,M*N*sizeof(double),1,fid)!=1) _error_("could not read matrix ");
+		}
+		MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+	}
+
+	/*Assign output pointers: */
+	*pmatrix=matrix;
+	if (pM)*pM=M;
+	if (pN)*pN=N;
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(char***   pstrings,int* pnumstrings,int data_enum){{{1*/
+void  IoModel::FetchData(char*** pstrings,int* pnumstrings,int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+	
+	int i;
+
+	/*output: */
+	int   numstrings=0;
+	char** strings=NULL;
+	
+	/*intermediary: */
+	char* string=NULL;
+	int   string_size;
+	int   code;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
+	
+	if(code!=9)_error_("expecting a string array for enum %s",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");
+	}
+	MPI_Bcast(&numstrings,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+	/*Now allocate string array: */
+	if(numstrings){
+		strings=(char**)xmalloc(numstrings*sizeof(char*));
+		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 ");
+			}
+			MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD); 
+			if(string_size){
+				string=(char*)xmalloc((string_size+1)*sizeof(char));
+				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 ");
+				}
+				MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD); 
+			}
+			else{
+				string=(char*)xmalloc(sizeof(char));
+				string[0]='\0';
+			}
+
+			strings[i]=string;
+		}
+	}
+
+	/*Assign output pointers: */
+	*pstrings=strings;
+	*pnumstrings=numstrings;
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(double*** pmatrices,int** pmdims,int** pndims, int* pM,int data_enum){{{1*/
+void  IoModel::FetchData(double*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum){
+
+	int i;
+
+	extern int my_rank;
+	extern int num_procs;
+
+	/*output: */
+	double** matrices=NULL;
+	int*     mdims=NULL;
+	int*     ndims=NULL;
+	int      numrecords=0;
+
+	/*intermediary: */
+	int     M, N;
+	double *matrix = NULL;
+	int     code;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
+	if(code!=8)_error_("expecting a double mat array for enum %s",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 ");
+	}
+	MPI_Bcast(&numrecords,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+	if(numrecords){
+
+		/*Allocate matrices :*/
+		matrices=(double**)xmalloc(numrecords*sizeof(double*));
+		mdims=(int*)xmalloc(numrecords*sizeof(int));
+		ndims=(int*)xmalloc(numrecords*sizeof(int));
+
+		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_("%s%i%s","could not read number of rows in ",i,"th matrix of matrix array");
+			}
+			MPI_Bcast(&M,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+			if(my_rank==0){  
+				if(fread(&N,sizeof(int),1,fid)!=1) _error_("%s%i%s","could not read number of columns in ",i,"th matrix of matrix array");
+			}
+			MPI_Bcast(&N,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+			/*Now allocate matrix: */
+			if(M*N){
+				matrix=(double*)xmalloc(M*N*sizeof(double));
+
+				/*Read matrix on node 0, then broadcast: */
+				if(my_rank==0){  
+					if(fread(matrix,M*N*sizeof(double),1,fid)!=1) _error_("could not read matrix ");
+				}
+
+				MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+			}
+
+			/*Assign: */
+			matrices[i]=matrix;
+			mdims[i]=M;
+			ndims[i]=N;
+		}
+	}
+
+	/*Assign output pointers: */
+	*pmatrices=matrices;
+	*pmdims=mdims;
+	*pndims=ndims;
+	*pnumrecords=numrecords;
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(int num,...){{{1*/
+void  IoModel::FetchData(int num,...){
+
+	va_list ap;
+	int     dataenum;
+	double* 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 double* : */
+	
+	va_start(ap,num);
+	for(i=0; i<num; i++){
+		
+		dataenum=va_arg(ap, int);
+
+		/*Some checks in debugging mode*/
+		/*{{{*/
+		#ifdef _ISSM_DEBUG_
+		_assert_(dataenum<MaximumNumberOfEnums);
+		if(this->data[dataenum]){
+			_error_("Info: trying to fetch %s but previous pointer has not been freed (DeleteData has not been called)",EnumToStringx(dataenum));
+		}
+		#endif
+		/*}}}*/
+
+		/*Add to this->data: */
+		this->FetchData(&matrix,&M,&N,dataenum);
+		this->data[dataenum]=matrix;
+	}
+	va_end(ap);
+
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchDataToInput{{{1*/
+void IoModel::FetchDataToInput(Elements* elements,int vector_enum,int default_vector_enum,double default_value){
+
+	/*intermediary: */
+	int     i;
+	bool    defaulting    = false;
+	bool    transient     = false;
+
+	FILE   *fid           = NULL;
+	int     code          = 0;
+	int     vector_layout = 0;
+	int     counter;
+	int     nods;
+	int     nel;
+	int     numberofelements;
+
+
+	/*variables being fetched: */
+	bool    boolean;
+	int     integer;
+	double  scalar;
+	char   *string        = NULL;
+	double *doublevector  = NULL;
+	int     M,N;
+
+	/*Fetch parameters: */
+	this->constants->FindParam(&numberofelements,MeshNumberofelementsEnum);
+
+	/*First of, find the record for the enum, and get code  of data type: */
+	fid=this->SetFilePointerToData(&code, &vector_layout,vector_enum);
+
+	switch(code){
+		case 1: //boolean constant.  {{{2
+			this->FetchData(&boolean,vector_enum);
+
+			/*Add boolean constant input to all elements: */
+			counter=0;
+			for (i=0;i<numberofelements;i++){
+				if(this->my_elements[i]){
+					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					element->InputCreate((double)boolean,vector_enum,code); 
+					counter++;
+				}
+			}
+			break; /*}}}*/
+		case 2: //integer constant.  {{{2
+			this->FetchData(&integer,vector_enum);
+
+			/*Add integer constant input to all elements: */
+			counter=0;
+			for (i=0;i<numberofelements;i++){
+				if(this->my_elements[i]){
+					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					element->InputCreate((double)integer,vector_enum,code); 
+					counter++;
+				}
+			}
+			break; /*}}}*/
+		case 3: //double constant.  {{{2
+			this->FetchData(&scalar,vector_enum);
+
+			/*Add double constant input to all elements: */
+			counter=0;
+			for (i=0;i<numberofelements;i++){
+				if(this->my_elements[i]){
+					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					element->InputCreate(scalar,vector_enum,code); 
+					counter++;
+				}
+			}
+			break; /*}}}*/
+		case 5: //boolean vector.  {{{2
+
+			/*Fetch vector:*/
+			this->FetchData(&doublevector,&M,&N,vector_enum); //we still have a doublevector, because it might include times in transient mode
+			/*Check we got something, otherwise fetch default: */
+			if(doublevector){ 
+				defaulting=false;  //we are not defaulting, because  we do have a vector
+			}
+			else{
+				/*do we have a default enum to go fetch? */
+				if(default_vector_enum!=NoneEnum){
+					/*yes. fetch it: */
+					this->FetchData(&doublevector,&M,&N,default_vector_enum);
+					if(doublevector){
+						defaulting=false;  //we are not defaulting, because  we do have a vector
+					}
+					else{
+						/*even the default vector is non existent. we are defaulting to the default value: */
+						defaulting=true;
+					}
+				}
+				else{
+					/*we are left with the default value: */
+					defaulting=true;
+				}
+			}
+
+			/*Create inputs:*/
+			counter=0;
+			for (i=0;i<numberofelements;i++){
+				if(this->my_elements[i]){
+					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					if(defaulting) element->InputCreate(default_value,vector_enum,code); 
+					else           element->InputCreate(doublevector,i,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+					counter++;
+				}
+			}
+			break; /*}}}*/
+		case 6: //int vector.  {{{2
+
+			/*Fetch vector:*/
+			this->FetchData(&doublevector,&M,&N,vector_enum); //we still have a doublevector, because it might include times in transient mode
+			/*Check we got something, otherwise fetch default: */
+			if(doublevector){ 
+				defaulting=false;  //we are not defaulting, because  we do have a vector
+			}
+			else{
+				/*do we have a default enum to go fetch? */
+				if(default_vector_enum!=NoneEnum){
+					/*yes. fetch it: */
+					this->FetchData(&doublevector,&M,&N,default_vector_enum);
+					if(doublevector){
+						defaulting=false;  //we are not defaulting, because  we do have a vector
+					}
+					else{
+						/*even the default vector is non existent. we are defaulting to the default value: */
+						defaulting=true;
+					}
+				}
+				else{
+					/*we are left with the default value: */
+					defaulting=true;
+				}
+			}
+
+			/*Create inputs:*/
+			counter=0;
+			for (i=0;i<numberofelements;i++){
+				if(this->my_elements[i]){
+					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					if(defaulting) element->InputCreate(default_value,vector_enum,code); 
+					else           element->InputCreate(doublevector,i,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+					counter++;
+				}
+			}
+			break; /*}}}*/
+		case 7: //double vector.  {{{2
+
+			/*Fetch vector:*/
+			this->FetchData(&doublevector,&M,&N,vector_enum);
+			/*Check we got something, otherwise fetch default: */
+			if(doublevector){ 
+				defaulting=false;  //we are not defaulting, because  we do have a vector
+			}
+			else{
+				/*do we have a default enum to go fetch? */
+				if(default_vector_enum!=NoneEnum){
+					/*yes. fetch it: */
+					this->FetchData(&doublevector,&M,&N,default_vector_enum);
+					if(doublevector){
+						defaulting=false;  //we are not defaulting, because  we do have a vector
+					}
+					else{
+						/*even the default vector is non existent. we are defaulting to the default value: */
+						defaulting=true;
+					}
+				}
+				else{
+					/*we are left with the default value: */
+					defaulting=true;
+				}
+			}
+
+			/*Create inputs:*/
+			counter=0;
+			for (i=0;i<numberofelements;i++){
+				if(this->my_elements[i]){
+					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					if(defaulting) element->InputCreate(default_value,vector_enum,code); 
+					else           element->InputCreate(doublevector,i,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+					counter++;
+				}
+			}
+
+			break; /*}}}*/
+		default: /*{{{2*/
+			_error_("%s%i%s","data code ",code," not supported yet!");
+			break;
+			/*}}}*/
+	}
+	/*Free ressources:*/
+	xfree((void**)&doublevector);
+	xfree((void**)&string);
+}
+/*FUNCTION IoModel::SetFilePointerToData{{{1*/
+FILE* IoModel::SetFilePointerToData(int* pcode,int* pvector_type, int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+	
+	int found=0;
+	int record_enum;
+	int record_length;
+	int record_code; //1 to 7 number
+	int vector_type; //nodal or elementary
+ 
+	/*Go find in the binary file, the position of the data we want to fetch: */
+	if(my_rank==0){
+	
+		/*First set FILE* position to the beginning of the file: */
+		fseek(fid,0,SEEK_SET);
+
+		/*Now march through file looking for the correct data identifier: */
+		for(;;){
+			/*Read enum for this size of first string name: */
+			if(fread(&record_enum,sizeof(int),1,fid)==0){
+				/*Ok, we have reached the end of the file. break: */
+				found=0;
+				break;
+			}
+			
+			/*Is this the record sought for? : */
+			if (data_enum==record_enum){
+				/*Ok, we have found the correct string. Pass the record length, and read data type code: */
+				fseek(fid,sizeof(int),SEEK_CUR);
+				fread(&record_code,sizeof(int),1,fid);
+
+				/*if record_code points to a vector, get its type (nodal or elementary): */
+				if(5<=record_code && record_code<=7)fread(&vector_type,sizeof(int),1,fid);
+				found=1;
+				break;
+			}
+			else{
+				/*This is not the correct string, read the record length, and use it to skip this record: */
+				fread(&record_length,sizeof(int),1,fid);
+				/*skip: */
+				fseek(fid,record_length,SEEK_CUR);
+			}
+		}
+	}
+	MPI_Bcast(&found,1,MPI_INT,0,MPI_COMM_WORLD); 
+	if(!found)_error_("%s %s ","could not find data with name",EnumToStringx(data_enum));
+
+	/*Broadcast code and vector type: */
+	MPI_Bcast(&record_code,1,MPI_INT,0,MPI_COMM_WORLD); 
+	MPI_Bcast(&vector_type,1,MPI_INT,0,MPI_COMM_WORLD); 
+	if(record_code==5) MPI_Bcast(&vector_type,1,MPI_INT,0,MPI_COMM_WORLD); 
+
+	/*Assign output pointers:*/
+	*pcode=record_code;
+	if(pvector_type)*pvector_type=vector_type;
+
+	return fid;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/IoModel.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/IoModel.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/IoModel.h	(revision 11330)
@@ -0,0 +1,64 @@
+/* \file IoModel.h
+ * \brief  Header file defining the IoModel structure that will help in processing the input data coming 
+ * into ISSM, from Matlab, or through a binary file opened for reading.
+ * \sa IoModel.cpp
+ */
+
+#ifndef _IOMODEL_H
+#define _IOMODEL_H
+
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+class Elements;
+class Param;
+
+
+class IoModel {
+
+	private: 
+		FILE        *fid;         //pointer to input file
+		double     **data;        //this dataset holds temporary data, memory intensive.
+		Parameters  *constants;   //this dataset holds all double, int, bool and char *parameters read in from the input file.*
+
+	public:
+		/*This data needs to stay memory resident at all time, even if it's memory intensive: */
+		bool *my_elements;
+		bool *my_nodes;
+		int  *my_vertices;
+		int  *singlenodetoelementconnectivity;
+		int  *numbernodetoelementconnectivity;
+
+		/*Data to synchronize through low level object drivers: */
+		int nodecounter;         //keep track of how many nodes are being created in each analysis type
+		int loadcounter;         //keep track of how many loads are being created in each analysis type
+		int constraintcounter;   //keep track of how many constraints are being created in each analysis type
+
+		/*Methods*/
+		~IoModel();
+		IoModel();
+		IoModel(FILE* iomodel_handle);
+
+		/*Input/Output*/
+		void        Constant(bool   *poutput,int constant_enum);
+		void        Constant(int    *poutput,int constant_enum);
+		void        Constant(double *poutput,int constant_enum);
+		void        Constant(char  **poutput,int constant_enum);
+		Param      *CopyConstantObject(int constant_enum);
+		double     *Data(int dataenum);
+		void        DeleteData(int num,...);
+		void        FetchConstants(void);
+		void        FetchData(bool*     pboolean,int data_enum);
+		void        FetchData(int*      pinteger,int data_enum);
+		void        FetchData(double*   pscalar,int data_enum);
+		void        FetchData(char**    pstring,int data_enum);
+		void        FetchData(int** pmatrix,int* pM,int* pN,int data_enum);
+		void        FetchData(double**  pscalarmatrix,int* pM,int* pN,int data_enum);
+		void        FetchData(char***   pstringarray,int* pnumstrings,int data_enum);
+		void        FetchData(double*** pmatrixarray,int** pmdims,int** pndims, int* pnumrecords,int data_enum);
+		void        FetchData(int num,...);
+		void        FetchDataToInput(Elements* elements,int vector_enum,int default_vector_enum=NoneEnum,double default_value=0);
+		FILE*       SetFilePointerToData(int* pcode,int* pvector_type, int data_enum);
+};
+
+#endif  /* _IOMODEL_H */
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KMLFileReadUtils.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KMLFileReadUtils.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KMLFileReadUtils.cpp	(revision 11330)
@@ -0,0 +1,653 @@
+/*!\file KMLFileUtils.cpp
+ * \brief: utilities for kml file reading.
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*FUNCTION  KMLFileToken(FILE* fid,int* pncom=NULL,char*** ppcom=NULL) {{{1*/
+char* KMLFileToken(FILE* fid,
+				   int* pncom=NULL,char*** ppcom=NULL){
+
+/*  get the next token (tag or field) in the file  */
+
+	bool    inew=1,itag=0,ifield=0;
+	int     c;
+	int     ibuf=0,buflen=1024,bufblk=1024;
+	char    *buffer=NULL,*bufferc=NULL;
+
+	buffer=(char *) xmalloc(buflen*sizeof(char));
+	buffer[0]='\0';
+
+/*  read kml file character-by-character  */
+
+//  note that fgets includes newline
+//	fgets(buffer,buflen,fid);
+
+	while ((c=getc(fid)) != EOF) {
+		/*  ignore leading blanks  */
+		if (inew && isspace(c))
+			continue;
+
+		/*  distinguish between tag or field  */
+		if (!itag && !ifield) {
+
+			/*  distinguish between tag or comment  */
+			if (c == '<') {
+				ungetc(c,fid);
+				if (!(bufferc=KMLFileTokenComment(fid))) {
+					c=getc(fid);
+					itag=1;
+				}
+				else {
+					if (pncom && ppcom) {
+						(*pncom)++;
+						*ppcom=(char **) xrealloc(*ppcom,*pncom*sizeof(char*));
+						(*ppcom)[*pncom-1]=bufferc;
+					}
+					else
+						xfree((void**)&bufferc);
+					inew=1;
+					continue;
+				}
+			}
+			else
+				ifield=1;
+			inew=0;
+			KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+							   c,
+							   bufblk);
+		}
+
+		/*  accumulate tag, not including newlines  */
+		else if (itag) {
+			if (c != '\n') {
+				inew=0;
+				KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+								   c,
+								   bufblk);
+				if (c == '>')
+					break;
+			}
+			else
+				inew=1;
+		}
+
+		/*  accumulate field, including newlines  */
+		else if (ifield) {
+			/*  distinguish between another tag or comment  */
+			if (c == '<') {
+				ungetc(c,fid);
+				if (!(bufferc=KMLFileTokenComment(fid)))
+					break;
+				else
+					if (pncom && ppcom) {
+						(*pncom)++;
+						*ppcom=(char **) xrealloc(*ppcom,*pncom*sizeof(char*));
+						(*ppcom)[*pncom-1]=bufferc;
+					}
+					else
+						xfree((void**)&bufferc);
+			}
+			else {
+				inew=0;
+				KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+								   c,
+								   bufblk);
+				if (c == '\n')
+					inew=1;
+			}
+		}
+
+	}
+
+/*  remove trailing blanks or newline  */
+
+	while (ibuf > 0)
+		if (isspace(buffer[ibuf-1]))
+			ibuf--;
+		else {
+			buffer[ibuf]='\0';
+			break;
+		}
+
+//	if      (itag)
+//		_printf_(true,"tag buffer (length=%d):\n",ibuf);
+//	else if (ifield)
+//		_printf_(true,"field buffer (length=%d):\n",ibuf);
+//	_printf_(true,"%s\n",buffer);
+
+	if (!ibuf)
+		xfree((void**)&buffer);
+
+	return(buffer);
+}
+/*}}}*/
+
+/*FUNCTION  KMLFileTokenComment(FILE* fid) {{{1*/
+char* KMLFileTokenComment(FILE* fid){
+
+/*  check for comment in the file and read it  */
+
+	bool    inew=1;
+	int     i;
+	int     c;
+	int     ibuf=0,buflen=1024,bufblk=1024;
+	char*   buffer=NULL;
+
+	buffer=(char *) xmalloc(buflen*sizeof(char));
+	buffer[0]='\0';
+
+/*  read kml file character-by-character  */
+
+	while ((c=getc(fid)) != EOF) {
+		/*  ignore leading blanks  */
+		if (inew && isspace(c))
+			continue;
+
+		inew=0;
+		KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+						   c,
+						   bufblk);
+
+		/*  check for comment  */
+		if (ibuf <= 4) {
+			if ((ibuf == 1 && buffer[0] != '<') ||
+				(ibuf == 2 && buffer[1] != '!') ||
+				(ibuf == 3 && buffer[2] != '-') ||
+				(ibuf == 4 && buffer[3] != '-')) {
+				for (i=ibuf-1; i>=0; i--)
+					ungetc(buffer[i],fid);
+				xfree((void**)&buffer);
+				return(buffer);
+			}
+		}
+
+		/*  accumulate comment, including newlines  */
+		else
+			if (buffer[ibuf-3]=='-' && buffer[ibuf-2]=='-' && buffer[ibuf-1]=='>')
+				break;
+	}
+
+/*  remove trailing blanks or newline  */
+
+	while (ibuf > 0)
+		if (isspace(buffer[ibuf-1]))
+			ibuf--;
+		else {
+			buffer[ibuf]='\0';
+			break;
+		}
+
+//	_printf_(true,"comment buffer (length=%d):\n",ibuf);
+//	_printf_(true,"%s\n",buffer);
+
+	if (!ibuf)
+		xfree((void**)&buffer);
+
+	return(buffer);
+}
+/*}}}*/
+
+/*FUNCTION  KMLFileTokenBuffer {{{1*/
+void KMLFileTokenBuffer(char** pbuffer,int* pibuf,int* pbuflen,
+						int c,
+						int bufblk){
+
+/*  add the specified character to the token buffer  */
+
+	char*   buffer=NULL;
+
+/*  check buffer length and realloc if necessary  */
+
+	if (*pibuf+2 > *pbuflen) {
+		*pbuflen+=bufblk;
+		*pbuffer=(char *) xrealloc(*pbuffer,*pbuflen*sizeof(char));
+	}
+
+/*  add character and terminator  */
+
+	(*pbuffer)[(*pibuf)++]=c;
+	(*pbuffer)[ *pibuf   ]='\0';
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION  KMLFileTagAttrib {{{1*/
+int KMLFileTagAttrib(KML_Object* kobj,
+					 char* ktag){
+
+/*  for the given tag buffer, read and store the attributes  */
+
+	char*   ktagi;
+	char*   ktokn;
+	char*   ktokv;
+	char    quote[]={'\"','\0'};
+	int     isolo=0;
+
+/*  strtok modifies ktag, so work on copy  */
+
+	ktagi=(char *) xmalloc((strlen(ktag)+1)*sizeof(char));
+	memcpy(ktagi,ktag,(strlen(ktag)+1)*sizeof(char));
+
+/*  loop through tag to find all attributes  */
+
+	/*  return first non blank and move past subsequent blank  */
+	ktokn=strtok(ktagi," ");
+//	_printf_(true,"KMLFileTagAttrib -- initial token=\"%s\".\n",ktokn);
+
+	/*  return next non " =?/>" and move past subsequent " =?/>"  */
+	while (ktokn=strtok(NULL," =?/>")) {
+
+		/*  return next non quote and move past subsequent quote  */
+		ktokv=strtok(NULL,quote);
+//		_printf_(true,"KMLFileTagAttrib -- attribute %s=\"%s\".\n",ktokn,ktokv);
+
+/*  add the attribute to the dataset  */
+
+		if (kobj)
+			kobj->AddAttrib(ktokn,ktokv);
+	}
+
+	xfree((void**)&ktagi);
+
+/*  check for xml declaration, dtd declaration, or solo tag  */
+
+	if ((!strncmp(&ktag[0],"<?"       ,2) && !strncmp(&ktag[strlen(ktag)-2],"?>",2)) ||
+		(!strncmp(&ktag[0],"<!DOCTYPE",9) && !strncmp(&ktag[strlen(ktag)-1], ">",1)) ||
+		(!strncmp(&ktag[0],"<"        ,1) && !strncmp(&ktag[strlen(ktag)-2],"/>",2)))
+		isolo=1;
+//	_printf_(true,"KMLFileTagAttrib -- isolo=%d.\n",isolo);
+
+	return(isolo);
+}
+/*}}}*/
+
+/*FUNCTION  KMLFileTokenParse {{{1*/
+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 %s.\n",ktag);
+
+	sscanf(kstr,"%d",pival);
+	xfree((void**)&kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+			_error_("KMLFileTokenParse -- Missing closing tag for %s.\n",ktag);
+		else
+			xfree((void**)&kstr);
+
+//	_printf_(true,"KMLFileTokenParse -- %s=%d.\n",ktag,*pival);
+
+	return(0);
+}
+/*}}}*/
+
+/*FUNCTION  KMLFileTokenParse {{{1*/
+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 %s.\n",ktag);
+
+	sscanf(kstr,"%d",&ival);
+	*pbval=(bool)ival;
+	xfree((void**)&kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+			_error_("KMLFileTokenParse -- Missing closing tag for %s.\n",ktag);
+		else
+			xfree((void**)&kstr);
+
+//	_printf_(true,"KMLFileTokenParse -- %s=%s.\n",ktag,(*pbval ? "true" : "false"));
+
+	return(0);
+}
+/*}}}*/
+
+/*FUNCTION  KMLFileTokenParse {{{1*/
+char* KMLFileTokenParse(char* pstr,int *m,int maxlen,
+						char* ktag,
+						FILE* fid){
+
+	char*   kstr;
+	char*   pstro=NULL;
+
+/*  get next token and allocate if necessary  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing string field for %s.\n",ktag);
+
+	if (!pstr) {
+		if (maxlen)
+			pstr=(char *) xmalloc((maxlen      +1)*sizeof(char));
+		else
+			pstr=(char *) xmalloc((strlen(kstr)+1)*sizeof(char));
+		pstro=pstr;
+	}
+
+	if (maxlen && (maxlen < strlen(kstr))) {
+		_printf_(true,"KMLFileTokenParse -- string field too short for %s.\n",ktag);
+		_printf_(true,"KMLFileTokenParse -- \"%s\" truncated to %d characters.\n",kstr,maxlen);
+		strncpy(pstr,kstr,maxlen);
+	}
+	else
+		memcpy(pstr,kstr,(strlen(kstr)+1)*sizeof(char));
+
+	xfree((void**)&kstr);
+
+	if (m)
+		*m=strlen(pstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+			_error_("KMLFileTokenParse -- Missing closing tag for %s.\n",ktag);
+		else
+			xfree((void**)&kstr);
+
+//	_printf_(true,"KMLFileTokenParse -- %s=\"%s\".\n",ktag,pstr);
+
+	return(pstro);
+}
+/*}}}*/
+
+/*FUNCTION  KMLFileTokenParse {{{1*/
+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 %s.\n",ktag);
+
+	sscanf(kstr,"%g",pfval);
+	xfree((void**)&kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+			_error_("KMLFileTokenParse -- Missing closing tag for %s.\n",ktag);
+		else
+			xfree((void**)&kstr);
+
+//	_printf_(true,"KMLFileTokenParse -- %s=%g.\n",ktag,*pfval);
+
+	return(0);
+}
+/*}}}*/
+
+/*FUNCTION  KMLFileTokenParse {{{1*/
+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 %s.\n",ktag);
+
+	sscanf(kstr,"%lg",pdval);
+	xfree((void**)&kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+			_error_("KMLFileTokenParse -- Missing closing tag for %s.\n",ktag);
+		else
+			xfree((void**)&kstr);
+
+//	_printf_(true,"KMLFileTokenParse -- %s=%g.\n",ktag,*pdval);
+
+	return(0);
+}
+/*}}}*/
+
+/*FUNCTION  KMLFileTokenParse {{{1*/
+int KMLFileTokenParse(double **pdval,int* m,int maxlen,
+					  char* ktag,
+					  FILE* fid){
+
+	int     i=-1,j;
+	char*   kstr;
+	char*   ktok;
+	char    delim[]={' ',',','\f','\n','\r','\t','\v','\0'};
+
+/*  get next token and allocate if necessary  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing double [m] field for %s.\n",ktag);
+
+	if (!*pdval)
+		if (maxlen)
+			*pdval=(double *) xmalloc(maxlen              *sizeof(double));
+		else
+			*pdval=(double *) xmalloc(((strlen(kstr)+1)/2)*sizeof(double));
+
+/*  loop through string to get all values  */
+
+	ktok=strtok(kstr,delim);
+	while (ktok) {
+		i++;
+		if (maxlen && (maxlen < i+1))
+			_error_("KMLFileTokenParse -- Double [m] field too short for %s.\n",ktag);
+		sscanf(ktok,"%lg",&((*pdval)[i]));
+		ktok=strtok(NULL,delim);
+	}
+	xfree((void**)&kstr);
+
+	if (!maxlen)
+		*pdval=(double *) xrealloc(*pdval,(i+1)*sizeof(double));
+
+	if (m)
+		*m=i+1;
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+			_error_("KMLFileTokenParse -- Missing closing tag for %s.\n",ktag);
+		else
+			xfree((void**)&kstr);
+
+//	_printf_(true,"KMLFileTokenParse -- %s=...\n",ktag);
+//	for (j=0; j<=i; j++)
+//		_printf_(true,"   [%d]: %lg\n",j,(*pdval)[j]);
+
+	return(0);
+}
+/*}}}*/
+
+/*FUNCTION  KMLFileTokenParse {{{1*/
+int KMLFileTokenParse(double (**pdval3)[3],int* m,int maxlen,
+					  char* ktag,
+					  FILE* fid){
+
+	int     i=0,j=-1;
+	char*   kstr;
+	char*   ktok;
+	char    delim[]={' ',',','\f','\n','\r','\t','\v','\0'};
+
+/*  get next token and allocate if necessary  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing double [m x 3] field for %s.\n",ktag);
+
+	if (!*pdval3)
+		if (maxlen)
+			*pdval3=(double (*)[3]) xmalloc((maxlen*3)          *sizeof(double));
+		else
+			*pdval3=(double (*)[3]) xmalloc(((strlen(kstr)+1)/2)*sizeof(double));
+
+/*  loop through string to get all values  */
+
+	ktok=strtok(kstr,delim);
+	while (ktok) {
+		j++;
+		if (j == 3) {
+			i++;
+			j=0;
+			if (maxlen && (maxlen < i+1))
+				_error_("KMLFileTokenParse -- Double [m x 3] field too short for %s.\n",ktag);
+		}
+		sscanf(ktok,"%lg",&((*pdval3)[i][j]));
+		ktok=strtok(NULL,delim);
+	}
+	xfree((void**)&kstr);
+
+	if (!maxlen)
+		*pdval3=(double (*)[3]) xrealloc(*pdval3,((i+1)*3)*sizeof(double));
+
+	if (m)
+		*m=i+1;
+
+	if (j != 2)
+		_printf_(true,"KMLFileTokenParse -- Double [m x 3] field for %s does not have multiple of 3 values.\n",ktag);
+
+/*  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 %s.\n",ktag);
+		else
+			xfree((void**)&kstr);
+
+//	_printf_(true,"KMLFileTokenParse -- %s=...\n",ktag);
+//	for (j=0; j<=i; j++)
+//		_printf_(true,"   [%d][0-2]: %lg,%lg,%lg\n",j,(*pdval3)[j][0],(*pdval3)[j][1],(*pdval3)[j][2]);
+
+	return(0);
+}
+/*}}}*/
+
+/*FUNCTION  KMLFileTagSkip {{{1*/
+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  */
+
+	_printf_(true,"KMLFileTagSkip -- input tag %s.\n",ktag);
+
+/*  if next token is a closing tag, compare to input  */
+
+	while (kstr=KMLFileToken(fid,
+							 NULL,NULL)) {
+		if      ((kstr[0] == '<') &&
+				 (kstr[1] == '/') &&
+				 (!strncmp(&(kstr[2]),&(ktag[1]),(strcspn(ktag," >")-1)/sizeof(char)))) {
+			_printf_(true,"KMLFileTagSkip -- closing tag %s.\n",kstr);
+			xfree((void**)&kstr);
+			return(0);
+		}
+
+/*  if next token is an opening tag, call recursively  */
+
+		else if ((kstr[0] == '<') &&
+				 (kstr[1] != '/')) {
+			_printf_(true,"KMLFileTagSkip -- opening tag %s.\n",kstr);
+			KMLFileTagSkip(kstr,
+						   fid);
+		}
+
+/*  if next token is a closing tag, error out  */
+
+		else if ((kstr[0] == '<') &&
+				 (kstr[1] == '/')) {
+			_error_("KMLFileTagSkip -- Unexpected closing tag %s.\n",kstr);
+		}
+
+		xfree((void**)&kstr);
+	}
+
+	_error_("KMLFileTokenParse -- Corresponding closing tag for %s not found.\n",ktag);
+
+	return(0);
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KMLFileReadUtils.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KMLFileReadUtils.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KMLFileReadUtils.h	(revision 11330)
@@ -0,0 +1,50 @@
+/*!\file:  KMLFileReadUtils.h
+ * \brief: header file for kml file reading utilities.
+ */ 
+
+#ifndef _KMLFILEREADUTILS_H
+#define _KMLFILEREADUTILS_H
+
+/*Headers:{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "../Object.h"
+/*}}}*/
+
+/* local prototypes: */
+char* KMLFileToken(FILE* fid,
+				   int* pncom,char*** ppcom);
+char* KMLFileTokenComment(FILE* fid);
+void KMLFileTokenBuffer(char** pbuffer,int* pibuf,int* pbuflen,
+						int c,
+						int bufblk);
+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,int *m,int maxlen,
+					  char* ktag,
+					  FILE* fid);
+int KMLFileTokenParse(float* pfval,
+					  char* ktag,
+					  FILE* fid);
+int KMLFileTokenParse(double* pdval,
+					  char* ktag,
+					  FILE* fid);
+int KMLFileTokenParse(double **pdval,int* m,int maxlen,
+					  char* ktag,
+					  FILE* fid);
+int KMLFileTokenParse(double (**pdval3)[3],int* m,int maxlen,
+					  char* ktag,
+					  FILE* fid);
+int KMLFileTagSkip(char* ktag,
+				   FILE* fid);
+
+#endif  /* _KMLFILEREADUTILS_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Attribute.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Attribute.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Attribute.cpp	(revision 11330)
@@ -0,0 +1,133 @@
+/*!\file KML_Attribute.cpp
+ * \brief: implementation of the kml_attribute object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Attribute::KML_Attribute(){{{1*/
+KML_Attribute::KML_Attribute(){
+
+	name      =NULL;
+	value     =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::~KML_Attribute(){{{1*/
+KML_Attribute::~KML_Attribute(){
+
+	if (name      ) xfree((void**)&name);
+	if (value     ) xfree((void**)&value);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Attribute::Echo {{{1*/
+void  KML_Attribute::Echo(){
+
+	int   i;
+	bool  flag=true;
+
+	_printf_(flag,"    ");
+	for (i=0;i<10-strlen(name);i++)
+		_printf_(flag," ");
+	_printf_(flag,"%s: \"%s\"\n",name,value);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::DeepEcho {{{1*/
+void  KML_Attribute::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Attribute::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::DeepEcho {{{1*/
+void  KML_Attribute::DeepEcho(const char* indent){
+
+	int   i;
+	bool  flag=true;
+
+	_printf_(flag,"%s    ",indent);
+	for (i=0;i<10-strlen(name);i++)
+		_printf_(flag," ");
+	_printf_(flag,"%s: \"%s\"\n",name,value);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::Write {{{1*/
+void  KML_Attribute::Write(FILE* filout,const char* indent){
+
+//  attributes always written in keyword line of kml_object
+
+	fprintf(filout,"%s%s=\"%s\"",indent,name,value);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::Read {{{1*/
+void  KML_Attribute::Read(FILE* fid,char* kstr){
+
+//  attributes always read in keyword line of kml_object
+
+	;
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::Alloc {{{1*/
+void  KML_Attribute::Alloc(const char* namei,const char* valuei){
+
+	name =(char *) xmalloc((strlen(namei )+1)*sizeof(char));
+	memcpy(name,namei,(strlen(namei)+1)*sizeof(char));
+
+	value=(char *) xmalloc((strlen(valuei)+1)*sizeof(char));
+	memcpy(value,valuei,(strlen(valuei)+1)*sizeof(char));
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::Add {{{1*/
+void  KML_Attribute::Add(DataSet* attrib){
+
+	attrib->AddObject((Object*)this);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::Get {{{1*/
+void  KML_Attribute::Get(char** pvalueo,char* deflt){
+
+	if (!value || !strlen(value)) {
+		*pvalueo=(char *) xmalloc((strlen(deflt)+1)*sizeof(char));
+		memcpy(*pvalueo,deflt,(strlen(deflt)+1)*sizeof(char));
+	}
+	else {
+		*pvalueo=(char *) xmalloc((strlen(value)+1)*sizeof(char));
+		memcpy(*pvalueo,value,(strlen(value)+1)*sizeof(char));
+	}
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Attribute.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Attribute.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Attribute.h	(revision 11330)
@@ -0,0 +1,50 @@
+/*! \file KML_Attribute.h 
+ *  \brief: header file for kml_attribute object
+ */
+
+#ifndef _KML_ATTRIBUTE_H_
+#define _KML_ATTRIBUTE_H_
+
+/*Headers:{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "../Object.h"
+class DataSet;
+/*}}}*/
+
+class KML_Attribute: public Object {
+
+	public:
+
+		char* name;
+		char* value;
+
+		/*KML_Attribute constructors, destructors {{{1*/
+		KML_Attribute();
+		~KML_Attribute();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		virtual void  Echo();
+		virtual void  DeepEcho();
+		virtual void  DeepEcho(const char* indent);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+		/*virtual functions: */
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  Alloc(const char* namei,const char* valuei);
+		void  Add(DataSet* attrib);
+		void  Get(char** pvalueo,char* deflt);
+
+};
+#endif  /* _KML_ATTRIBUTE_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_ColorStyle.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_ColorStyle.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_ColorStyle.cpp	(revision 11330)
@@ -0,0 +1,115 @@
+/*!\file KML_ColorStyle.cpp
+ * \brief: implementation of the kml_colorstyle abstract object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_ColorStyle::KML_ColorStyle(){{{1*/
+KML_ColorStyle::KML_ColorStyle(){
+
+	strcpy(color     ,"ffffffff");
+	strcpy(colormode ,"normal");
+
+}
+/*}}}*/
+/*FUNCTION KML_ColorStyle::~KML_ColorStyle(){{{1*/
+KML_ColorStyle::~KML_ColorStyle(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_ColorStyle::Echo {{{1*/
+void  KML_ColorStyle::Echo(){
+
+	bool  flag=true;
+
+	KML_SubStyle::Echo();
+
+	_printf_(flag,"         color: %s\n"          ,color);
+	_printf_(flag,"     colormode: %s\n"          ,colormode);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_ColorStyle::DeepEcho {{{1*/
+void  KML_ColorStyle::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_ColorStyle::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_ColorStyle::DeepEcho {{{1*/
+void  KML_ColorStyle::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	KML_SubStyle::DeepEcho(indent);
+
+	_printf_(flag,"%s         color: %s\n"          ,indent,color);
+	_printf_(flag,"%s     colormode: %s\n"          ,indent,colormode);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_ColorStyle::Write {{{1*/
+void  KML_ColorStyle::Write(FILE* filout,const char* indent){
+
+	KML_SubStyle::Write(filout,indent);
+
+	if (color     && strlen(color))
+		fprintf(filout,"%s  <color>%s</color>\n",indent,color);
+	if (colormode && strlen(colormode))
+		fprintf(filout,"%s  <colorMode>%s</colorMode>\n",indent,colormode);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_ColorStyle::Read {{{1*/
+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 %s.\n",kstr);
+	else if (strncmp(kstr,"<",1))
+		_error_("KML_ColorStyle::Read -- Unexpected field \"%s\".\n",kstr);
+
+	else if (!strcmp(kstr,"<color>"))
+		KMLFileTokenParse( color     ,NULL,KML_COLORSTYLE_COLOR_LENGTH,
+						  kstr,
+						  fid);
+	else if (!strcmp(kstr,"<colorMode>"))
+		KMLFileTokenParse( colormode ,NULL,KML_COLORSTYLE_COLORMODE_LENGTH,
+						  kstr,
+						  fid);
+
+	else if (!strncmp(kstr,"<",1))
+		KML_SubStyle::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_ColorStyle.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_ColorStyle.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_ColorStyle.h	(revision 11330)
@@ -0,0 +1,48 @@
+/*! \file KML_ColorStyle.h 
+ *  \brief: header file for kml_colorstyle abstract object
+ */
+
+#ifndef _KML_COLORSTYLE_H_
+#define _KML_COLORSTYLE_H_
+
+#define KML_COLORSTYLE_COLOR_LENGTH      8
+#define KML_COLORSTYLE_COLORMODE_LENGTH  6
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_SubStyle.h"
+/*}}}*/
+
+class KML_ColorStyle: public KML_SubStyle {
+
+	public:
+
+		char  color[KML_COLORSTYLE_COLOR_LENGTH+1];
+		char  colormode[KML_COLORSTYLE_COLORMODE_LENGTH+1];
+
+		/*KML_ColorStyle constructors, destructors {{{1*/
+		KML_ColorStyle();
+		~KML_ColorStyle();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_COLORSTYLE_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Comment.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Comment.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Comment.cpp	(revision 11330)
@@ -0,0 +1,118 @@
+/*!\file KML_Comment.cpp
+ * \brief: implementation of the kml_comment object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Comment::KML_Comment(){{{1*/
+KML_Comment::KML_Comment(){
+
+	value     =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_Comment::~KML_Comment(){{{1*/
+KML_Comment::~KML_Comment(){
+
+	if (value     ) xfree((void**)&value);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Comment::Echo {{{1*/
+void  KML_Comment::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"    ");
+	_printf_(flag,"%s\n",value);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::DeepEcho {{{1*/
+void  KML_Comment::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Comment::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::DeepEcho {{{1*/
+void  KML_Comment::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	_printf_(flag,"%s    ",indent);
+	_printf_(flag,"%s\n",value);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::Write {{{1*/
+void  KML_Comment::Write(FILE* filout,const char* indent){
+
+	if (strncmp(&value[0]              ,"<!--",4))
+		fprintf(filout,"%s<!--\n",indent);
+	fprintf(filout,"%s  %s\n",indent,value);
+	if (strncmp(&value[strlen(value)-3],"-->" ,3))
+		fprintf(filout,"%s-->\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::Read {{{1*/
+void  KML_Comment::Read(FILE* fid,char* kstr){
+
+//  comments always read as part of KMLFileToken
+
+	;
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::Alloc {{{1*/
+void  KML_Comment::Alloc(const char* valuei){
+
+	value=(char *) xmalloc((strlen(valuei)+1)*sizeof(char));
+	memcpy(value,valuei,(strlen(valuei)+1)*sizeof(char));
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::Add {{{1*/
+void  KML_Comment::Add(DataSet* commnt){
+
+	commnt->AddObject((Object*)this);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::Get {{{1*/
+void  KML_Comment::Get(char** pvalueo){
+
+	*pvalueo=(char *) xmalloc((strlen(value)+1)*sizeof(char));
+	memcpy(*pvalueo,value,(strlen(value)+1)*sizeof(char));
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Comment.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Comment.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Comment.h	(revision 11330)
@@ -0,0 +1,50 @@
+/*! \file KML_Comment.h 
+ *  \brief: header file for kml_comment object
+ */
+
+#ifndef _KML_COMMENT_H_
+#define _KML_COMMENT_H_
+
+/*Headers:{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "../Object.h"
+class DataSet;
+/*}}}*/
+
+class KML_Comment: public Object {
+
+	public:
+
+		char* name;
+		char* value;
+
+		/*KML_Comment constructors, destructors {{{1*/
+		KML_Comment();
+		~KML_Comment();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		virtual void  Echo();
+		virtual void  DeepEcho();
+		virtual void  DeepEcho(const char* indent);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+		/*virtual functions: */
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  Alloc(const char* valuei);
+		void  Add(DataSet* commnt);
+		void  Get(char** pvalueo);
+
+};
+#endif  /* _KML_COMMENT_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Container.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Container.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Container.cpp	(revision 11330)
@@ -0,0 +1,169 @@
+/*!\file KML_Container.cpp
+ * \brief: implementation of the kml_container abstract object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Container::KML_Container(){{{1*/
+KML_Container::KML_Container(){
+
+	feature   =new DataSet;
+
+}
+/*}}}*/
+/*FUNCTION KML_Container::~KML_Container(){{{1*/
+KML_Container::~KML_Container(){
+
+	if (feature) {
+		delete feature;
+		feature   =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Container::Echo {{{1*/
+void  KML_Container::Echo(){
+
+	bool  flag=true;
+
+	KML_Feature::Echo();
+
+	_printf_(flag,"       feature: (size=%d)\n" ,feature->Size());
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Container::DeepEcho {{{1*/
+void  KML_Container::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Container::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Container::DeepEcho {{{1*/
+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++) {
+			_printf_(flag,"%s       feature: -------- begin [%d] --------\n" ,indent,i);
+			((KML_Feature *)feature->GetObjectByOffset(i))->DeepEcho(indent2);
+			_printf_(flag,"%s       feature: --------  end  [%d] --------\n" ,indent,i);
+		}
+	else
+		_printf_(flag,"%s       feature: [empty]\n"    ,indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Container::Write {{{1*/
+void  KML_Container::Write(FILE* filout,const char* indent){
+
+	int   i;
+	char  indent2[81];
+
+	KML_Feature::Write(filout,indent);
+
+/*  loop over the features for the container  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	for (i=0; i<feature->Size(); i++)
+		((KML_Feature *)feature->GetObjectByOffset(i))->Write(filout,indent2);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Container::Read {{{1*/
+void  KML_Container::Read(FILE* fid,char* kstr){
+
+	KML_Object*  kobj;
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</Container",11)) {
+		xfree((void**)&kstr);
+		return;
+	}
+	else if (!strncmp(kstr,"</",2))
+		_error_("KML_Container::Read -- Unexpected closing tag %s.\n",kstr);
+	else if (strncmp(kstr,"<",1))
+		_error_("KML_Container::Read -- Unexpected field \"%s\".\n",kstr);
+
+	else if (!strncmp(kstr,"<Placemark",10)) {
+		kobj=(KML_Object*)new KML_Placemark();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Folder", 7)) {
+		kobj=(KML_Object*)new KML_Folder();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Document", 9)) {
+		kobj=(KML_Object*)new KML_Document();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<GroundOverlay",14)) {
+		kobj=(KML_Object*)new KML_GroundOverlay();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Feature::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Container::WriteExp {{{1*/
+void  KML_Container::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+
+/*  loop over the features for the container  */
+
+	for (i=0; i<feature->Size(); i++)
+		((KML_Object *)feature->GetObjectByOffset(i))->WriteExp(fid,nstr,sgn,cm,sp);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Container.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Container.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Container.h	(revision 11330)
@@ -0,0 +1,46 @@
+/*! \file KML_Container.h 
+ *  \brief: header file for kml_container abstract object
+ */
+
+#ifndef _KML_CONTAINER_H_
+#define _KML_CONTAINER_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Feature.h"
+class DataSet;
+/*}}}*/
+
+class KML_Container: public KML_Feature {
+
+	public:
+
+		DataSet* feature;
+
+		/*KML_Container constructors, destructors {{{1*/
+		KML_Container();
+		~KML_Container();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_CONTAINER_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Document.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Document.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Document.cpp	(revision 11330)
@@ -0,0 +1,131 @@
+/*!\file KML_Document.cpp
+ * \brief: implementation of the kml_document object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Document::KML_Document(){{{1*/
+KML_Document::KML_Document(){
+
+	;
+
+}
+/*}}}*/
+/*FUNCTION KML_Document::~KML_Document(){{{1*/
+KML_Document::~KML_Document(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Document::Echo {{{1*/
+void  KML_Document::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_Document:\n");
+	KML_Container::Echo();
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Document::DeepEcho {{{1*/
+void  KML_Document::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Document::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Document::DeepEcho {{{1*/
+void  KML_Document::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_Document:\n",indent);
+	KML_Container::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Document::Write {{{1*/
+void  KML_Document::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<Document",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Container::Write(filout,indent);
+
+	fprintf(filout,"%s</Document>\n",indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Document::Read {{{1*/
+void  KML_Document::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Document",10)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_Document::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_Document::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Container::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Document.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Document.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Document.h	(revision 11330)
@@ -0,0 +1,43 @@
+/*! \file KML_Document.h 
+ *  \brief: header file for kml_document object
+ */
+
+#ifndef _KML_DOCUMENT_H_
+#define _KML_DOCUMENT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Container.h"
+class KML_Feature;
+/*}}}*/
+
+class KML_Document: public KML_Container {
+
+	public:
+
+		/*KML_Document constructors, destructors {{{1*/
+		KML_Document();
+		~KML_Document();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_DOCUMENT_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Feature.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Feature.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Feature.cpp	(revision 11330)
@@ -0,0 +1,197 @@
+/*!\file KML_Feature.cpp
+ * \brief: implementation of the kml_feature abstract object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Feature::KML_Feature(){{{1*/
+KML_Feature::KML_Feature(){
+
+	memcpy(name,"",(strlen("")+1)*sizeof(char));
+
+	visibility=true;
+	open      =false;
+	memcpy(snippet,"",(strlen("")+1)*sizeof(char));
+	memcpy(descript,"",(strlen("")+1)*sizeof(char));
+	memcpy(styleurl,"",(strlen("")+1)*sizeof(char));
+	style     =new DataSet;
+
+}
+/*}}}*/
+/*FUNCTION KML_Feature::~KML_Feature(){{{1*/
+KML_Feature::~KML_Feature(){
+
+	if (style) {
+		delete style;
+		style     =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Feature::Echo {{{1*/
+void  KML_Feature::Echo(){
+
+	bool  flag=true;
+
+	KML_Object::Echo();
+
+	_printf_(flag,"          name: \"%s\"\n"    ,name);
+	_printf_(flag,"    visibility: %s\n"        ,(visibility ? "true" : "false"));
+	_printf_(flag,"          open: %s\n"        ,(open ? "true" : "false"));
+	_printf_(flag,"       snippet: \"%s\"\n"    ,snippet);
+	_printf_(flag,"      descript: \"%s\"\n"    ,descript);
+	_printf_(flag,"      styleurl: \"%s\"\n"    ,styleurl);
+	_printf_(flag,"         style: (size=%d)\n" ,style->Size());
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Feature::DeepEcho {{{1*/
+void  KML_Feature::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Feature::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Feature::DeepEcho {{{1*/
+void  KML_Feature::DeepEcho(const char* indent){
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	KML_Object::DeepEcho(indent);
+
+	_printf_(flag,"%s          name: \"%s\"\n"      ,indent,name);
+	_printf_(flag,"%s    visibility: %s\n"          ,indent,(visibility ? "true" : "false"));
+	_printf_(flag,"%s          open: %s\n"          ,indent,(open ? "true" : "false"));
+	_printf_(flag,"%s       snippet: \"%s\"\n"      ,indent,snippet);
+	_printf_(flag,"%s      descript: \"%s\"\n"      ,indent,descript);
+	_printf_(flag,"%s      styleurl: \"%s\"\n"      ,indent,styleurl);
+
+/*  loop over any styles for the feature  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	if (style->Size())
+		for (i=0; i<style->Size(); i++) {
+			_printf_(flag,"%s         style: -------- begin [%d] --------\n" ,indent,i);
+			((KML_Style *)style->GetObjectByOffset(i))->DeepEcho(indent2);
+			_printf_(flag,"%s         style: --------  end  [%d] --------\n" ,indent,i);
+		}
+	else
+		_printf_(flag,"%s         style: [empty]\n"    ,indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Feature::Write {{{1*/
+void  KML_Feature::Write(FILE* filout,const char* indent){
+
+	int   i;
+	char  indent2[81];
+
+	KML_Object::Write(filout,indent);
+
+	if (name     && strlen(name))
+		fprintf(filout,"%s  <name>%s</name>\n",indent,name);
+	fprintf(filout,"%s  <visibility>%d</visibility>\n",indent,(visibility ? 1 : 0));
+	fprintf(filout,"%s  <open>%d</open>\n",indent,(open ? 1 : 0));
+	if (snippet  && strlen(snippet))
+		fprintf(filout,"%s  <Snippet maxLines=\"2\">%s</Snippet>\n",indent,snippet);
+	if (descript && strlen(descript))
+		fprintf(filout,"%s  <description>%s</description>\n",indent,descript);
+	if (styleurl && strlen(styleurl))
+		fprintf(filout,"%s  <styleUrl>%s</styleUrl>\n",indent,styleurl);
+
+/*  loop over any styles for the feature  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+    for (i=0; i<style->Size(); i++)
+        ((KML_Style *)style->GetObjectByOffset(i))->Write(filout,indent2);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Feature::Read {{{1*/
+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 %s.\n",kstr);
+	else if (strncmp(kstr,"<",1))
+		_error_("KML_Feature::Read -- Unexpected field \"%s\".\n",kstr);
+
+	else if (!strncmp(kstr,"<Style", 6)) {
+		kobj=(KML_Object*)new KML_Style();
+		kobj->Read(fid,kstr);
+		style     ->AddObject((Object*)kobj);
+	}
+
+	else if (!strcmp(kstr,"<name>"))
+		KMLFileTokenParse( name      ,NULL,KML_FEATURE_NAME_LENGTH,
+						  kstr,
+						  fid);
+	else if (!strcmp(kstr,"<visibility>"))
+		KMLFileTokenParse(&visibility,
+						  kstr,
+						  fid);
+	else if (!strcmp(kstr,"<open>"))
+		KMLFileTokenParse(&open      ,
+						  kstr,
+						  fid);
+	else if (!strncmp(kstr,"<snippet", 8))
+		KMLFileTokenParse( snippet   ,NULL,KML_FEATURE_SNIPPET_LENGTH,
+						  kstr,
+						  fid);
+	else if (!strcmp(kstr,"<description>"))
+		KMLFileTokenParse( descript  ,NULL,KML_FEATURE_DESCRIPT_LENGTH,
+						  kstr,
+						  fid);
+	else if (!strcmp(kstr,"<styleUrl>"))
+		KMLFileTokenParse( styleurl  ,NULL,KML_FEATURE_STYLEURL_LENGTH,
+						  kstr,
+						  fid);
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Feature.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Feature.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Feature.h	(revision 11330)
@@ -0,0 +1,57 @@
+/*! \file KML_Feature.h 
+ *  \brief: header file for kml_feature abstract object
+ */
+
+#ifndef _KML_FEATURE_H_
+#define _KML_FEATURE_H_
+
+#define KML_FEATURE_NAME_LENGTH         80
+#define KML_FEATURE_SNIPPET_LENGTH     160
+#define KML_FEATURE_DESCRIPT_LENGTH   3200
+#define KML_FEATURE_STYLEURL_LENGTH     80
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Object.h"
+class KML_Style;
+class DataSet;
+/*}}}*/
+
+class KML_Feature: public KML_Object {
+
+	public:
+
+		char  name[KML_FEATURE_NAME_LENGTH+1];
+		bool  visibility;
+		bool  open;
+		char  snippet[KML_FEATURE_SNIPPET_LENGTH+1];
+		char  descript[KML_FEATURE_DESCRIPT_LENGTH+1];
+		char  styleurl[KML_FEATURE_STYLEURL_LENGTH+1];
+		DataSet* style;
+
+		/*KML_Feature constructors, destructors {{{1*/
+		KML_Feature();
+		~KML_Feature();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FEATURE_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_File.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_File.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_File.cpp	(revision 11330)
@@ -0,0 +1,276 @@
+/*!\file KML_File.cpp
+ * \brief: implementation of the kml_file object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_File::KML_File(){{{1*/
+KML_File::KML_File(){
+
+	kmlobj    =new DataSet;
+
+}
+/*}}}*/
+/*FUNCTION KML_File::~KML_File(){{{1*/
+KML_File::~KML_File(){
+
+	if (kmlobj) {
+		delete kmlobj;
+		kmlobj    =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_File::Echo {{{1*/
+void  KML_File::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_File:\n");
+	KML_Object::Echo();
+
+	_printf_(flag,"        kmlobj: (size=%d)\n" ,kmlobj->Size());
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_File::DeepEcho {{{1*/
+void  KML_File::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_File::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_File::DeepEcho {{{1*/
+void  KML_File::DeepEcho(const char* indent){
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_File:\n",indent);
+	KML_Object::DeepEcho(indent);
+
+/*  loop over the kml objects for the file  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	if (kmlobj->Size())
+		for (i=0; i<kmlobj->Size(); i++) {
+			_printf_(flag,"%s        kmlobj: -------- begin [%d] --------\n" ,indent,i);
+			((KML_Object *)kmlobj->GetObjectByOffset(i))->DeepEcho(indent2);
+			_printf_(flag,"%s        kmlobj: --------  end  [%d] --------\n" ,indent,i);
+		}
+	else
+		_printf_(flag,"%s        kmlobj: [empty]\n"    ,indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_File::Write {{{1*/
+void  KML_File::Write(FILE* filout,const char* indent){
+
+	int   i;
+	char  indent2[81];
+
+	fprintf(filout,"%s<kml",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Object::Write(filout,indent);
+
+/*  loop over the kml objects for the file  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	for (i=0; i<kmlobj->Size(); i++)
+		((KML_Object *)kmlobj->GetObjectByOffset(i))->Write(filout,indent2);
+
+	fprintf(filout,"%s</kml>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_File::Read {{{1*/
+void  KML_File::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+	KML_Object*  kobj;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</kml", 5)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_File::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_File::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strncmp(kstri,"<Placemark",10)) {
+			kobj=(KML_Object*)new KML_Placemark();
+			kobj->Read(fid,kstri);
+			kmlobj    ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<Folder", 7)) {
+			kobj=(KML_Object*)new KML_Folder();
+			kobj->Read(fid,kstri);
+			kmlobj    ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<Document", 9)) {
+			kobj=(KML_Object*)new KML_Document();
+			kobj->Read(fid,kstri);
+			kmlobj    ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<GroundOverlay",14)) {
+			kobj=(KML_Object*)new KML_GroundOverlay();
+			kobj->Read(fid,kstri);
+			kmlobj    ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LatLonBox",10)) {
+			kobj=(KML_Object*)new KML_LatLonBox();
+			kobj->Read(fid,kstri);
+			kmlobj    ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<Icon", 5)) {
+			kobj=(KML_Object*)new KML_Icon();
+			kobj->Read(fid,kstri);
+			kmlobj    ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<Point", 6)) {
+			kobj=(KML_Object*)new KML_Point();
+			kobj->Read(fid,kstri);
+			kmlobj    ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LineString",11)) {
+			kobj=(KML_Object*)new KML_LineString();
+			kobj->Read(fid,kstri);
+			kmlobj    ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LinearRing",11)) {
+			kobj=(KML_Object*)new KML_LinearRing();
+			kobj->Read(fid,kstri);
+			kmlobj    ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<Polygon", 8)) {
+			kobj=(KML_Object*)new KML_Polygon();
+			kobj->Read(fid,kstri);
+			kmlobj    ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<MultiGeometry",14)) {
+			kobj=(KML_Object*)new KML_MultiGeometry();
+			kobj->Read(fid,kstri);
+			kmlobj    ->AddObject((Object*)kobj);
+		}
+
+//		else if (!strncmp(kstri,"<IconStyle",10)) {
+//			kobj=(KML_Object*)new KML_IconStyle();
+//			kobj->Read(fid,kstri);
+//			kmlobj    ->AddObject((Object*)kobj);
+//		}
+
+//		else if (!strncmp(kstri,"<LabelStyle",11)) {
+//			kobj=(KML_Object*)new KML_LabelStyle();
+//			kobj->Read(fid,kstri);
+//			kmlobj    ->AddObject((Object*)kobj);
+//		}
+
+		else if (!strncmp(kstri,"<LineStyle",10)) {
+			kobj=(KML_Object*)new KML_LineStyle();
+			kobj->Read(fid,kstri);
+			kmlobj    ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<PolyStyle",10)) {
+			kobj=(KML_Object*)new KML_PolyStyle();
+			kobj->Read(fid,kstri);
+			kmlobj    ->AddObject((Object*)kobj);
+		}
+
+//		else if (!strncmp(kstri,"<BalloonStyle",13)) {
+//			kobj=(KML_Object*)new KML_BalloonStyle();
+//			kobj->Read(fid,kstri);
+//			kmlobj    ->AddObject((Object*)kobj);
+//		}
+
+//		else if (!strncmp(kstri,"<ListStyle",10)) {
+//			kobj=(KML_Object*)new KML_ListStyle();
+//			kobj->Read(fid,kstri);
+//			kmlobj    ->AddObject((Object*)kobj);
+//		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_File::WriteExp {{{1*/
+void  KML_File::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+
+/*  loop over the kml objects for the file  */
+
+	for (i=0; i<kmlobj->Size(); i++)
+		((KML_Object *)kmlobj->GetObjectByOffset(i))->WriteExp(fid,nstr,sgn,cm,sp);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_File.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_File.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_File.h	(revision 11330)
@@ -0,0 +1,46 @@
+/*! \file KML_File.h 
+ *  \brief: header file for kml_file object
+ */
+
+#ifndef _KML_FILE_H_
+#define _KML_FILE_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Feature.h"
+class DataSet;
+/*}}}*/
+
+class KML_File: public KML_Object {
+
+	public:
+
+		DataSet* kmlobj;
+
+		/*KML_File constructors, destructors {{{1*/
+		KML_File();
+		~KML_File();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FILE_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Folder.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Folder.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Folder.cpp	(revision 11330)
@@ -0,0 +1,131 @@
+/*!\file KML_Folder.cpp
+ * \brief: implementation of the kml_folder object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Folder::KML_Folder(){{{1*/
+KML_Folder::KML_Folder(){
+
+	;
+
+}
+/*}}}*/
+/*FUNCTION KML_Folder::~KML_Folder(){{{1*/
+KML_Folder::~KML_Folder(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Folder::Echo {{{1*/
+void  KML_Folder::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_Folder:\n");
+	KML_Container::Echo();
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Folder::DeepEcho {{{1*/
+void  KML_Folder::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Folder::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Folder::DeepEcho {{{1*/
+void  KML_Folder::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_Folder:\n",indent);
+	KML_Container::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Folder::Write {{{1*/
+void  KML_Folder::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<Folder",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Container::Write(filout,indent);
+
+	fprintf(filout,"%s</Folder>\n",indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Folder::Read {{{1*/
+void  KML_Folder::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Folder", 8)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_Folder::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_Folder::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Container::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Folder.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Folder.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Folder.h	(revision 11330)
@@ -0,0 +1,43 @@
+/*! \file KML_Folder.h 
+ *  \brief: header file for kml_folder object
+ */
+
+#ifndef _KML_FOLDER_H_
+#define _KML_FOLDER_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Container.h"
+class KML_Feature;
+/*}}}*/
+
+class KML_Folder: public KML_Container {
+
+	public:
+
+		/*KML_Folder constructors, destructors {{{1*/
+		KML_Folder();
+		~KML_Folder();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FOLDER_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Geometry.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Geometry.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Geometry.cpp	(revision 11330)
@@ -0,0 +1,94 @@
+/*!\file KML_Geometry.cpp
+ * \brief: implementation of the kml_geometry abstract object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Geometry::KML_Geometry(){{{1*/
+KML_Geometry::KML_Geometry(){
+
+	;
+
+}
+/*}}}*/
+/*FUNCTION KML_Geometry::~KML_Geometry(){{{1*/
+KML_Geometry::~KML_Geometry(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Geometry::Echo {{{1*/
+void  KML_Geometry::Echo(){
+
+	this->KML_Object::Echo();
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Geometry::DeepEcho {{{1*/
+void  KML_Geometry::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Geometry::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Geometry::DeepEcho {{{1*/
+void  KML_Geometry::DeepEcho(const char* indent){
+
+	this->KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Geometry::Write {{{1*/
+void  KML_Geometry::Write(FILE* filout,const char* indent){
+
+	KML_Object::Write(filout,indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Geometry::Read {{{1*/
+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 %s.\n",kstr);
+	else if (strncmp(kstr,"<",1))
+		_error_("KML_Geometry::Read -- Unexpected field \"%s\".\n",kstr);
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Geometry.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Geometry.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Geometry.h	(revision 11330)
@@ -0,0 +1,42 @@
+/*! \file KML_Geometry.h 
+ *  \brief: header file for kml_geometry abstract object
+ */
+
+#ifndef _KML_GEOMETRY_H_
+#define _KML_GEOMETRY_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_Geometry: public KML_Object {
+
+	public:
+
+		/*KML_Geometry constructors, destructors {{{1*/
+		KML_Geometry();
+		~KML_Geometry();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_GEOMETRY_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_GroundOverlay.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_GroundOverlay.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_GroundOverlay.cpp	(revision 11330)
@@ -0,0 +1,177 @@
+/*!\file KML_GroundOverlay.cpp
+ * \brief: implementation of the kml_groundoverlay object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_GroundOverlay::KML_GroundOverlay(){{{1*/
+KML_GroundOverlay::KML_GroundOverlay(){
+
+	altitude  = 0.;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	llbox     =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_GroundOverlay::~KML_GroundOverlay(){{{1*/
+KML_GroundOverlay::~KML_GroundOverlay(){
+
+	if (llbox) {
+		delete llbox;
+		llbox     =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_GroundOverlay::Echo {{{1*/
+void  KML_GroundOverlay::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_GroundOverlay:\n");
+	KML_Overlay::Echo();
+
+	_printf_(flag,"      altitude: %0.16g\n"      ,altitude);
+	_printf_(flag,"       altmode: \"%s\"\n"      ,altmode);
+	_printf_(flag,"         llbox: %p\n"          ,llbox);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_GroundOverlay::DeepEcho {{{1*/
+void  KML_GroundOverlay::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_GroundOverlay::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_GroundOverlay::DeepEcho {{{1*/
+void  KML_GroundOverlay::DeepEcho(const char* indent){
+
+	char  indent2[81];
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_GroundOverlay:\n",indent);
+	KML_Overlay::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	_printf_(flag,"%s      altitude: %0.16g\n"      ,indent,altitude);
+	_printf_(flag,"%s       altmode: \"%s\"\n"      ,indent,altmode);
+	if (llbox)
+		llbox->DeepEcho(indent2);
+	else
+		_printf_(flag,"%s         llbox: %p\n"          ,indent,llbox);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_GroundOverlay::Write {{{1*/
+void  KML_GroundOverlay::Write(FILE* filout,const char* indent){
+
+	char  indent2[81];
+
+	fprintf(filout,"%s<GroundOverlay",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Overlay::Write(filout,indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	fprintf(filout,"%s  <altitude>%0.16g</altitude>\n",indent,altitude);
+	fprintf(filout,"%s  <altitudeMode>%s</altitudeMode>\n",indent,altmode);
+	if (llbox)
+		llbox->Write(filout,indent2);
+
+	fprintf(filout,"%s</GroundOverlay>\n",indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_GroundOverlay::Read {{{1*/
+void  KML_GroundOverlay::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</GroundOverlay",15)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_GroundOverlay::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_GroundOverlay::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strcmp(kstri,"<altitude>"))
+			KMLFileTokenParse(&altitude  ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_GROUNDOVERLAY_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strncmp(kstri,"<LatLonBox",10)) {
+			llbox     =new KML_LatLonBox();
+			llbox     ->Read(fid,kstri);
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Overlay::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_GroundOverlay.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_GroundOverlay.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_GroundOverlay.h	(revision 11330)
@@ -0,0 +1,49 @@
+/*! \file KML_GroundOverlay.h 
+ *  \brief: header file for kml_groundoverlay object
+ */
+
+#ifndef _KML_GROUNDOVERLAY_H_
+#define _KML_GROUNDOVERLAY_H_
+
+#define KML_GROUNDOVERLAY_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Overlay.h"
+class KML_LatLonBox;
+/*}}}*/
+
+class KML_GroundOverlay: public KML_Overlay {
+
+	public:
+
+		double altitude;
+		char  altmode[KML_GROUNDOVERLAY_ALTMODE_LENGTH+1];
+		KML_LatLonBox* llbox;
+
+		/*KML_GroundOverlay constructors, destructors {{{1*/
+		KML_GroundOverlay();
+		~KML_GroundOverlay();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_GROUNDOVERLAY_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Icon.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Icon.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Icon.cpp	(revision 11330)
@@ -0,0 +1,203 @@
+/*!\file KML_Icon.cpp
+ * \brief: implementation of the kml_feature abstract object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Icon::KML_Icon(){{{1*/
+KML_Icon::KML_Icon(){
+
+	strcpy(href      ,"");
+	strcpy(refmode   ,"onChange");
+	refint    = 4.;
+	strcpy(vrefmode  ,"never");
+	vreftime  = 4.;
+	vboundsc  = 1.;
+	strcpy(vformat   ,"");
+	strcpy(hquery    ,"");
+
+}
+/*}}}*/
+/*FUNCTION KML_Icon::~KML_Icon(){{{1*/
+KML_Icon::~KML_Icon(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Icon::Echo {{{1*/
+void  KML_Icon::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_Icon:\n");
+	KML_Object::Echo();
+
+	_printf_(flag,"          href: \"%s\"\n"    ,href);
+	_printf_(flag,"       refmode: \"%s\"\n"    ,refmode);
+	_printf_(flag,"        refint: %g\n"        ,refint);
+	_printf_(flag,"      vrefmode: \"%s\"\n"    ,vrefmode);
+	_printf_(flag,"      vreftime: %g\n"        ,vreftime);
+	_printf_(flag,"      vboundsc: %g\n"        ,vboundsc);
+	_printf_(flag,"       vformat: \"%s\"\n"    ,vformat);
+	_printf_(flag,"        hquery: \"%s\"\n"    ,hquery);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Icon::DeepEcho {{{1*/
+void  KML_Icon::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Icon::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Icon::DeepEcho {{{1*/
+void  KML_Icon::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_Icon:\n",indent);
+	KML_Object::DeepEcho(indent);
+
+	_printf_(flag,"%s          href: \"%s\"\n"    ,indent,href);
+	_printf_(flag,"%s       refmode: \"%s\"\n"    ,indent,refmode);
+	_printf_(flag,"%s        refint: %g\n"        ,indent,refint);
+	_printf_(flag,"%s      vrefmode: \"%s\"\n"    ,indent,vrefmode);
+	_printf_(flag,"%s      vreftime: %g\n"        ,indent,vreftime);
+	_printf_(flag,"%s      vboundsc: %g\n"        ,indent,vboundsc);
+	_printf_(flag,"%s       vformat: \"%s\"\n"    ,indent,vformat);
+	_printf_(flag,"%s        hquery: \"%s\"\n"    ,indent,hquery);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Icon::Write {{{1*/
+void  KML_Icon::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<Icon",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Object::Write(filout,indent);
+
+	if (href     && strlen(href))
+		fprintf(filout,"%s  <href>%s</href>\n",indent,href);
+	if (refmode  && strlen(refmode))
+		fprintf(filout,"%s  <refreshMode>%s</refreshMode>\n",indent,refmode);
+	fprintf(filout,"%s  <refreshInterval>%g</refreshInterval>\n",indent,refint);
+	if (vrefmode && strlen(vrefmode))
+		fprintf(filout,"%s  <viewRefreshMode>%s</viewRefreshMode>\n",indent,vrefmode);
+	fprintf(filout,"%s  <viewRefreshTime>%g</viewRefreshTime>\n",indent,vreftime);
+	fprintf(filout,"%s  <viewBoundScale>%g</viewBoundScale>\n",indent,vboundsc);
+	if (vformat  && strlen(vformat))
+		fprintf(filout,"%s  <viewFormat>%s</viewFormat>\n",indent,vformat);
+	if (hquery   && strlen(hquery))
+		fprintf(filout,"%s  <httpQuery>%s</httpQuery>\n",indent,hquery);
+
+	fprintf(filout,"%s</Icon>\n",indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Icon::Read {{{1*/
+void  KML_Icon::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Icon", 6)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_Icon::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_Icon::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strcmp(kstri,"<href>"))
+			KMLFileTokenParse( href      ,NULL,KML_ICON_HREF_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<refreshMode>"))
+			KMLFileTokenParse( refmode   ,NULL,KML_ICON_REFMODE_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<refreshInterval>"))
+			KMLFileTokenParse(&refint    ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<viewRefreshMode>"))
+			KMLFileTokenParse( vrefmode  ,NULL,KML_ICON_VREFMODE_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<viewRefreshTime>"))
+			KMLFileTokenParse(&vreftime  ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<viewBoundScale>"))
+			KMLFileTokenParse(&vboundsc  ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<viewFormat>"))
+			KMLFileTokenParse( vformat   ,NULL,KML_ICON_VFORMAT_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<httpQuery>"))
+			KMLFileTokenParse( hquery    ,NULL,KML_ICON_HQUERY_LENGTH,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Icon.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Icon.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Icon.h	(revision 11330)
@@ -0,0 +1,57 @@
+/*! \file KML_Icon.h 
+ *  \brief: header file for kml_icon object
+ */
+
+#ifndef _KML_ICON_H_
+#define _KML_ICON_H_
+
+#define KML_ICON_HREF_LENGTH      800
+#define KML_ICON_REFMODE_LENGTH    10
+#define KML_ICON_VREFMODE_LENGTH    9
+#define KML_ICON_VFORMAT_LENGTH   800
+#define KML_ICON_HQUERY_LENGTH    800
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_Icon: public KML_Object {
+
+	public:
+
+		char  href[KML_ICON_HREF_LENGTH+1];
+		char  refmode[KML_ICON_REFMODE_LENGTH+1];
+		float refint;
+		char  vrefmode[KML_ICON_VREFMODE_LENGTH+1];
+		float vreftime;
+		float vboundsc;
+		char  vformat[KML_ICON_VFORMAT_LENGTH+1];
+		char  hquery[KML_ICON_HQUERY_LENGTH+1];
+
+		/*KML_Icon constructors, destructors {{{1*/
+		KML_Icon();
+		~KML_Icon();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_ICON_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_LatLonBox.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_LatLonBox.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_LatLonBox.cpp	(revision 11330)
@@ -0,0 +1,174 @@
+/*!\file KML_LatLonBox.cpp
+ * \brief: implementation of the kml_feature abstract object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_LatLonBox::KML_LatLonBox(){{{1*/
+KML_LatLonBox::KML_LatLonBox(){
+
+	north     = 0.;
+	south     = 0.;
+	east      = 0.;
+	west      = 0.;
+	rotation  = 0.;
+
+}
+/*}}}*/
+/*FUNCTION KML_LatLonBox::~KML_LatLonBox(){{{1*/
+KML_LatLonBox::~KML_LatLonBox(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_LatLonBox::Echo {{{1*/
+void  KML_LatLonBox::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_LatLonBox:\n");
+	KML_Object::Echo();
+
+	_printf_(flag,"         north: %0.16g\n"    ,north);
+	_printf_(flag,"         south: %0.16g\n"    ,south);
+	_printf_(flag,"          east: %0.16g\n"    ,east);
+	_printf_(flag,"          west: %0.16g\n"    ,west);
+	_printf_(flag,"      rotation: %0.16g\n"    ,rotation);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_LatLonBox::DeepEcho {{{1*/
+void  KML_LatLonBox::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_LatLonBox::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_LatLonBox::DeepEcho {{{1*/
+void  KML_LatLonBox::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_LatLonBox:\n",indent);
+	KML_Object::DeepEcho(indent);
+
+	_printf_(flag,"%s         north: %0.16g\n"    ,indent,north);
+	_printf_(flag,"%s         south: %0.16g\n"    ,indent,south);
+	_printf_(flag,"%s          east: %0.16g\n"    ,indent,east);
+	_printf_(flag,"%s          west: %0.16g\n"    ,indent,west);
+	_printf_(flag,"%s      rotation: %0.16g\n"    ,indent,rotation);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_LatLonBox::Write {{{1*/
+void  KML_LatLonBox::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<LatLonBox",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Object::Write(filout,indent);
+
+	fprintf(filout,"%s  <north>%0.16g</north>\n",indent,north);
+	fprintf(filout,"%s  <south>%0.16g</south>\n",indent,south);
+	fprintf(filout,"%s  <east>%0.16g</east>\n",indent,east);
+	fprintf(filout,"%s  <west>%0.16g</west>\n",indent,west);
+	fprintf(filout,"%s  <rotation>%0.16g</rotation>\n",indent,rotation);
+
+	fprintf(filout,"%s</LatLonBox>\n",indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_LatLonBox::Read {{{1*/
+void  KML_LatLonBox::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</LatLonBox",11)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_LatLonBox::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_LatLonBox::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strcmp(kstri,"<north>"))
+			KMLFileTokenParse(&north     ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<south>"))
+			KMLFileTokenParse(&south     ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<east>"))
+			KMLFileTokenParse(&east      ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<west>"))
+			KMLFileTokenParse(&west      ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<rotation>"))
+			KMLFileTokenParse(&rotation  ,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_LatLonBox.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_LatLonBox.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_LatLonBox.h	(revision 11330)
@@ -0,0 +1,48 @@
+/*! \file KML_LatLonBox.h 
+ *  \brief: header file for kml_latlonbox object
+ */
+
+#ifndef _KML_LATLONBOX_H_
+#define _KML_LATLONBOX_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_LatLonBox: public KML_Object {
+
+	public:
+
+		double north;
+		double south;
+		double east;
+		double west;
+		double rotation;
+
+		/*KML_LatLonBox constructors, destructors {{{1*/
+		KML_LatLonBox();
+		~KML_LatLonBox();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LATLONBOX_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_LineString.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_LineString.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_LineString.cpp	(revision 11330)
@@ -0,0 +1,232 @@
+/*!\file KML_LineString.cpp
+ * \brief: implementation of the kml_linestring object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+#include "../../modules/Ll2xyx/Ll2xyx.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_LineString::KML_LineString(){{{1*/
+KML_LineString::KML_LineString(){
+
+	extrude   =false;
+	tessellate=false;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	ncoord    =0;
+	coords    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_LineString::~KML_LineString(){{{1*/
+KML_LineString::~KML_LineString(){
+
+	if (coords) xfree((void**)&coords);
+
+	coords    =NULL;
+	ncoord    =0;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_LineString::Echo {{{1*/
+void  KML_LineString::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_LineString:\n");
+	KML_Geometry::Echo();
+
+	_printf_(flag,"       extrude: %s\n"          ,(extrude ? "true" : "false"));
+	_printf_(flag,"    tessellate: %s\n"          ,(tessellate ? "true" : "false"));
+	_printf_(flag,"       altmode: \"%s\"\n"      ,altmode);
+	_printf_(flag,"        coords: (ncoord=%d)\n" ,ncoord);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineString::DeepEcho {{{1*/
+void  KML_LineString::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_LineString::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineString::DeepEcho {{{1*/
+void  KML_LineString::DeepEcho(const char* indent){
+
+	int   i;
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_LineString:\n",indent);
+	KML_Geometry::DeepEcho(indent);
+
+	_printf_(flag,"%s       extrude: %s\n"          ,indent,(extrude ? "true" : "false"));
+	_printf_(flag,"%s    tessellate: %s\n"          ,indent,(tessellate ? "true" : "false"));
+	_printf_(flag,"%s       altmode: \"%s\"\n"      ,indent,altmode);
+	_printf_(flag,"%s        coords: (ncoord=%d)\n" ,indent,ncoord);
+	for (i=0; i<ncoord; i++)
+		_printf_(flag,"%s                (%g,%g,%g)\n" ,indent,
+				coords[i][0],coords[i][1],coords[i][2]);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineString::Write {{{1*/
+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[i][0],coords[i][1],coords[i][2]);
+
+	fprintf(filout,"%s  </coordinates>\n",indent);
+	fprintf(filout,"%s</LineString>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineString::Read {{{1*/
+void  KML_LineString::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</LineString",12)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_LineString::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_LineString::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude   ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<tessellate>"))
+			KMLFileTokenParse(&tessellate,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_LINESTRING_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<coordinates>"))
+			KMLFileTokenParse(&coords    ,&ncoord    ,0,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineString::WriteExp {{{1*/
+void  KML_LineString::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int     i;
+	double  *lat,*lon,*x,*y;
+	char    nstr2[81];
+
+/*  extract latitude and longitude into vectors  */
+
+	lat=(double *) xmalloc(ncoord*sizeof(double));
+	lon=(double *) xmalloc(ncoord*sizeof(double));
+	for (i=0; i<ncoord; i++) {
+		lon[i]=coords[i][0];
+		lat[i]=coords[i][1];
+	}
+
+/*  convert latitude and longitude to x and y  */
+
+	x  =(double *) xmalloc(ncoord*sizeof(double));
+	y  =(double *) xmalloc(ncoord*sizeof(double));
+	Ll2xyx(x,y,lat,lon,ncoord,sgn,cm,sp);
+
+/*  write header  */
+
+	memcpy(nstr2,nstr,(strlen(nstr)+1)*sizeof(char));
+
+	for (i=0; i<strlen(nstr2); i++)
+		if ((nstr2[i] == ' ') || (nstr2[i] == '\t'))
+			nstr2[i]='_';
+	fprintf(fid,"## Name:%s\n",nstr2);
+	fprintf(fid,"## Icon:0\n");
+	fprintf(fid,"# Points Count	Value\n");
+    fprintf(fid,"%u	%s\n",ncoord  ,"1.");
+	fprintf(fid,"# X pos	Y pos\n");
+
+/*  write vertices  */
+
+	for (i=0; i<ncoord; i++)
+	    fprintf(fid,"%lf\t%lf\n",x[i],y[i]);
+
+/*  write blank line  */
+
+	fprintf(fid,"\n");
+
+	xfree((void**)&y);
+	xfree((void**)&x);
+	xfree((void**)&lon);
+	xfree((void**)&lat);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_LineString.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_LineString.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_LineString.h	(revision 11330)
@@ -0,0 +1,51 @@
+/*! \file KML_LineString.h 
+ *  \brief: header file for kml_linestring object
+ */
+
+#ifndef _KML_LINESTRING_H_
+#define _KML_LINESTRING_H_
+
+#define KML_LINESTRING_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Geometry.h"
+/*}}}*/
+
+class KML_LineString: public KML_Geometry {
+
+	public:
+
+		bool  extrude;
+		bool  tessellate;
+		char  altmode[KML_LINESTRING_ALTMODE_LENGTH+1];
+        int   ncoord;
+		double (*coords)[3];
+
+		/*KML_LineString constructors, destructors {{{1*/
+		KML_LineString();
+		~KML_LineString();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINESTRING_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_LineStyle.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_LineStyle.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_LineStyle.cpp	(revision 11330)
@@ -0,0 +1,143 @@
+/*!\file KML_LineStyle.cpp
+ * \brief: implementation of the kml_linestyle object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_LineStyle::KML_LineStyle(){{{1*/
+KML_LineStyle::KML_LineStyle(){
+
+	width     =1.;
+
+}
+/*}}}*/
+/*FUNCTION KML_LineStyle::~KML_LineStyle(){{{1*/
+KML_LineStyle::~KML_LineStyle(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_LineStyle::Echo {{{1*/
+void  KML_LineStyle::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_LineStyle:\n");
+	KML_ColorStyle::Echo();
+
+	_printf_(flag,"         width: %g\n"          ,width);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_LineStyle::DeepEcho {{{1*/
+void  KML_LineStyle::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_LineStyle::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_LineStyle::DeepEcho {{{1*/
+void  KML_LineStyle::DeepEcho(const char* indent){
+
+	int   i;
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_LineStyle:\n",indent);
+	KML_ColorStyle::DeepEcho(indent);
+
+	_printf_(flag,"%s         width: %g\n"          ,indent,width);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_LineStyle::Write {{{1*/
+void  KML_LineStyle::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<LineStyle",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_ColorStyle::Write(filout,indent);
+
+	fprintf(filout,"%s  <width>%g</width>\n",indent,width);
+
+	fprintf(filout,"%s</LineStyle>\n",indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_LineStyle::Read {{{1*/
+void  KML_LineStyle::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</LineStyle",11)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_LineStyle::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_LineStyle::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strcmp(kstri,"<width>"))
+			KMLFileTokenParse(&width     ,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_ColorStyle::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_LineStyle.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_LineStyle.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_LineStyle.h	(revision 11330)
@@ -0,0 +1,44 @@
+/*! \file KML_LineStyle.h 
+ *  \brief: header file for kml_linestyle object
+ */
+
+#ifndef _KML_LINESTYLE_H_
+#define _KML_LINESTYLE_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_ColorStyle.h"
+/*}}}*/
+
+class KML_LineStyle: public KML_ColorStyle {
+
+	public:
+
+		float width;
+
+		/*KML_LineStyle constructors, destructors {{{1*/
+		KML_LineStyle();
+		~KML_LineStyle();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINESTYLE_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_LinearRing.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_LinearRing.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_LinearRing.cpp	(revision 11330)
@@ -0,0 +1,243 @@
+/*!\file KML_LinearRing.cpp
+ * \brief: implementation of the kml_linearring object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../modules/Ll2xyx/Ll2xyx.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_LinearRing::KML_LinearRing(){{{1*/
+KML_LinearRing::KML_LinearRing(){
+
+	extrude   =false;
+	tessellate=false;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	ncoord    =0;
+	coords    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_LinearRing::~KML_LinearRing(){{{1*/
+KML_LinearRing::~KML_LinearRing(){
+
+	if (coords) xfree((void**)&coords);
+
+	coords    =NULL;
+	ncoord    =0;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_LinearRing::Echo {{{1*/
+void  KML_LinearRing::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_LinearRing:\n");
+	KML_Geometry::Echo();
+
+	_printf_(flag,"       extrude: %s\n"          ,(extrude ? "true" : "false"));
+	_printf_(flag,"    tessellate: %s\n"          ,(tessellate ? "true" : "false"));
+	_printf_(flag,"       altmode: \"%s\"\n"      ,altmode);
+	_printf_(flag,"        coords: (ncoord=%d)\n" ,ncoord);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_LinearRing::DeepEcho {{{1*/
+void  KML_LinearRing::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_LinearRing::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_LinearRing::DeepEcho {{{1*/
+void  KML_LinearRing::DeepEcho(const char* indent){
+
+	int   i;
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_LinearRing:\n",indent);
+	KML_Geometry::DeepEcho(indent);
+
+	_printf_(flag,"%s       extrude: %s\n"          ,indent,(extrude ? "true" : "false"));
+	_printf_(flag,"%s    tessellate: %s\n"          ,indent,(tessellate ? "true" : "false"));
+	_printf_(flag,"%s       altmode: \"%s\"\n"      ,indent,altmode);
+	_printf_(flag,"%s        coords: (ncoord=%d)\n" ,indent,ncoord);
+	for (i=0; i<ncoord; i++)
+		_printf_(flag,"%s                (%g,%g,%g)\n" ,indent,
+				coords[i][0],coords[i][1],coords[i][2]);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_LinearRing::Write {{{1*/
+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[i][0],coords[i][1],coords[i][2]);
+
+	fprintf(filout,"%s  </coordinates>\n",indent);
+	fprintf(filout,"%s</LinearRing>\n",indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_LinearRing::Read {{{1*/
+void  KML_LinearRing::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,"</LinearRing",12)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_LinearRing::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_LinearRing::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude   ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<tessellate>"))
+			KMLFileTokenParse(&tessellate,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_LINEARRING_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<coordinates>"))
+			KMLFileTokenParse(&coords    ,&ncoord    ,0,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_LinearRing::WriteExp {{{1*/
+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=(double *) xmalloc(ncoord*sizeof(double));
+	lon=(double *) xmalloc(ncoord*sizeof(double));
+	for (i=0; i<ncoord; i++) {
+		lon[i]=coords[i][0];
+		lat[i]=coords[i][1];
+	}
+
+/*  convert latitude and longitude to x and y  */
+
+	x  =(double *) xmalloc(ncoord*sizeof(double));
+	y  =(double *) xmalloc(ncoord*sizeof(double));
+	Ll2xyx(x,y,lat,lon,ncoord,sgn,cm,sp);
+
+/*  write header  */
+
+	memcpy(nstr2,nstr,(strlen(nstr)+1)*sizeof(char));
+
+	for (i=0; i<strlen(nstr2); i++)
+		if ((nstr2[i] == ' ') || (nstr2[i] == '\t'))
+			nstr2[i]='_';
+	fprintf(fid,"## Name:%s\n",nstr2);
+	fprintf(fid,"## Icon:0\n");
+	fprintf(fid,"# Points Count	Value\n");
+	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");
+
+	xfree((void**)&y);
+	xfree((void**)&x);
+	xfree((void**)&lon);
+	xfree((void**)&lat);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_LinearRing.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_LinearRing.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_LinearRing.h	(revision 11330)
@@ -0,0 +1,51 @@
+/*! \file KML_LinearRing.h 
+ *  \brief: header file for kml_linearring object
+ */
+
+#ifndef _KML_LINEARRING_H_
+#define _KML_LINEARRING_H_
+
+#define KML_LINEARRING_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Geometry.h"
+/*}}}*/
+
+class KML_LinearRing: public KML_Geometry {
+
+	public:
+
+		bool  extrude;
+		bool  tessellate;
+		char  altmode[KML_LINEARRING_ALTMODE_LENGTH+1];
+        int   ncoord;
+		double (*coords)[3];
+
+		/*KML_LinearRing constructors, destructors {{{1*/
+		KML_LinearRing();
+		~KML_LinearRing();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINEARRING_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_MultiGeometry.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_MultiGeometry.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_MultiGeometry.cpp	(revision 11330)
@@ -0,0 +1,210 @@
+/*!\file KML_MultiGeometry.cpp
+ * \brief: implementation of the kml_multigeometry object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_MultiGeometry::KML_MultiGeometry(){{{1*/
+KML_MultiGeometry::KML_MultiGeometry(){
+
+	geometry  =new DataSet;
+
+}
+/*}}}*/
+/*FUNCTION KML_MultiGeometry::~KML_MultiGeometry(){{{1*/
+KML_MultiGeometry::~KML_MultiGeometry(){
+
+	if (geometry) {
+		delete geometry;
+		geometry  =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_MultiGeometry::Echo {{{1*/
+void  KML_MultiGeometry::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_Multigeometry:\n");
+	KML_Geometry::Echo();
+
+	_printf_(flag,"      geometry: (size=%d)\n" ,geometry->Size());
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_MultiGeometry::DeepEcho {{{1*/
+void  KML_MultiGeometry::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_MultiGeometry::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_MultiGeometry::DeepEcho {{{1*/
+void  KML_MultiGeometry::DeepEcho(const char* indent){
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_Multigeometry:\n",indent);
+	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++) {
+			_printf_(flag,"%s      geometry: -------- begin [%d] --------\n" ,indent,i);
+			((KML_Geometry *)geometry->GetObjectByOffset(i))->DeepEcho(indent2);
+			_printf_(flag,"%s      geometry: --------  end  [%d] --------\n" ,indent,i);
+		}
+	else
+		_printf_(flag,"%s      geometry: [empty]\n"    ,indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_MultiGeometry::Write {{{1*/
+void  KML_MultiGeometry::Write(FILE* filout,const char* indent){
+
+	int   i;
+	char  indent2[81];
+
+	fprintf(filout,"%s<MultiGeometry",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Geometry::Write(filout,indent);
+
+/*  loop over the geometry elements for the multigeometry  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	for (i=0; i<geometry->Size(); i++)
+		((KML_Geometry *)geometry->GetObjectByOffset(i))->Write(filout,indent2);
+
+	fprintf(filout,"%s</MultiGeometry>\n",indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_MultiGeometry::Read {{{1*/
+void  KML_MultiGeometry::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+	KML_Object*  kobj;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</MultiGeometry",15)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_MultiGeometry::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_MultiGeometry::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strncmp(kstri,"<Point", 6)) {
+			kobj=(KML_Object*)new KML_Point();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LineString",11)) {
+			kobj=(KML_Object*)new KML_LineString();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LinearRing",11)) {
+			kobj=(KML_Object*)new KML_LinearRing();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<Polygon", 8)) {
+			kobj=(KML_Object*)new KML_Polygon();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<MultiGeometry",14)) {
+			kobj=(KML_Object*)new KML_MultiGeometry();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_MultiGeometry::WriteExp {{{1*/
+void  KML_MultiGeometry::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+
+/*  loop over the geometry elements for the multigeometry  */
+
+	for (i=0; i<geometry->Size(); i++)
+		((KML_Object *)geometry->GetObjectByOffset(i))->WriteExp(fid,nstr,sgn,cm,sp);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_MultiGeometry.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_MultiGeometry.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_MultiGeometry.h	(revision 11330)
@@ -0,0 +1,47 @@
+/*! \file KML_MultiGeometry.h 
+ *  \brief: header file for kml_multigeometry object
+ */
+
+#ifndef _KML_MULTIGEOMETRY_H_
+#define _KML_MULTIGEOMETRY_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Geometry.h"
+class KML_Geometry;
+class DataSet;
+/*}}}*/
+
+class KML_MultiGeometry: public KML_Geometry {
+
+	public:
+
+		DataSet* geometry;
+
+		/*KML_MultiGeometry constructors, destructors {{{1*/
+		KML_MultiGeometry();
+		~KML_MultiGeometry();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_MULTIGEOMETRY_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Object.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Object.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Object.cpp	(revision 11330)
@@ -0,0 +1,248 @@
+/*!\file KML_Object.cpp
+ * \brief: implementation of the kml_object abstract object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Object::KML_Object(){{{1*/
+KML_Object::KML_Object(){
+
+	attrib    =new DataSet;
+	commnt    =new DataSet;
+
+}
+/*}}}*/
+/*FUNCTION KML_Object::~KML_Object(){{{1*/
+KML_Object::~KML_Object(){
+
+	if (attrib) {
+		delete attrib;
+		attrib    =NULL;
+	}
+	if (commnt) {
+		delete commnt;
+		commnt    =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Object::Echo {{{1*/
+void  KML_Object::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"        attrib: (size=%d)\n" ,attrib->Size());
+	_printf_(flag,"        commnt: (size=%d)\n" ,commnt->Size());
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::DeepEcho {{{1*/
+void  KML_Object::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::DeepEcho {{{1*/
+void  KML_Object::DeepEcho(const char* indent){
+
+	int   i;
+	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
+		_printf_(flag,"%s        attrib: [empty]\n"    ,indent);
+
+/*  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
+		_printf_(flag,"%s        commnt: [empty]\n"    ,indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::Write {{{1*/
+void  KML_Object::Write(FILE* filout,const char* indent){
+
+//  attributes always written in keyword line of derived classes
+//  comments always written after keyword line of derived classes
+
+	;
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::Read {{{1*/
+void  KML_Object::Read(FILE* fid,char* kstr){
+
+/*  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 %s.\n",kstr);
+	else if (strncmp(kstr,"<",1))
+		_error_("KML_Object::Read -- Unexpected field \"%s\".\n",kstr);
+
+	else if (!strncmp(kstr,"<",1)) {
+		_printf_(true,"KML_Object::Read -- Unrecognized opening tag %s.\n",kstr);
+		KMLFileTagSkip(kstr,
+					   fid);
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::WriteExp {{{1*/
+void  KML_Object::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	;
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::AddAttrib {{{1*/
+void  KML_Object::AddAttrib(const char* name,const char* value){
+
+	KML_Attribute* katt=NULL;
+
+	katt=new KML_Attribute();
+	katt->Alloc(name,value);
+	katt->Add(attrib);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::FindAttrib {{{1*/
+void  KML_Object::FindAttrib(char** pvalue,char* name,char* deflt){
+
+	int   i;
+	KML_Attribute* katt=NULL;
+
+/*  loop over any attributes for the object  */
+
+	if (attrib->Size())
+		for (i=0; i<attrib->Size(); i++)
+			if (!strcmp(((KML_Attribute *)attrib->GetObjectByOffset(i))->name,name)) {
+				katt=(KML_Attribute *)attrib->GetObjectByOffset(i);
+				break;
+			}
+
+/*  if found, get the value; otherwise use the default  */
+
+	if (katt)
+		katt->Get(pvalue,deflt);
+	else {
+		*pvalue=(char *) xmalloc((strlen(deflt)+1)*sizeof(char));
+		memcpy(*pvalue,deflt,(strlen(deflt)+1)*sizeof(char));
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::WriteAttrib {{{1*/
+void  KML_Object::WriteAttrib(FILE* filout,const char* indent){
+
+//  attributes always written in keyword line of kml_object
+
+/*  loop over any attributes for the object  */
+
+	if (attrib->Size())
+		for (int i=0; i<attrib->Size(); i++)
+			((KML_Attribute *)attrib->GetObjectByOffset(i))->Write(filout,indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::AddCommnt {{{1*/
+void  KML_Object::AddCommnt(int ncom,char** pcom){
+
+	int   i;
+	KML_Comment* kcom=NULL;
+
+	for (i=0; i<ncom; i++) {
+		kcom=new KML_Comment();
+		kcom->Alloc(pcom[i]);
+		kcom->Add(commnt);
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::AddCommnt {{{1*/
+void  KML_Object::AddCommnt(char* value){
+
+	KML_Comment* kcom=NULL;
+
+	kcom=new KML_Comment();
+	kcom->Alloc(value);
+	kcom->Add(commnt);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::FindCommnt {{{1*/
+void  KML_Object::FindCommnt(char** pvalue,int inum){
+
+	KML_Comment* kcom=NULL;
+
+/*  loop over any comments for the object  */
+
+	if (inum <= commnt->Size())
+		kcom=(KML_Comment *)commnt->GetObjectByOffset(inum-1);
+
+/*  if found, get the value; otherwise use the NULL  */
+
+	if (kcom)
+		kcom->Get(pvalue);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::WriteCommnt {{{1*/
+void  KML_Object::WriteCommnt(FILE* filout,const char* indent){
+
+	int   i;
+
+//  comments always written after keyword line of kml_object
+
+/*  loop over any comments for the object  */
+
+	if (commnt->Size())
+		for (i=0; i<commnt->Size(); i++)
+			((KML_Comment *)commnt->GetObjectByOffset(i))->Write(filout,indent);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Object.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Object.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Object.h	(revision 11330)
@@ -0,0 +1,55 @@
+/*! \file KML_Object.h 
+ *  \brief: header file for kml_object abstract object
+ */
+
+#ifndef _KML_OBJECT_H_
+#define _KML_OBJECT_H_
+
+/*Headers:{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "../Object.h"
+class DataSet;
+/*}}}*/
+
+class KML_Object: public Object {
+
+	public:
+
+		DataSet* attrib;
+		DataSet* commnt;
+
+		/*KML_Object constructors, destructors {{{1*/
+		KML_Object();
+		~KML_Object();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		virtual void  Echo();
+		virtual void  DeepEcho();
+		virtual void  DeepEcho(const char* indent);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+		/*virtual functions: */
+		virtual void  Write(FILE* fid,const char* indent)=0;
+		virtual void  Read(FILE* fid,char* kstr)=0;
+		virtual void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		virtual void  AddAttrib(const char* name,const char* value);
+		virtual void  FindAttrib(char** pvalue,char* name,char* deflt);
+		virtual void  WriteAttrib(FILE* fid,const char* indent);
+		virtual void  AddCommnt(int ncom,char** pcom);
+		virtual void  AddCommnt(char* value);
+		virtual void  FindCommnt(char** pvalue,int inum);
+		virtual void  WriteCommnt(FILE* fid,const char* indent);
+
+};
+#endif  /* _KML_OBJECT_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Overlay.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Overlay.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Overlay.cpp	(revision 11330)
@@ -0,0 +1,150 @@
+/*!\file KML_Overlay.cpp
+ * \brief: implementation of the kml_overlay abstract object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Overlay::KML_Overlay(){{{1*/
+KML_Overlay::KML_Overlay(){
+
+	strcpy(color     ,"ffffffff");
+	memcpy(color,"ffffffff",(strlen("ffffffff")+1)*sizeof(char));
+
+	draword   = 0;
+	icon      =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_Overlay::~KML_Overlay(){{{1*/
+KML_Overlay::~KML_Overlay(){
+
+	if (icon) {
+		delete icon;
+		icon      =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Overlay::Echo {{{1*/
+void  KML_Overlay::Echo(){
+
+	bool  flag=true;
+
+	KML_Feature::Echo();
+
+	_printf_(flag,"         color: \"%s\"\n" ,color);
+	_printf_(flag,"       draword: %d\n"     ,draword);
+	_printf_(flag,"          icon: %p\n"     ,icon);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Overlay::DeepEcho {{{1*/
+void  KML_Overlay::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Overlay::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Overlay::DeepEcho {{{1*/
+void  KML_Overlay::DeepEcho(const char* indent){
+
+	char  indent2[81];
+	bool  flag=true;
+
+	KML_Feature::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	_printf_(flag,"%s         color: %s\n"          ,indent,color);
+	_printf_(flag,"%s       draword: %d\n"          ,indent,draword);
+	if (icon)
+		icon->DeepEcho(indent2);
+	else
+		_printf_(flag,"%s          icon: %p\n"          ,indent,icon);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Overlay::Write {{{1*/
+void  KML_Overlay::Write(FILE* filout,const char* indent){
+
+	char  indent2[81];
+
+	KML_Feature::Write(filout,indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	if (color     && strlen(color))
+		fprintf(filout,"%s  <color>%s</color>\n",indent,color);
+	fprintf(filout,"%s  <drawOrder>%d</drawOrder>\n",indent,draword);
+	if (icon)
+		icon->Write(filout,indent2);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Overlay::Read {{{1*/
+void  KML_Overlay::Read(FILE* fid,char* kstr){
+
+/*  process field within opening and closing tags  */
+
+	if      (!strncmp(kstr,"</Overlay", 9)) {
+		xfree((void**)&kstr);
+		return;
+	}
+	else if (!strncmp(kstr,"</",2))
+		_error_("KML_Overlay::Read -- Unexpected closing tag %s.\n",kstr);
+	else if (strncmp(kstr,"<",1))
+		_error_("KML_Overlay::Read -- Unexpected field \"%s\".\n",kstr);
+
+	else if (!strcmp(kstr,"<color>"))
+		KMLFileTokenParse( color     ,NULL,KML_OVERLAY_COLOR_LENGTH,
+						  kstr,
+						  fid);
+	else if (!strcmp(kstr,"<drawOrder>"))
+		KMLFileTokenParse(&draword   ,
+						  kstr,
+						  fid);
+
+	else if (!strncmp(kstr,"<Icon", 5)) {
+		icon      =new KML_Icon();
+		icon      ->Read(fid,kstr);
+	}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Feature::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Overlay.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Overlay.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Overlay.h	(revision 11330)
@@ -0,0 +1,49 @@
+/*! \file KML_Overlay.h 
+ *  \brief: header file for kml_overlay abstract object
+ */
+
+#ifndef _KML_OVERLAY_H_
+#define _KML_OVERLAY_H_
+
+#define KML_OVERLAY_COLOR_LENGTH  8
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Feature.h"
+class KML_Icon;
+/*}}}*/
+
+class KML_Overlay: public KML_Feature {
+
+	public:
+
+		char  color[KML_OVERLAY_COLOR_LENGTH+1];
+		int   draword;
+		KML_Icon* icon;
+
+		/*KML_Overlay constructors, destructors {{{1*/
+		KML_Overlay();
+		~KML_Overlay();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_OVERLAY_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Placemark.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Placemark.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Placemark.cpp	(revision 11330)
@@ -0,0 +1,211 @@
+/*!\file KML_Placemark.cpp
+ * \brief: implementation of the kml_placemark object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Placemark::KML_Placemark(){{{1*/
+KML_Placemark::KML_Placemark(){
+
+	geometry  =new DataSet;
+
+}
+/*}}}*/
+/*FUNCTION KML_Placemark::~KML_Placemark(){{{1*/
+KML_Placemark::~KML_Placemark(){
+
+	if (geometry) {
+		delete geometry;
+		geometry  =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Placemark::Echo {{{1*/
+void  KML_Placemark::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_Placemark:\n");
+	KML_Feature::Echo();
+
+	_printf_(flag,"      geometry: (size=%d)\n" ,geometry->Size());
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Placemark::DeepEcho {{{1*/
+void  KML_Placemark::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Placemark::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Placemark::DeepEcho {{{1*/
+void  KML_Placemark::DeepEcho(const char* indent){
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_Placemark:\n",indent);
+	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++) {
+			_printf_(flag,"%s      geometry: -------- begin [%d] --------\n" ,indent,i);
+			((KML_Geometry *)geometry->GetObjectByOffset(i))->DeepEcho(indent2);
+			_printf_(flag,"%s      geometry: --------  end  [%d] --------\n" ,indent,i);
+		}
+	else
+		_printf_(flag,"%s      geometry: [empty]\n"    ,indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Placemark::Write {{{1*/
+void  KML_Placemark::Write(FILE* filout,const char* indent){
+
+	int   i;
+	char  indent2[81];
+
+	fprintf(filout,"%s<Placemark",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Feature::Write(filout,indent);
+
+/*  loop over the geometry elements for the placemark  */
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	for (i=0; i<geometry->Size(); i++)
+		((KML_Geometry *)geometry->GetObjectByOffset(i))->Write(filout,indent2);
+
+	fprintf(filout,"%s</Placemark>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Placemark::Read {{{1*/
+void  KML_Placemark::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+	KML_Object*  kobj;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Placemark",11)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_Placemark::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_Placemark::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strncmp(kstri,"<Point", 6)) {
+			kobj=(KML_Object*)new KML_Point();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LineString",11)) {
+			kobj=(KML_Object*)new KML_LineString();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LinearRing",11)) {
+			kobj=(KML_Object*)new KML_LinearRing();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<Polygon", 8)) {
+			kobj=(KML_Object*)new KML_Polygon();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<MultiGeometry",14)) {
+			kobj=(KML_Object*)new KML_MultiGeometry();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Feature::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Placemark::WriteExp {{{1*/
+void  KML_Placemark::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+	char  nstr2[81];
+
+/*  loop over the geometry elements for the placemark  */
+
+	for (i=0; i<geometry->Size(); i++) {
+		if (strlen(nstr))
+			sprintf(nstr2,"%s %s",nstr,name);
+		else
+			sprintf(nstr2,"%s",name);
+
+		((KML_Object *)geometry->GetObjectByOffset(i))->WriteExp(fid,nstr2,sgn,cm,sp);
+	}
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Placemark.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Placemark.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Placemark.h	(revision 11330)
@@ -0,0 +1,47 @@
+/*! \file KML_Placemark.h 
+ *  \brief: header file for kml_placemark object
+ */
+
+#ifndef _KML_PLACEMARK_H_
+#define _KML_PLACEMARK_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Feature.h"
+class KML_Geometry;
+class DataSet;
+/*}}}*/
+
+class KML_Placemark: public KML_Feature {
+
+	public:
+
+		DataSet* geometry;
+
+		/*KML_Placemark constructors, destructors {{{1*/
+		KML_Placemark();
+		~KML_Placemark();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_PLACEMARK_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Point.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Point.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Point.cpp	(revision 11330)
@@ -0,0 +1,199 @@
+/*!\file KML_Point.cpp
+ * \brief: implementation of the kml_point object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+#include "../../modules/Ll2xyx/Ll2xyx.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Point::KML_Point(){{{1*/
+KML_Point::KML_Point(){
+
+	extrude   =false;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	coords[0] = 0.;
+	coords[1] = 0.;
+	coords[2] = 0.;
+
+}
+/*}}}*/
+/*FUNCTION KML_Point::~KML_Point(){{{1*/
+KML_Point::~KML_Point(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Point::Echo {{{1*/
+void  KML_Point::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_Point:\n");
+	KML_Geometry::Echo();
+
+	_printf_(flag,"       extrude: %s\n"         ,(extrude ? "true" : "false"));
+	_printf_(flag,"       altmode: \"%s\"\n"     ,altmode);
+	_printf_(flag,"        coords: (%g,%g,%g)\n" ,coords[0],coords[1],coords[2]);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Point::DeepEcho {{{1*/
+void  KML_Point::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Point::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Point::DeepEcho {{{1*/
+void  KML_Point::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_Point:\n",indent);
+	KML_Geometry::DeepEcho(indent);
+
+	_printf_(flag,"%s       extrude: %s\n"         ,indent,(extrude ? "true" : "false"));
+	_printf_(flag,"%s       altmode: \"%s\"\n"     ,indent,altmode);
+	_printf_(flag,"%s        coords: (%g,%g,%g)\n" ,indent,coords[0],coords[1],coords[2]);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Point::Write {{{1*/
+void  KML_Point::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<Point",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Geometry::Write(filout,indent);
+
+	fprintf(filout,"%s  <extrude>%d</extrude>\n",indent,(extrude ? 1 : 0));
+	fprintf(filout,"%s  <altitudeMode>%s</altitudeMode>\n",indent,altmode);
+	fprintf(filout,"%s  <coordinates>%0.16g,%0.16g,%0.16g</coordinates>\n",
+			indent,coords[0],coords[1],coords[2]);
+
+	fprintf(filout,"%s</Point>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Point::Read {{{1*/
+void  KML_Point::Read(FILE* fid,char* kstr){
+
+	double*      pcoords=&coords[0];
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Point", 7)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_Point::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_Point::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude   ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_POINT_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<coordinates>"))
+			KMLFileTokenParse(&pcoords   ,NULL,3,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Point::WriteExp {{{1*/
+void  KML_Point::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int     i;
+	double  lat,lon,x,y;
+	char    nstr2[81];
+
+/*  extract latitude and longitude  */
+
+	lon=coords[0];
+	lat=coords[1];
+
+/*  convert latitude and longitude to x and y  */
+
+	Ll2xyx(&x,&y,&lat,&lon,1,sgn,cm,sp);
+
+/*  write header  */
+
+	memcpy(nstr2,nstr,(strlen(nstr)+1)*sizeof(char));
+
+	for (i=0; i<strlen(nstr2); i++)
+		if ((nstr2[i] == ' ') || (nstr2[i] == '\t'))
+			nstr2[i]='_';
+	fprintf(fid,"## Name:%s\n",nstr2);
+	fprintf(fid,"## Icon:0\n");
+	fprintf(fid,"# Points Count	Value\n");
+    fprintf(fid,"%u	%s\n",1,"1.");
+	fprintf(fid,"# X pos	Y pos\n");
+
+/*  write vertex  */
+
+    fprintf(fid,"%lf\t%lf\n",x,y);
+
+/*  write blank line  */
+
+	fprintf(fid,"\n");
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Point.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Point.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Point.h	(revision 11330)
@@ -0,0 +1,49 @@
+/*! \file KML_Point.h 
+ *  \brief: header file for kml_point object
+ */
+
+#ifndef _KML_POINT_H_
+#define _KML_POINT_H_
+
+#define KML_POINT_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Geometry.h"
+/*}}}*/
+
+class KML_Point: public KML_Geometry {
+
+	public:
+
+		bool  extrude;
+		char  altmode[KML_POINT_ALTMODE_LENGTH+1];
+		double coords[3];
+
+		/*KML_Point constructors, destructors {{{1*/
+		KML_Point();
+		~KML_Point();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POINT_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_PolyStyle.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_PolyStyle.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_PolyStyle.cpp	(revision 11330)
@@ -0,0 +1,151 @@
+/*!\file KML_PolyStyle.cpp
+ * \brief: implementation of the kml_polystyle object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_PolyStyle::KML_PolyStyle(){{{1*/
+KML_PolyStyle::KML_PolyStyle(){
+
+	fill      =true;
+	outline   =true;
+
+}
+/*}}}*/
+/*FUNCTION KML_PolyStyle::~KML_PolyStyle(){{{1*/
+KML_PolyStyle::~KML_PolyStyle(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_PolyStyle::Echo {{{1*/
+void  KML_PolyStyle::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_PolyStyle:\n");
+	KML_ColorStyle::Echo();
+
+	_printf_(flag,"          fill: %d\n"          ,fill);
+	_printf_(flag,"       outline: %d\n"          ,outline);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_PolyStyle::DeepEcho {{{1*/
+void  KML_PolyStyle::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_PolyStyle::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_PolyStyle::DeepEcho {{{1*/
+void  KML_PolyStyle::DeepEcho(const char* indent){
+
+	int   i;
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_PolyStyle:\n",indent);
+	KML_ColorStyle::DeepEcho(indent);
+
+	_printf_(flag,"%s          fill: %d\n"          ,indent,fill);
+	_printf_(flag,"%s       outline: %d\n"          ,indent,outline);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_PolyStyle::Write {{{1*/
+void  KML_PolyStyle::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<PolyStyle",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_ColorStyle::Write(filout,indent);
+
+	fprintf(filout,"%s  <fill>%d</fill>\n",indent,fill);
+	fprintf(filout,"%s  <outline>%d</outline>\n",indent,outline);
+
+	fprintf(filout,"%s</PolyStyle>\n",indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_PolyStyle::Read {{{1*/
+void  KML_PolyStyle::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</PolyStyle",11)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_PolyStyle::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_PolyStyle::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strcmp(kstri,"<fill>"))
+			KMLFileTokenParse(&fill      ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<outline>"))
+			KMLFileTokenParse(&outline   ,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_ColorStyle::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_PolyStyle.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_PolyStyle.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_PolyStyle.h	(revision 11330)
@@ -0,0 +1,45 @@
+/*! \file KML_PolyStyle.h 
+ *  \brief: header file for kml_polystyle object
+ */
+
+#ifndef _KML_POLYSTYLE_H_
+#define _KML_POLYSTYLE_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_ColorStyle.h"
+/*}}}*/
+
+class KML_PolyStyle: public KML_ColorStyle {
+
+	public:
+
+		int   fill;
+		int   outline;
+
+		/*KML_PolyStyle constructors, destructors {{{1*/
+		KML_PolyStyle();
+		~KML_PolyStyle();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POLYSTYLE_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Polygon.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Polygon.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Polygon.cpp	(revision 11330)
@@ -0,0 +1,300 @@
+/*!\file KML_Polygon.cpp
+ * \brief: implementation of the kml_polygon object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Polygon::KML_Polygon(){{{1*/
+KML_Polygon::KML_Polygon(){
+
+	extrude   =false;
+	tessellate=false;
+	memcpy(altmode,"clampToGround",(strlen("clampToGround")+1)*sizeof(char));
+
+	outer     =new DataSet;
+	inner     =new DataSet;
+
+}
+/*}}}*/
+/*FUNCTION KML_Polygon::~KML_Polygon(){{{1*/
+KML_Polygon::~KML_Polygon(){
+
+	if (inner) {
+		delete inner;
+		inner     =NULL;
+	}
+
+	if (outer) {
+		delete outer;
+		outer     =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Polygon::Echo {{{1*/
+void  KML_Polygon::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_Polygon:\n");
+	KML_Geometry::Echo();
+
+	_printf_(flag,"       extrude: %s\n"          ,(extrude ? "true" : "false"));
+	_printf_(flag,"    tessellate: %s\n"          ,(tessellate ? "true" : "false"));
+	_printf_(flag,"       altmode: \"%s\"\n"      ,altmode);
+	_printf_(flag,"         outer: (size=%d)\n"   ,outer->Size());
+	_printf_(flag,"         inner: (size=%d)\n"   ,inner->Size());
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Polygon::DeepEcho {{{1*/
+void  KML_Polygon::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Polygon::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Polygon::DeepEcho {{{1*/
+void  KML_Polygon::DeepEcho(const char* indent){
+
+	int   i;
+	char  indent2[81];
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_Polygon:\n",indent);
+	KML_Geometry::DeepEcho(indent);
+
+	_printf_(flag,"%s       extrude: %s\n"          ,indent,(extrude ? "true" : "false"));
+	_printf_(flag,"%s    tessellate: %s\n"          ,indent,(tessellate ? "true" : "false"));
+	_printf_(flag,"%s       altmode: \"%s\"\n"      ,indent,altmode);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+	if (outer->Size())
+		for (i=0; i<outer->Size(); i++) {
+			_printf_(flag,"%s         outer: -------- begin [%d] --------\n" ,indent,i);
+			((KML_LinearRing *)outer->GetObjectByOffset(i))->DeepEcho(indent2);
+			_printf_(flag,"%s         outer: --------  end  [%d] --------\n" ,indent,i);
+		}
+	else
+		_printf_(flag,"%s         outer: [empty]\n"    ,indent);
+
+	if (inner->Size())
+		for (i=0; i<inner->Size(); i++) {
+			_printf_(flag,"%s         inner: -------- begin [%d] --------\n" ,indent,i);
+			((KML_LinearRing *)inner->GetObjectByOffset(i))->DeepEcho(indent2);
+			_printf_(flag,"%s         inner: --------  end  [%d] --------\n" ,indent,i);
+		}
+	else
+		_printf_(flag,"%s         inner: [empty]\n"    ,indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Polygon::Write {{{1*/
+void  KML_Polygon::Write(FILE* filout,const char* indent){
+
+	int   i;
+	char  indent4[81];
+
+	fprintf(filout,"%s<Polygon",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Geometry::Write(filout,indent);
+
+	fprintf(filout,"%s  <extrude>%d</extrude>\n",indent,(extrude ? 1 : 0));
+	fprintf(filout,"%s  <tessellate>%d</tessellate>\n",indent,(tessellate ? 1 : 0));
+	fprintf(filout,"%s  <altitudeMode>%s</altitudeMode>\n",indent,altmode);
+
+	memcpy(indent4,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent4,"    ");
+
+/*  check outer boundary for the polygon  */
+
+	fprintf(filout,"%s  <outerBoundaryIs>\n",indent);
+	if (outer->Size())
+		((KML_LinearRing *)outer->GetObjectByOffset(0))->Write(filout,indent4);
+	fprintf(filout,"%s  </outerBoundaryIs>\n",indent);
+
+/*  loop over any inner boundaries for the polygon  */
+
+	for (i=0; i<inner->Size(); i++) {
+		fprintf(filout,"%s  <innerBoundaryIs>\n",indent);
+		((KML_LinearRing *)inner->GetObjectByOffset(i))->Write(filout,indent4);
+		fprintf(filout,"%s  </innerBoundaryIs>\n",indent);
+	}
+
+	fprintf(filout,"%s</Polygon>\n",indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Polygon::Read {{{1*/
+void  KML_Polygon::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	char*        kstrj;
+	int          ncom=0;
+	char**       pcom=NULL;
+	KML_Object*  kobj;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Polygon", 9)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_Polygon::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_Polygon::Read -- Unexpected field \"%s\".\n",kstri);
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude   ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<tessellate>"))
+			KMLFileTokenParse(&tessellate,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_POLYGON_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+
+		else if (!strcmp(kstri,"<outerBoundaryIs>"))
+
+/*  loop over and process fields within outer boundary  */
+
+			while (kstrj=KMLFileToken(fid,
+									  &ncom,&pcom)) {
+				if      (!strncmp(kstrj,"</outerBoundaryIs",17)) {
+					xfree((void**)&kstrj);
+					break;
+				}
+				else if (!strncmp(kstrj,"</",2))
+					_error_("KML_Polygon::Read -- Unexpected closing tag %s.\n",kstrj);
+				else if (strncmp(kstrj,"<",1))
+					_error_("KML_Polygon::Read -- Unexpected field \"%s\".\n",kstrj);
+
+				else if (!strncmp(kstrj,"<LinearRing",11)) {
+					kobj=(KML_Object*)new KML_LinearRing();
+					kobj->Read(fid,kstrj);
+					outer     ->AddObject((Object*)kobj);
+				}
+
+				else if (!strncmp(kstrj,"<",1))
+					KML_Geometry::Read(fid,kstrj);
+
+				xfree((void**)&kstrj);
+			}
+
+		else if (!strcmp(kstri,"<innerBoundaryIs>"))
+
+/*  loop over and process fields within inner boundaries  */
+
+			while (kstrj=KMLFileToken(fid,
+									  &ncom,&pcom)) {
+				if      (!strncmp(kstrj,"</innerBoundaryIs",17)) {
+					xfree((void**)&kstrj);
+					break;
+				}
+				else if (!strncmp(kstrj,"</",2))
+					_error_("KML_Polygon::Read -- Unexpected closing tag %s.\n",kstrj);
+				else if (strncmp(kstrj,"<",1))
+					_error_("KML_Polygon::Read -- Unexpected field \"%s\".\n",kstrj);
+
+				else if (!strncmp(kstrj,"<LinearRing",11)) {
+					kobj=(KML_Object*)new KML_LinearRing();
+					kobj->Read(fid,kstrj);
+					inner     ->AddObject((Object*)kobj);
+				}
+
+				else if (!strncmp(kstrj,"<",1))
+					KML_Geometry::Read(fid,kstrj);
+
+				xfree((void**)&kstrj);
+			}
+
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Polygon::WriteExp {{{1*/
+void  KML_Polygon::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+	char  nstr2[81];
+
+/*  check outer boundary for the polygon  */
+
+	if (outer->Size()) {
+		if (strlen(nstr))
+			sprintf(nstr2,"%s (outer)",nstr);
+		else
+			sprintf(nstr2,"(outer)");
+
+		((KML_LinearRing *)outer->GetObjectByOffset(0))->WriteExp(fid,nstr2,sgn,cm,sp);
+	}
+
+/*  loop over any inner boundaries for the polygon  */
+
+	for (i=0; i<inner->Size(); i++) {
+		if (strlen(nstr))
+			sprintf(nstr2,"%s (inner %d of %d)",nstr,i+1,inner->Size());
+		else
+			sprintf(nstr2,"(inner %d of %d)",i+1,inner->Size());
+
+		((KML_LinearRing *)inner->GetObjectByOffset(i))->WriteExp(fid,nstr2,sgn,cm,sp);
+	}
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Polygon.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Polygon.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Polygon.h	(revision 11330)
@@ -0,0 +1,53 @@
+/*! \file KML_Polygon.h 
+ *  \brief: header file for kml_polygon object
+ */
+
+#ifndef _KML_POLYGON_H_
+#define _KML_POLYGON_H_
+
+#define KML_POLYGON_ALTMODE_LENGTH    18
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Geometry.h"
+class KML_LinearRing;
+class DataSet;
+/*}}}*/
+
+class KML_Polygon: public KML_Geometry {
+
+	public:
+
+		bool  extrude;
+		bool  tessellate;
+		char  altmode[KML_POLYGON_ALTMODE_LENGTH+1];
+		DataSet* outer;
+		DataSet* inner;
+
+		/*KML_Polygon constructors, destructors {{{1*/
+		KML_Polygon();
+		~KML_Polygon();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POLYGON_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Style.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Style.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Style.cpp	(revision 11330)
@@ -0,0 +1,249 @@
+/*!\file KML_Style.cpp
+ * \brief: implementation of the kml_style object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Style::KML_Style(){{{1*/
+KML_Style::KML_Style(){
+
+	icon      =NULL;
+	label     =NULL;
+	line      =NULL;
+	poly      =NULL;
+	balloon   =NULL;
+	list      =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_Style::~KML_Style(){{{1*/
+KML_Style::~KML_Style(){
+
+	if (list) {
+//		delete list;
+		if (list      ) xfree((void**)&list);
+		list      =NULL;
+	}
+	if (balloon) {
+//		delete balloon;
+		if (balloon   ) xfree((void**)&balloon);
+		balloon   =NULL;
+	}
+	if (poly) {
+		delete poly;
+		poly      =NULL;
+	}
+	if (line) {
+		delete line;
+		line      =NULL;
+	}
+	if (label) {
+//		delete label;
+		if (label     ) xfree((void**)&label);
+		label     =NULL;
+	}
+	if (icon) {
+//		delete icon;
+		if (icon      ) xfree((void**)&icon);
+		icon      =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Style::Echo {{{1*/
+void  KML_Style::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_Style:\n");
+	KML_StyleSelector::Echo();
+
+	_printf_(flag,"          icon: %p\n"          ,icon);
+	_printf_(flag,"         label: %p\n"          ,label);
+	_printf_(flag,"          line: %p\n"          ,line);
+	_printf_(flag,"          poly: %p\n"          ,poly);
+	_printf_(flag,"       balloon: %p\n"          ,balloon);
+	_printf_(flag,"          list: %p\n"          ,list);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Style::DeepEcho {{{1*/
+void  KML_Style::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Style::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Style::DeepEcho {{{1*/
+void  KML_Style::DeepEcho(const char* indent){
+
+	char  indent2[81];
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_Style:\n",indent);
+	KML_StyleSelector::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+//	if (icon)
+//		icon->DeepEcho(indent2);
+//	else
+		_printf_(flag,"%s          icon: %p\n"          ,indent,icon);
+//	if (label)
+//		label->DeepEcho(indent2);
+//	else
+		_printf_(flag,"%s         label: %p\n"          ,indent,label);
+	if (line)
+		line->DeepEcho(indent2);
+	else
+		_printf_(flag,"%s          line: %p\n"          ,indent,line);
+	if (poly)
+		poly->DeepEcho(indent2);
+	else
+		_printf_(flag,"%s          poly: %p\n"          ,indent,poly);
+//	if (balloon)
+//		balloon->DeepEcho(indent2);
+//	else
+		_printf_(flag,"%s       balloon: %p\n"          ,indent,balloon);
+//	if (list)
+//		list->DeepEcho(indent2);
+//	else
+		_printf_(flag,"%s          list: %p\n"          ,indent,list);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Style::Write {{{1*/
+void  KML_Style::Write(FILE* filout,const char* indent){
+
+	char  indent2[81];
+
+	fprintf(filout,"%s<Style",indent);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_StyleSelector::Write(filout,indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+
+	strcat(indent2,"  ");
+
+//	if (icon)
+//		icon->Write(filout,indent2);
+//	if (label)
+//		label->Write(filout,indent2);
+	if (line)
+		line->Write(filout,indent2);
+	if (poly)
+		poly->Write(filout,indent2);
+//	if (balloon)
+//		balloon->Write(filout,indent2);
+//	if (list)
+//		list->Write(filout,indent2);
+
+	fprintf(filout,"%s</Style>\n",indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_Style::Read {{{1*/
+void  KML_Style::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	int          ncom=0;
+	char**       pcom=NULL;
+
+/*  get object attributes and check for solo tag  */
+
+	if (KMLFileTagAttrib(this,
+						 kstr))
+		return;
+
+/*  loop over and process fields within opening and closing tags  */
+
+	while (kstri=KMLFileToken(fid,
+							  &ncom,&pcom)) {
+		if      (!strncmp(kstri,"</Style", 7)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_Style::Read -- Unexpected closing tag %s.\n",kstri);
+		else if (strncmp(kstri,"<",1))
+			_error_("KML_Style::Read -- Unexpected field \"%s\".\n",kstri);
+
+//		else if (!strncmp(kstri,"<IconStyle",10)) {
+//			icon      =new KML_IconStyle();
+//			icon      ->Read(fid,kstri);
+//		}
+
+//		else if (!strncmp(kstri,"<LabelStyle",11)) {
+//			label     =new KML_LabelStyle();
+//			label     ->Read(fid,kstri);
+//		}
+
+		else if (!strncmp(kstri,"<LineStyle",10)) {
+			line      =new KML_LineStyle();
+			line      ->Read(fid,kstri);
+		}
+
+		else if (!strncmp(kstri,"<PolyStyle",10)) {
+			poly      =new KML_PolyStyle();
+			poly      ->Read(fid,kstri);
+		}
+
+//		else if (!strncmp(kstri,"<BalloonStyle",13)) {
+//			balloon   =new KML_BalloonStyle();
+//			balloon   ->Read(fid,kstri);
+//		}
+
+//		else if (!strncmp(kstri,"<ListStyle",10)) {
+//			list      =new KML_ListStyle();
+//			list      ->Read(fid,kstri);
+//		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_StyleSelector::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Style.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Style.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Style.h	(revision 11330)
@@ -0,0 +1,51 @@
+/*! \file KML_Style.h 
+ *  \brief: header file for kml_style object
+ */
+
+#ifndef _KML_STYLE_H_
+#define _KML_STYLE_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_StyleSelector.h"
+class KML_LineStyle;
+class KML_PolyStyle;
+/*}}}*/
+
+class KML_Style: public KML_StyleSelector {
+
+	public:
+
+		void* icon;
+		void* label;
+		KML_LineStyle* line;
+		KML_PolyStyle* poly;
+		void* balloon;
+		void* list;
+
+		/*KML_Style constructors, destructors {{{1*/
+		KML_Style();
+		~KML_Style();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_STYLE_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_StyleSelector.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_StyleSelector.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_StyleSelector.cpp	(revision 11330)
@@ -0,0 +1,94 @@
+/*!\file KML_StyleSelector.cpp
+ * \brief: implementation of the kml_styleselector abstract object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_StyleSelector::KML_StyleSelector(){{{1*/
+KML_StyleSelector::KML_StyleSelector(){
+
+	;
+
+}
+/*}}}*/
+/*FUNCTION KML_StyleSelector::~KML_StyleSelector(){{{1*/
+KML_StyleSelector::~KML_StyleSelector(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_StyleSelector::Echo {{{1*/
+void  KML_StyleSelector::Echo(){
+
+	KML_Object::Echo();
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_StyleSelector::DeepEcho {{{1*/
+void  KML_StyleSelector::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_StyleSelector::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_StyleSelector::DeepEcho {{{1*/
+void  KML_StyleSelector::DeepEcho(const char* indent){
+
+	KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_StyleSelector::Write {{{1*/
+void  KML_StyleSelector::Write(FILE* filout,const char* indent){
+
+	KML_Object::Write(filout,indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_StyleSelector::Read {{{1*/
+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 %s.\n",kstr);
+	else if (strncmp(kstr,"<",1))
+		_error_("KML_StyleSelector::Read -- Unexpected field \"%s\".\n",kstr);
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_StyleSelector.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_StyleSelector.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_StyleSelector.h	(revision 11330)
@@ -0,0 +1,42 @@
+/*! \file KML_StyleSelector.h 
+ *  \brief: header file for kml_styleselector abstract object
+ */
+
+#ifndef _KML_STYLESELECTOR_H_
+#define _KML_STYLESELECTOR_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_StyleSelector: public KML_Object {
+
+	public:
+
+		/*KML_StyleSelector constructors, destructors {{{1*/
+		KML_StyleSelector();
+		~KML_StyleSelector();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_STYLESELECTOR_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_SubStyle.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_SubStyle.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_SubStyle.cpp	(revision 11330)
@@ -0,0 +1,94 @@
+/*!\file KML_SubStyle.cpp
+ * \brief: implementation of the kml_substyle abstract object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_SubStyle::KML_SubStyle(){{{1*/
+KML_SubStyle::KML_SubStyle(){
+
+	;
+
+}
+/*}}}*/
+/*FUNCTION KML_SubStyle::~KML_SubStyle(){{{1*/
+KML_SubStyle::~KML_SubStyle(){
+
+	;
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_SubStyle::Echo {{{1*/
+void  KML_SubStyle::Echo(){
+
+	KML_Object::Echo();
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_SubStyle::DeepEcho {{{1*/
+void  KML_SubStyle::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_SubStyle::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_SubStyle::DeepEcho {{{1*/
+void  KML_SubStyle::DeepEcho(const char* indent){
+
+	KML_Object::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_SubStyle::Write {{{1*/
+void  KML_SubStyle::Write(FILE* filout,const char* indent){
+
+	KML_Object::Write(filout,indent);
+
+	return;
+}
+/*}}}*/
+
+/*FUNCTION KML_SubStyle::Read {{{1*/
+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 %s.\n",kstr);
+	else if (strncmp(kstr,"<",1))
+		_error_("KML_SubStyle::Read -- Unexpected field \"%s\".\n",kstr);
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_SubStyle.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_SubStyle.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_SubStyle.h	(revision 11330)
@@ -0,0 +1,42 @@
+/*! \file KML_SubStyle.h 
+ *  \brief: header file for kml_substyle abstract object
+ */
+
+#ifndef _KML_SUBSTYLE_H_
+#define _KML_SUBSTYLE_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_SubStyle: public KML_Object {
+
+	public:
+
+		/*KML_SubStyle constructors, destructors {{{1*/
+		KML_SubStyle();
+		~KML_SubStyle();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_SUBSTYLE_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Unknown.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Unknown.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Unknown.cpp	(revision 11330)
@@ -0,0 +1,141 @@
+/*!\file KML_Unknown.cpp
+ * \brief: implementation of the kml_unknown object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION KML_Unknown::KML_Unknown(){{{1*/
+KML_Unknown::KML_Unknown(){
+
+	name      =NULL;
+	value     =NULL;
+
+}
+/*}}}*/
+/*FUNCTION KML_Unknown::~KML_Unknown(){{{1*/
+KML_Unknown::~KML_Unknown(){
+
+	if (name      ) xfree((void**)&name);
+	if (value     ) xfree((void**)&value);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Unknown::Echo {{{1*/
+void  KML_Unknown::Echo(){
+
+	bool  flag=true;
+
+	_printf_(flag,"KML_Unknown_%s:\n",name);
+	KML_Object::Echo();
+
+	if (value     )
+		_printf_(flag,"         value: \"%s\"\n"     ,value);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Unknown::DeepEcho {{{1*/
+void  KML_Unknown::DeepEcho(){
+
+	char  indent[81]="";
+
+	KML_Unknown::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Unknown::DeepEcho {{{1*/
+void  KML_Unknown::DeepEcho(const char* indent){
+
+	bool  flag=true;
+
+	_printf_(flag,"%sKML_Unknown_%s:\n",indent,name);
+	KML_Object::DeepEcho(indent);
+
+	if (value     )
+		_printf_(flag,"%s         value: \"%s\"\n"     ,indent,value);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Unknown::Write {{{1*/
+void  KML_Unknown::Write(FILE* filout,const char* indent){
+
+	fprintf(filout,"%s<%s",indent,name);
+	WriteAttrib(filout," ");
+	fprintf(filout,">\n");
+	WriteCommnt(filout,indent);
+
+	KML_Object::Write(filout,indent);
+
+	if (value     )
+		fprintf(filout,"%s  %s\n",indent,value);
+
+	fprintf(filout,"%s</%s>\n",indent,name);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Unknown::Read {{{1*/
+void  KML_Unknown::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[0],"</", 2) &&
+				 !strncmp(&kstri[2],name,strlen(name))) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+			_error_("KML_Unknown::Read -- Unexpected closing tag %s.\n",kstri);
+
+		else if (strncmp(kstri,"<",1))
+			KMLFileTokenParse( value     ,NULL,0,
+							  NULL,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/KML/KML_Unknown.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/KML/KML_Unknown.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/KML/KML_Unknown.h	(revision 11330)
@@ -0,0 +1,45 @@
+/*! \file KML_Unknown.h 
+ *  \brief: header file for kml_unknown object
+ */
+
+#ifndef _KML_UNKNOWN_H_
+#define _KML_UNKNOWN_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./KML_Object.h"
+/*}}}*/
+
+class KML_Unknown: public KML_Object {
+
+	public:
+
+		char* name;
+		char* value;
+
+		/*KML_Unknown constructors, destructors {{{1*/
+		KML_Unknown();
+		~KML_Unknown();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(const char* indent);
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		int   Id(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_UNKNOWN_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/Loads/Friction.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Loads/Friction.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Loads/Friction.cpp	(revision 11330)
@@ -0,0 +1,334 @@
+/*!\file Friction.c
+ * \brief: implementation of the Friction object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../Container/Container.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+/*}}}*/	
+
+/*Constructors/destructors*/
+/*FUNCTION Friction::Friction() {{{1*/
+Friction::Friction(){
+	this->element_type=NULL;
+	this->inputs=NULL;
+	this->matpar=NULL;
+}
+/*}}}*/
+/*FUNCTION Friction::Friction(const char* element_type, Inputs* inputs,Matpar* matpar,int analysis_type){{{1*/
+Friction::Friction(const char* element_type_in,Inputs* inputs_in,Matpar* matpar_in, int in_analysis_type){
+
+	this->analysis_type=in_analysis_type;
+	this->inputs=inputs_in;
+	this->element_type=(char*)xmalloc((strlen(element_type_in)+1)*sizeof(char));
+	memcpy(this->element_type,element_type_in,(strlen(element_type_in)+1)*sizeof(char));
+
+	this->matpar=matpar_in;
+}
+/*}}}*/
+/*FUNCTION Friction::~Friction() {{{1*/
+Friction::~Friction(){
+	xfree((void**)&element_type);
+}
+/*}}}*/
+
+/*methods: */
+/*FUNCTION Friction::Echo {{{1*/
+void Friction::Echo(void){
+	printf("Friction:\n");
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	printf("   element_type: %s\n",this->element_type);
+	inputs->Echo();
+	matpar->Echo();
+}
+/*}}}*/
+/*FUNCTION Friction::GetAlpha2(double* palpha2, GaussTria* gauss,int vxenum,int vyenum,int vzenum){{{1*/
+void Friction::GetAlpha2(double* palpha2, GaussTria* gauss,int vxenum,int vyenum,int vzenum){
+
+	/*This routine calculates the basal friction coefficient 
+	  alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p**/
+
+	/*diverse: */
+	double  r,s;
+	double  drag_p, drag_q;
+	double  gravity,rho_ice,rho_water;
+	double  Neff;
+	double  thickness,bed;
+	double  vx,vy,vz,vmag;
+	double  drag_coefficient;
+	double  alpha2;
+
+	/*Recover parameters: */
+	inputs->GetInputValue(&drag_p,FrictionPEnum);
+	inputs->GetInputValue(&drag_q,FrictionQEnum);
+	this->GetInputValue(&thickness, gauss,ThicknessEnum);
+	this->GetInputValue(&bed, gauss,BedEnum);
+	this->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
+
+	/*Get material parameters: */
+	gravity=matpar->GetG();
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	//compute r and q coefficients: */
+	r=drag_q/drag_p;
+	s=1./drag_p;
+
+	//From bed and thickness, compute effective pressure when drag is viscous:
+	Neff=gravity*(rho_ice*thickness+rho_water*bed);
+
+	/*If effective pressure becomes negative, sliding becomes unstable (Paterson 4th edition p 148). This is because 
+	  the water pressure is so high, the ice sheet elevates over its ice bumps and slides. But the limit behaviour 
+	  for friction should be an ice shelf sliding (no basal drag). Therefore, for any effective pressure Neff < 0, we should 
+	  replace it by Neff=0 (ie, equival it to an ice shelf)*/
+	if (Neff<0)Neff=0;
+
+	if(strcmp(element_type,"2d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2));
+	}
+	else if (strcmp(element_type,"3d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		this->GetInputValue(&vz, gauss,vzenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2)+pow(vz,2));
+	}
+	else _error_("element_type %s not supported yet",element_type);
+
+	/*Checks that s-1>0 if v=0*/
+	if(vmag==0 && (s-1)<0) _error_("velocity is 0 ans (s-1)=%g<0, alpha_complement is Inf",s-1);
+
+	alpha2=pow(drag_coefficient,2)*pow(Neff,r)*pow(vmag,(s-1));
+	_assert_(!isnan(alpha2));
+
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}
+/*}}}*/
+/*FUNCTION Friction::GetAlpha2(double* palpha2, GaussPenta* gauss,int vxenum,int vyenum,int vzenum){{{1*/
+void Friction::GetAlpha2(double* palpha2, GaussPenta* gauss,int vxenum,int vyenum,int vzenum){
+
+	/*This routine calculates the basal friction coefficient 
+	  alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p**/
+
+	/*diverse: */
+	double  r,s;
+	double  drag_p, drag_q;
+	double  gravity,rho_ice,rho_water;
+	double  Neff;
+	double  thickness,bed;
+	double  vx,vy,vz,vmag;
+	double  drag_coefficient;
+	double  alpha2;
+
+	/*Recover parameters: */
+	inputs->GetInputValue(&drag_p,FrictionPEnum);
+	inputs->GetInputValue(&drag_q,FrictionQEnum);
+	this->GetInputValue(&thickness, gauss,ThicknessEnum);
+	this->GetInputValue(&bed, gauss,BedEnum);
+	this->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
+
+	/*Get material parameters: */
+	gravity=matpar->GetG();
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	//compute r and q coefficients: */
+	r=drag_q/drag_p;
+	s=1./drag_p;
+
+	//From bed and thickness, compute effective pressure when drag is viscous:
+	Neff=gravity*(rho_ice*thickness+rho_water*bed);
+
+	/*If effective pressure becomes negative, sliding becomes unstable (Paterson 4th edition p 148). This is because 
+	  the water pressure is so high, the ice sheet elevates over its ice bumps and slides. But the limit behaviour 
+	  for friction should be an ice shelf sliding (no basal drag). Therefore, for any effective pressure Neff < 0, we should 
+	  replace it by Neff=0 (ie, equival it to an ice shelf)*/
+	if (Neff<0)Neff=0;
+
+	if(strcmp(element_type,"2d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2));
+	}
+	else if (strcmp(element_type,"3d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		this->GetInputValue(&vz, gauss,vzenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2)+pow(vz,2));
+	}
+	else _error_("element_type %s not supported yet",element_type);
+
+	/*Checks that s-1>0 if v=0*/
+	if(vmag==0 && (s-1)<0) _error_("velocity is 0 ans (s-1)=%g<0, alpha_complement is Inf",s-1);
+
+	alpha2=pow(drag_coefficient,2)*pow(Neff,r)*pow(vmag,(s-1));
+	_assert_(!isnan(alpha2));
+
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}
+/*}}}*/
+/*FUNCTION Friction::GetAlphaComplement(double* palpha_complement, GaussTria* gauss,int vxenum,int vyenum,int vzenum) {{{1*/
+void Friction::GetAlphaComplement(double* palpha_complement, GaussTria* gauss,int vxenum,int vyenum,int vzenum){
+
+	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p. 
+	 * FrictionGetAlphaComplement is used in control methods on drag, and it computes: 
+	 * alpha_complement= Neff ^r * vel ^s*/
+
+	/*diverse: */
+	int     i;
+	double  r,s;
+	double  vx,vy,vz,vmag;
+	double  drag_p,drag_q;
+	double  Neff;
+	double  drag_coefficient;
+	double  bed,thickness;
+	double  gravity,rho_ice,rho_water;
+	double  alpha_complement;
+
+	/*Recover parameters: */
+	inputs->GetInputValue(&drag_p,FrictionPEnum);
+	inputs->GetInputValue(&drag_q,FrictionQEnum);
+	this->GetInputValue(&thickness, gauss,ThicknessEnum);
+	this->GetInputValue(&bed, gauss,BedEnum);
+	this->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
+
+	/*Get material parameters: */
+	gravity=matpar->GetG();
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	//compute r and q coefficients: */
+	r=drag_q/drag_p;
+	s=1./drag_p;
+
+	//From bed and thickness, compute effective pressure when drag is viscous:
+	Neff=gravity*(rho_ice*thickness+rho_water*bed);
+
+	/*If effective pressure becomes negative, sliding becomes unstable (Paterson 4th edition p 148). This is because 
+	  the water pressure is so high, the ice sheet elevates over its ice bumps and slides. But the limit behaviour 
+	  for friction should be an ice shelf sliding (no basal drag). Therefore, for any effective pressure Neff < 0, we should 
+	  replace it by Neff=0 (ie, equival it to an ice shelf)*/
+	if (Neff<0)Neff=0;
+
+	//We need the velocity magnitude to evaluate the basal stress:
+	if(strcmp(element_type,"2d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2));
+	}
+	else if (strcmp(element_type,"3d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		this->GetInputValue(&vz, gauss,vzenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2)+pow(vz,2));
+	}
+	else _error_("element_type %s not supported yet",element_type);
+
+	/*Checks that s-1>0 if v=0*/
+	if(vmag==0 && (s-1)<0) _error_("velocity is 0 ans (s-1)=%g<0, alpha_complement is Inf",s-1);
+
+	alpha_complement=pow(Neff,r)*pow(vmag,(s-1));            _assert_(!isnan(alpha_complement));
+
+	/*Assign output pointers:*/
+	*palpha_complement=alpha_complement;
+}
+/*}}}*/
+/*FUNCTION Friction::GetAlphaComplement(double* palpha_complement, GaussPenta* gauss,int vxenum,int vyenum,int vzenum) {{{1*/
+void Friction::GetAlphaComplement(double* palpha_complement, GaussPenta* gauss,int vxenum,int vyenum,int vzenum){
+
+	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p. 
+	 * FrictionGetAlphaComplement is used in control methods on drag, and it computes: 
+	 * alpha_complement= Neff ^r * vel ^s*/
+
+	/*diverse: */
+	int     i;
+	double  r,s;
+	double  vx,vy,vz,vmag;
+	double  drag_p,drag_q;
+	double  Neff;
+	double  drag_coefficient;
+	double  bed,thickness;
+	double  gravity,rho_ice,rho_water;
+	double  alpha_complement;
+
+	/*Recover parameters: */
+	inputs->GetInputValue(&drag_p,FrictionPEnum);
+	inputs->GetInputValue(&drag_q,FrictionQEnum);
+	this->GetInputValue(&thickness, gauss,ThicknessEnum);
+	this->GetInputValue(&bed, gauss,BedEnum);
+	this->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
+
+	/*Get material parameters: */
+	gravity=matpar->GetG();
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	//compute r and q coefficients: */
+	r=drag_q/drag_p;
+	s=1./drag_p;
+
+	//From bed and thickness, compute effective pressure when drag is viscous:
+	Neff=gravity*(rho_ice*thickness+rho_water*bed);
+
+	/*If effective pressure becomes negative, sliding becomes unstable (Paterson 4th edition p 148). This is because 
+	  the water pressure is so high, the ice sheet elevates over its ice bumps and slides. But the limit behaviour 
+	  for friction should be an ice shelf sliding (no basal drag). Therefore, for any effective pressure Neff < 0, we should 
+	  replace it by Neff=0 (ie, equival it to an ice shelf)*/
+	if (Neff<0)Neff=0;
+
+	//We need the velocity magnitude to evaluate the basal stress:
+	if(strcmp(element_type,"2d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2));
+	}
+	else if (strcmp(element_type,"3d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		this->GetInputValue(&vz, gauss,vzenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2)+pow(vz,2));
+	}
+	else _error_("element_type %s not supported yet",element_type);
+
+	/*Checks that s-1>0 if v=0*/
+	if(vmag==0 && (s-1)<0) _error_("velocity is 0 ans (s-1)=%g<0, alpha_complement is Inf",s-1);
+
+	alpha_complement=pow(Neff,r)*pow(vmag,(s-1));            _assert_(!isnan(alpha_complement));
+
+	/*Assign output pointers:*/
+	*palpha_complement=alpha_complement;
+}
+/*}}}*/
+/*FUNCTION Friction::GetInputValue{{{1*/
+void Friction::GetInputValue(double* pvalue,GaussTria* gauss,int enum_type){
+
+	Input* input=inputs->GetInput(enum_type);
+	if(!input) _error_("input %s not found",EnumToStringx(enum_type));
+	input->GetInputValue(pvalue,gauss);
+
+}
+/*}}}*/
+/*FUNCTION Friction::GetInputValue{{{1*/
+void Friction::GetInputValue(double* pvalue,GaussPenta* gauss,int enum_type){
+
+	Input* input=inputs->GetInput(enum_type);
+	if(!input) _error_("input %s not found",EnumToStringx(enum_type));
+	input->GetInputValue(pvalue,gauss);
+
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Loads/Friction.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Loads/Friction.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Loads/Friction.h	(revision 11330)
@@ -0,0 +1,38 @@
+/*!\file Friction.h
+ * \brief: header file for friction object
+ */
+
+#ifndef _FRICTION_H_
+#define _FRICTION_H_
+
+/*Headers:*/
+/*{{{1*/
+class Inputs;
+class Matpar;
+/*}}}*/
+
+class Friction{
+
+	public:
+		int analysis_type;
+
+		char* element_type;
+		Inputs* inputs;
+		Matpar* matpar;
+
+		/*methods: */
+		Friction();
+		Friction(const char* element_type, Inputs* inputs,Matpar* matpar, int analysis_type);
+		~Friction();
+	
+		void  Echo(void);
+		void  GetAlpha2(double* palpha2, GaussTria* gauss,int vxenum,int vyenum,int vzenum);
+		void  GetAlpha2(double* palpha2, GaussPenta* gauss,int vxenum,int vyenum,int vzenum);
+		void  GetAlphaComplement(double* alpha_complement, GaussTria* gauss,int vxenum,int vyenum,int vzenum);
+		void  GetAlphaComplement(double* alpha_complement, GaussPenta* gauss,int vxenum,int vyenum,int vzenum);
+		void  GetInputValue(double* pvalue,GaussTria* gauss,int enum_type);
+		void  GetInputValue(double* pvalue,GaussPenta* gauss,int enum_type);
+
+};
+
+#endif  /* _FRICTION_H_ */
Index: /issm/trunk-jpl-damage/src/c/objects/Loads/Icefront.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Loads/Icefront.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Loads/Icefront.cpp	(revision 11330)
@@ -0,0 +1,821 @@
+/*!\file Icefront.c
+ * \brief: implementation of the Icefront object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+/*}}}*/	
+
+/*Load macros*/
+#define NUMVERTICESSEG 2
+#define NUMVERTICESQUA 4
+
+/*Icefront constructors and destructor*/
+/*FUNCTION Icefront::Icefront() {{{1*/
+Icefront::Icefront(){
+
+	this->inputs=NULL;
+	this->parameters=NULL;
+
+	this->hnodes=NULL;
+	this->nodes= NULL;
+	this->helement=NULL;
+	this->element= NULL;
+	this->hmatpar=NULL;
+	this->matpar= NULL;
+}
+/*}}}*/
+/*FUNCTION Icefront::Icefront(int id, int i, IoModel* iomodel,int analysis_type) {{{1*/
+Icefront::Icefront(int icefront_id,int i, IoModel* iomodel,int in_icefront_type, int in_analysis_type){
+
+	int segment_width;
+	int element;
+	int num_nodes; 
+	int dim;
+	int numberofelements;
+
+	/*icefront constructor data: */
+	int  icefront_eid;
+	int  icefront_mparid;
+	int  icefront_node_ids[NUMVERTICESQUA]; //initialize with largest size
+	int  icefront_fill;
+	
+	/*find parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+
+	/*First, retrieve element index and element type: */
+	if (dim==2){
+		segment_width=4;
+	}
+	else{
+		segment_width=6;
+	}
+	_assert_(iomodel->Data(DiagnosticIcefrontEnum));
+	element=(int)(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+segment_width-2)-1); //element is in the penultimate column (node1 node2 ... elem fill)
+
+	/*Build ids for hook constructors: */
+	icefront_eid=(int) *(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+segment_width-2); //matlab indexing
+	icefront_mparid=numberofelements+1; //matlab indexing
+
+	if (in_icefront_type==MacAyeal2dIceFrontEnum || in_icefront_type==MacAyeal3dIceFrontEnum){
+		icefront_node_ids[0]=iomodel->nodecounter+(int)*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+0);
+		icefront_node_ids[1]=iomodel->nodecounter+(int)*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+1);
+	}
+	else if (in_icefront_type==PattynIceFrontEnum || in_icefront_type==StokesIceFrontEnum){
+		icefront_node_ids[0]=iomodel->nodecounter+(int)*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+0);
+		icefront_node_ids[1]=iomodel->nodecounter+(int)*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+1);
+		icefront_node_ids[2]=iomodel->nodecounter+(int)*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+2);
+		icefront_node_ids[3]=iomodel->nodecounter+(int)*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+3);
+	}
+	else _error_("in_icefront_type %s not supported yet!",EnumToStringx(in_icefront_type));
+
+	if (in_icefront_type==PattynIceFrontEnum || in_icefront_type==StokesIceFrontEnum)
+	 num_nodes=4;
+	else 
+	 num_nodes=2;
+
+	/*Fill*/
+	icefront_fill=(int)iomodel->Data(DiagnosticIcefrontEnum)[segment_width*i+segment_width-1];
+	
+	/*Ok, we have everything to build the object: */
+	this->id=icefront_id;
+	this->analysis_type=in_analysis_type;
+
+	/*Hooks: */
+	this->hnodes=new Hook(icefront_node_ids,num_nodes);
+	this->helement=new Hook(&icefront_eid,1);
+	this->hmatpar=new Hook(&icefront_mparid,1);
+
+	//intialize  and add as many inputs per element as requested: 
+	this->inputs=new Inputs();
+	this->inputs->AddInput(new IntInput(FillEnum,icefront_fill));
+	this->inputs->AddInput(new IntInput(TypeEnum,in_icefront_type));
+	
+	//parameters and hooked fields: we still can't point to them, they may not even exist. Configure will handle this.
+	this->parameters=NULL;
+	this->nodes= NULL;
+	this->element= NULL;
+	this->matpar= NULL;
+}
+
+
+/*}}}*/
+/*FUNCTION Icefront::~Icefront() {{{1*/
+Icefront::~Icefront(){
+	delete inputs;
+	this->parameters=NULL;
+	delete hnodes;
+	delete helement;
+	delete hmatpar;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Icefront::Echo {{{1*/
+void Icefront::Echo(void){
+	printf("Icefront:\n");
+	printf("   id: %i\n",id);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	hnodes->Echo();
+	helement->Echo();
+	hmatpar->Echo();
+	printf("   parameters: %p\n",parameters);
+	if(parameters)parameters->Echo();
+	printf("   inputs: %p\n",inputs);
+	if(inputs)inputs->Echo();
+}
+/*}}}*/
+/*FUNCTION Icefront::DeepEcho{{{1*/
+void Icefront::DeepEcho(void){
+
+	printf("Icefront:\n");
+	printf("   id: %i\n",id);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	hnodes->DeepEcho();
+	helement->DeepEcho();
+	hmatpar->DeepEcho();
+	printf("   parameters: %p\n",parameters);
+	if(parameters)parameters->DeepEcho();
+	printf("   inputs: %p\n",inputs);
+	if(inputs)inputs->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION Icefront::Id {{{1*/
+int    Icefront::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Icefront::MyRank {{{1*/
+int    Icefront::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION Icefront::Marshall {{{1*/
+void  Icefront::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+	char* marshalled_inputs=NULL;
+	int   marshalled_inputs_size;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of Icefront: */
+	enum_type=IcefrontEnum;
+
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+
+	/*marshall Icefront data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&analysis_type,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+
+	/*Marshall hooks: */
+	hnodes->Marshall(&marshalled_dataset);
+	helement->Marshall(&marshalled_dataset);
+	hmatpar->Marshall(&marshalled_dataset);
+
+	/*Marshall inputs: */
+	marshalled_inputs_size=inputs->MarshallSize();
+	marshalled_inputs=inputs->Marshall();
+	memcpy(marshalled_dataset,marshalled_inputs,marshalled_inputs_size*sizeof(char));
+	marshalled_dataset+=marshalled_inputs_size;
+
+	/*parameters: don't do anything about it. parameters are marshalled somewhere else!*/
+
+	xfree((void**)&marshalled_inputs);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION Icefront::MarshallSize {{{1*/
+int   Icefront::MarshallSize(){
+	
+	return sizeof(id)
+		+sizeof(analysis_type)
+		+hnodes->MarshallSize()
+		+helement->MarshallSize()
+		+hmatpar->MarshallSize()
+		+inputs->MarshallSize()
+		+sizeof(int); //sizeof(int) for enum type
+}
+/*}}}*/
+/*FUNCTION Icefront::Demarshall {{{1*/
+void  Icefront::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&analysis_type,marshalled_dataset,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+
+	/*demarshall hooks: */
+	hnodes=new Hook(); hnodes->Demarshall(&marshalled_dataset);
+	helement=new Hook(); helement->Demarshall(&marshalled_dataset);
+	hmatpar=new Hook(); hmatpar->Demarshall(&marshalled_dataset);
+	
+	/*pointers are garbabe, until configuration is carried out: */
+	nodes=NULL;
+	element=NULL;
+	matpar=NULL;
+
+	/*demarshall inputs: */
+	inputs=(Inputs*)DataSetDemarshallRaw(&marshalled_dataset); 
+
+	/*parameters: may not exist even yet, so let Configure handle it: */
+	this->parameters=NULL;
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION Icefront::ObjectEnum{{{1*/
+int Icefront::ObjectEnum(void){
+
+	return IcefrontEnum;
+
+}
+/*}}}*/
+/*FUNCTION Icefront::copy {{{1*/
+Object* Icefront::copy() {
+	
+	Icefront* icefront=NULL;
+
+	icefront=new Icefront();
+
+	/*copy fields: */
+	icefront->id=this->id;
+	icefront->analysis_type=this->analysis_type;
+	if(this->inputs){
+		icefront->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		icefront->inputs=new Inputs();
+	}
+	/*point parameters: */
+	icefront->parameters=this->parameters;
+
+	/*now deal with hooks and objects: */
+	icefront->hnodes=(Hook*)this->hnodes->copy();
+	icefront->helement=(Hook*)this->helement->copy();
+	icefront->hmatpar=(Hook*)this->hmatpar->copy();
+
+	/*corresponding fields*/
+	icefront->nodes  =(Node**)icefront->hnodes->deliverp();
+	icefront->element=(Element*)icefront->helement->delivers();
+	icefront->matpar =(Matpar*)icefront->hmatpar->delivers();
+
+	return icefront;
+
+}
+/*}}}*/
+
+/*Load virtual functions definitions:*/
+/*FUNCTION Icefront::Configure {{{1*/
+void  Icefront::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	hnodes->configure(nodesin);
+	helement->configure(elementsin);
+	hmatpar->configure(materialsin);
+
+	/*Initialize hooked fields*/
+	this->nodes  =(Node**)hnodes->deliverp();
+	this->element=(Element*)helement->delivers();
+	this->matpar =(Matpar*)hmatpar->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+}
+/*}}}*/
+/*FUNCTION Icefront::SetCurrentConfiguration {{{1*/
+void  Icefront::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+}
+/*}}}*/
+/*FUNCTION Icefront::CreateKMatrix {{{1*/
+void  Icefront::CreateKMatrix(Mat Kff, Mat Kfs){
+
+	/*No stiffness loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Icefront::CreatePVector {{{1*/
+void  Icefront::CreatePVector(Vec pf){
+
+	/*Checks in debugging mode*/
+	/*{{{2*/
+	_assert_(nodes);
+	_assert_(element);
+	_assert_(matpar);
+	/*}}}*/
+
+	/*Retrieve parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Just branch to the correct element icefront vector generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum:
+			pe=CreatePVectorDiagnosticHoriz();
+			break;
+		#endif
+		#ifdef _HAVE_CONTROL_
+		case AdjointHorizAnalysisEnum:
+			pe=CreatePVectorAdjointHoriz();
+			break;
+		#endif
+		default:
+			_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+
+	/*Add to global Vector*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}*/
+/*FUNCTION Icefront::PenaltyCreateKMatrix {{{1*/
+void  Icefront::PenaltyCreateKMatrix(Mat Kff, Mat Kfs, double kmax){
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Icefront::PenaltyCreatePVector{{{1*/
+void  Icefront::PenaltyCreatePVector(Vec pf,double kmax){
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Icefront::InAnalysis{{{1*/
+bool Icefront::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type)return true;
+	else return false;
+}
+/*}}}*/
+
+/*Update virtual functions definitions:*/
+/*FUNCTION Icefront::InputUpdateFromVector(double* vector, int name, int type) {{{1*/
+void  Icefront::InputUpdateFromVector(double* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Icefront::InputUpdateFromVector(int* vector, int name, int type) {{{1*/
+void  Icefront::InputUpdateFromVector(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Icefront::InputUpdateFromVector(bool* vector, int name, int type) {{{1*/
+void  Icefront::InputUpdateFromVector(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Icefront::InputUpdateFromMatrixDakota(double* matrix, int nrows, int ncols, int name, int type) {{{1*/
+void  Icefront::InputUpdateFromMatrixDakota(double* matrix, int nrows, int ncols, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Icefront::InputUpdateFromVectorDakota(double* vector, int name, int type) {{{1*/
+void  Icefront::InputUpdateFromVectorDakota(double* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Icefront::InputUpdateFromVectorDakota(int* vector, int name, int type) {{{1*/
+void  Icefront::InputUpdateFromVectorDakota(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Icefront::InputUpdateFromVectorDakota(bool* vector, int name, int type) {{{1*/
+void  Icefront::InputUpdateFromVectorDakota(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Icefront::InputUpdateFromConstant(double constant, int name) {{{1*/
+void  Icefront::InputUpdateFromConstant(double constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Icefront::InputUpdateFromConstant(int constant, int name) {{{1*/
+void  Icefront::InputUpdateFromConstant(int constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Icefront::InputUpdateFromConstant(bool constant, int name) {{{1*/
+void  Icefront::InputUpdateFromConstant(bool constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Icefront::InputUpdateFromSolution{{{1*/
+void  Icefront::InputUpdateFromSolution(double* solution){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+
+/*Icefront numerics: */
+#ifdef _HAVE_DIAGNOSTIC_
+/*FUNCTION Icefront::CreatePVectorDiagnosticHoriz {{{1*/
+ElementVector* Icefront::CreatePVectorDiagnosticHoriz(void){
+
+	int type;
+	inputs->GetInputValue(&type,TypeEnum);
+
+	switch(type){
+		case MacAyeal2dIceFrontEnum:
+			return CreatePVectorDiagnosticMacAyeal2d();
+        #ifdef _HAVE_THREED_
+		case MacAyeal3dIceFrontEnum:
+			return CreatePVectorDiagnosticMacAyeal3d();
+		case PattynIceFrontEnum:
+			return CreatePVectorDiagnosticPattyn();
+		case StokesIceFrontEnum:
+			return CreatePVectorDiagnosticStokes();
+	    #endif
+		default:
+			_error_("Icefront type %s not supported yet",EnumToStringx(type));
+	}
+}
+/*}}}*/
+/*FUNCTION Icefront::CreatePVectorDiagnosticMacAyeal2d{{{1*/
+ElementVector* Icefront::CreatePVectorDiagnosticMacAyeal2d(void){
+
+	/*Constants*/
+	const int numnodes= NUMVERTICESSEG;
+	const int numdofs = numnodes *NDOF2;
+
+	/*Intermediary*/
+	int        ig,index1,index2,fill;
+	double     Jdet;
+	double     thickness,bed,pressure,ice_pressure,rho_water,rho_ice,gravity;
+	double     water_pressure,air_pressure,surface_under_water,base_under_water;
+	double     xyz_list[numnodes][3];
+	double     normal[2];
+	double     L[2];
+	GaussTria *gauss;
+
+	Tria* tria=((Tria*)element);
+
+	/*Initialize Element vector and return if necessary*/
+	if(tria->IsOnWater()) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICESSEG,this->parameters,MacAyealApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],nodes,numnodes);
+	Input* thickness_input=tria->inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* bed_input      =tria->inputs->GetInput(BedEnum);       _assert_(bed_input);
+	inputs->GetInputValue(&fill,FillEnum);
+	rho_water=matpar->GetRhoWater();
+	rho_ice  =matpar->GetRhoIce();
+	gravity  =matpar->GetG();
+	GetSegmentNormal(&normal[0],xyz_list);
+
+	/*Start looping on Gaussian points*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+	gauss=new GaussTria(index1,index2,3);
+
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		bed_input->GetInputValue(&bed,gauss);
+
+		switch(fill){
+			case WaterEnum:
+				surface_under_water=min(0.,thickness+bed); // 0 if the top of the glacier is above water level
+				base_under_water=min(0.,bed);              // 0 if the bottom of the glacier is above water level
+				water_pressure=1.0/2.0*gravity*rho_water*(pow(surface_under_water,2) - pow(base_under_water,2));
+				break;
+			case AirEnum:
+				water_pressure=0;
+				break;
+			case IceEnum:
+				water_pressure=-1.0/2.0*gravity*rho_ice*pow(thickness,2); // we are facing a wall of ice. use water_pressure to cancel the lithostatic pressure.
+				break;
+			default:
+				_error_("fill type %s not supported yet",EnumToStringx(fill));
+		}
+		ice_pressure=1.0/2.0*gravity*rho_ice*pow(thickness,2);
+		air_pressure=0;
+		pressure = ice_pressure + water_pressure + air_pressure;
+
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2);
+
+		for (int i=0;i<numnodes;i++){
+			pe->values[2*i+0]+= pressure*Jdet*gauss->weight*normal[0]*L[i];
+			pe->values[2*i+1]+= pressure*Jdet*gauss->weight*normal[1]*L[i];
+		}
+	}
+
+	/*Transform load vector*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICESSEG,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_CONTROL_
+/*FUNCTION Icefront::CreatePVectorAdjointHoriz {{{1*/
+ElementVector* Icefront::CreatePVectorAdjointHoriz(void){
+
+	/*No load vector applied to the adjoint*/
+	return NULL;
+}
+/*}}}*/
+#endif
+#ifdef _HAVE_THREED_
+/*FUNCTION Icefront::CreatePVectorDiagnosticMacAyeal3d{{{1*/
+ElementVector* Icefront::CreatePVectorDiagnosticMacAyeal3d(void){
+
+	Icefront* icefront=NULL;
+	Penta*    penta=NULL;
+	Tria*     tria=NULL;
+	bool      onbed;
+
+	/*Cast element onto Penta*/
+	penta   =(Penta*)this->element;
+
+	/*Return if not on bed*/
+	if(!penta->IsOnBed() || penta->IsOnWater()) return NULL;
+
+	/*Spawn Tria and call MacAyeal2d*/
+	tria    =(Tria*)penta->SpawnTria(0,1,2);
+	icefront=(Icefront*)this->copy();
+	icefront->element=tria;
+	icefront->inputs->AddInput(new IntInput(TypeEnum,MacAyeal2dIceFrontEnum));
+	ElementVector* pe=icefront->CreatePVectorDiagnosticMacAyeal2d();
+
+	/*clean-up and return*/
+	delete tria->matice;
+	delete tria;
+	delete icefront;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Icefront::CreatePVectorDiagnosticPattyn{{{1*/
+ElementVector* Icefront::CreatePVectorDiagnosticPattyn(void){
+
+	/*Constants*/
+	const int numdofs = NUMVERTICESQUA *NDOF2;
+
+	/*Intermediaries*/
+	int         i,j,ig,index1,index2,index3,index4;
+	int         fill;
+	double      surface,pressure,ice_pressure,rho_water,rho_ice,gravity;
+	double      water_pressure,air_pressure;
+	double      Jdet,z_g;
+	double      xyz_list[NUMVERTICESQUA][3];
+	double      normal[3];
+	double      l1l4[4];
+	GaussPenta *gauss = NULL;
+
+	Penta* penta=(Penta*)element;
+
+	/*Initialize Element vector and return if necessary*/
+	if(penta->IsOnWater()) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICESQUA,this->parameters,PattynApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICESQUA);
+	Input* surface_input  =penta->inputs->GetInput(SurfaceEnum);   _assert_(surface_input);
+	inputs->GetInputValue(&fill,FillEnum);
+	rho_water=matpar->GetRhoWater();
+	rho_ice  =matpar->GetRhoIce();
+	gravity  =matpar->GetG();
+	GetQuadNormal(&normal[0],xyz_list);
+
+	/*Identify which nodes are in the quad: */
+	index1=element->GetNodeIndex(nodes[0]);
+	index2=element->GetNodeIndex(nodes[1]);
+	index3=element->GetNodeIndex(nodes[2]);
+	index4=element->GetNodeIndex(nodes[3]);
+
+	/* Start  looping on the number of gaussian points: */
+	double zmax=xyz_list[0][2]; for(i=1;i<NUMVERTICESQUA;i++) if(xyz_list[i][2]>zmax) zmax=xyz_list[i][2];
+	double zmin=xyz_list[0][2]; for(i=1;i<NUMVERTICESQUA;i++) if(xyz_list[i][2]<zmin) zmin=xyz_list[i][2];
+	if(zmax>0 && zmin<0) gauss=new GaussPenta(index1,index2,index3,index4,3,10); //refined in vertical because of the sea level discontinuity
+	else                 gauss=new GaussPenta(index1,index2,index3,index4,3,3);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		penta->GetQuadNodalFunctions(l1l4,gauss,index1,index2,index3,index4);
+		penta->GetQuadJacobianDeterminant(&Jdet,xyz_list,gauss);
+		z_g=penta->GetZcoord(gauss);
+		surface_input->GetInputValue(&surface,gauss);
+
+		switch(fill){
+			case WaterEnum:
+				water_pressure=rho_water*gravity*min(0.,z_g);//0 if the gaussian point is above water level
+				break;
+			case AirEnum:
+				water_pressure=0;
+				break;
+			default:
+				_error_("fill type %s not supported yet",EnumToStringx(fill));
+		}
+		ice_pressure=rho_ice*gravity*(surface-z_g);
+		air_pressure=0;
+		pressure = ice_pressure + water_pressure + air_pressure;
+
+		for(i=0;i<NUMVERTICESQUA;i++) for(j=0;j<NDOF2;j++) pe->values[i*NDOF2+j]+=Jdet*gauss->weight*pressure*l1l4[i]*normal[j];
+	}
+
+	/*Transform load vector*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICESQUA,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Icefront::CreatePVectorDiagnosticStokes{{{1*/
+ElementVector* Icefront::CreatePVectorDiagnosticStokes(void){
+
+	/*Constants*/
+	const int numdofs = NUMVERTICESQUA *NDOF4;
+
+	/*Intermediaries*/
+	int         i,j,ig,index1,index2,index3,index4;
+	int         fill;
+	double      pressure,rho_water,gravity;
+	double      water_pressure,air_pressure;
+	double      Jdet,z_g;
+	double      xyz_list[NUMVERTICESQUA][3];
+	double      normal[3];
+	double      l1l4[4];
+	GaussPenta *gauss = NULL;
+
+	Penta* penta=(Penta*)element;
+
+	/*Initialize Element vector and return if necessary*/
+	if(penta->IsOnWater()) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICESQUA,this->parameters,StokesApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICESQUA);
+	inputs->GetInputValue(&fill,FillEnum);
+	rho_water=matpar->GetRhoWater();
+	gravity  =matpar->GetG();
+	GetQuadNormal(&normal[0],xyz_list);
+
+	/*Identify which nodes are in the quad: */
+	index1=element->GetNodeIndex(nodes[0]);
+	index2=element->GetNodeIndex(nodes[1]);
+	index3=element->GetNodeIndex(nodes[2]);
+	index4=element->GetNodeIndex(nodes[3]);
+
+	/* Start  looping on the number of gaussian points: */
+	double zmax=xyz_list[0][2]; for(i=1;i<NUMVERTICESQUA;i++) if(xyz_list[i][2]>zmax) zmax=xyz_list[i][2];
+	double zmin=xyz_list[0][2]; for(i=1;i<NUMVERTICESQUA;i++) if(xyz_list[i][2]<zmin) zmin=xyz_list[i][2];
+	if(zmax>0 && zmin<0) gauss=new GaussPenta(index1,index2,index3,index4,3,30); //refined in vertical because of the sea level discontinuity
+	else                 gauss=new GaussPenta(index1,index2,index3,index4,3,3);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		penta->GetQuadNodalFunctions(l1l4,gauss,index1,index2,index3,index4);
+		penta->GetQuadJacobianDeterminant(&Jdet,xyz_list,gauss);
+		z_g=penta->GetZcoord(gauss);
+
+		switch(fill){
+			case WaterEnum:
+				water_pressure=rho_water*gravity*min(0.,z_g);//0 if the gaussian point is above water level
+				break;
+			case AirEnum:
+				water_pressure=0;
+				break;
+			default:
+				_error_("fill type %s not supported yet",EnumToStringx(fill));
+		}
+		air_pressure=0;
+		pressure = water_pressure + air_pressure; //no ice pressure fore Stokes
+
+		for(i=0;i<NUMVERTICESQUA;i++){
+			for(j=0;j<NDOF4;j++){
+				if(j<3)  pe->values[i*NDOF4+j]+=Jdet*gauss->weight*pressure*l1l4[i]*normal[j];
+				else     pe->values[i*NDOF4+j]+=0; //pressure term
+			}
+		}
+	}
+
+	/*Transform load vector*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICESQUA,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+#endif
+/*FUNCTION Icefront::GetDofList {{{1*/
+void  Icefront::GetDofList(int** pdoflist,int approximation_enum,int setenum){
+
+	int i,j;
+	int numberofdofs=0;
+	int count=0;
+	int type;
+	int numberofnodes=2;
+
+	/*output: */
+	int* doflist=NULL;
+
+	
+	/*recover type: */
+	inputs->GetInputValue(&type,TypeEnum);
+
+	/*Some checks for debugging*/
+	_assert_(nodes);
+		
+	/*How many nodes? :*/
+	if(type==MacAyeal2dIceFrontEnum || type==MacAyeal3dIceFrontEnum)
+	 numberofnodes=2;
+	else 
+	 numberofnodes=4;
+	
+	/*Figure out size of doflist: */
+	for(i=0;i<numberofnodes;i++){
+		numberofdofs+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
+	}
+
+	/*Allocate: */
+	doflist=(int*)xmalloc(numberofdofs*sizeof(int));
+
+	/*Populate: */
+	count=0;
+	for(i=0;i<numberofnodes;i++){
+		nodes[i]->GetDofList(doflist+count,approximation_enum,setenum);
+		count+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
+	}
+
+	/*Assign output pointers:*/
+	*pdoflist=doflist;
+}
+/*}}}*/
+/*FUNCTION Icefront::GetSegmentNormal {{{1*/
+void Icefront:: GetSegmentNormal(double* normal,double xyz_list[4][3]){
+
+	/*Build unit outward pointing vector*/
+	const int numnodes=NUMVERTICESSEG;
+	double vector[2];
+	double norm;
+
+	vector[0]=xyz_list[1][0] - xyz_list[0][0];
+	vector[1]=xyz_list[1][1] - xyz_list[0][1];
+
+	norm=sqrt(pow(vector[0],2.0)+pow(vector[1],2.0));
+
+	normal[0]= + vector[1]/norm;
+	normal[1]= - vector[0]/norm;
+}
+/*}}}*/
+/*FUNCTION Icefront::GetQuadNormal {{{1*/
+void Icefront:: GetQuadNormal(double* normal,double xyz_list[4][3]){
+
+	/*Build unit outward pointing vector*/
+	double AB[3];
+	double AC[3];
+	double norm;
+
+	AB[0]=xyz_list[1][0] - xyz_list[0][0];
+	AB[1]=xyz_list[1][1] - xyz_list[0][1];
+	AB[2]=xyz_list[1][2] - xyz_list[0][2];
+	AC[0]=xyz_list[2][0] - xyz_list[0][0];
+	AC[1]=xyz_list[2][1] - xyz_list[0][1];
+	AC[2]=xyz_list[2][2] - xyz_list[0][2];
+
+	cross(normal,AB,AC);
+	norm=sqrt(pow(normal[0],2.0)+pow(normal[1],2.0)+pow(normal[2],2.0));
+
+	for(int i=0;i<3;i++) normal[i]=normal[i]/norm;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Loads/Icefront.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Loads/Icefront.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Loads/Icefront.h	(revision 11330)
@@ -0,0 +1,101 @@
+/*!\file Icefront.h
+ * \brief: header file for icefront object
+ */
+
+#ifndef _ICEFRONT_H_
+#define _ICEFRONT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Load.h"
+class Hook;
+class Inputs;
+class Parameters;
+class Matpar;
+class Node;
+class Element;
+class IoModel;
+class ElementVector;
+/*}}}*/
+
+class Icefront: public Load {
+
+	public:
+		int id;
+		int analysis_type;
+
+		/*hooks: */
+		Hook* hnodes;
+		Hook* helement;
+		Hook* hmatpar;
+
+		/*Corresponding fields*/
+		Matpar   *matpar;
+		Node    **nodes;
+		Element  *element;
+
+		/*inputs and parameters: */
+		Inputs* inputs;
+		Parameters* parameters;
+
+		/*Icefront constructors, destructors: {{{1*/
+		Icefront();
+		Icefront(int icefront_id,int i, IoModel* iomodel,int in_icefront_type, int analysis_type);
+		~Icefront();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Update virtual functions definitions: {{{1*/
+		void  InputUpdateFromVector(double* vector, int name, int type);
+		void  InputUpdateFromVector(int* vector, int name, int type);
+		void  InputUpdateFromVector(bool* vector, int name, int type);
+		void  InputUpdateFromMatrixDakota(double* matrix,int ncols,int nrows, int name, int type);
+		void  InputUpdateFromVectorDakota(double* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
+		void  InputUpdateFromConstant(double constant, int name);
+		void  InputUpdateFromConstant(int constant, int name);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromSolution(double* solution);
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+		/*Load virtual functions definitions: {{{1*/
+		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(Mat Kff, Mat Kfs);
+		void  CreatePVector(Vec pf);
+		void  PenaltyCreateKMatrix(Mat Kff, Mat kfs, double kmax);
+		void  PenaltyCreatePVector(Vec pf, double kmax);
+		bool  InAnalysis(int analysis_type);
+		/*}}}*/
+		/*Load management: {{{1*/
+		void GetDofList(int** pdoflist,int approximation_enum,int setenum);
+		void GetSegmentNormal(double* normal,double xyz_list[2][3]);
+		void GetQuadNormal(double* normal,double xyz_list[4][3]);
+		#ifdef _HAVE_CONTROL_
+		ElementVector* CreatePVectorAdjointHoriz(void);
+		#endif
+		#ifdef _HAVE_DIAGNOSTIC_
+		ElementVector* CreatePVectorDiagnosticHoriz(void);
+		ElementVector* CreatePVectorDiagnosticMacAyeal2d(void);
+		#endif
+        #ifdef _HAVE_THREED_
+		ElementVector* CreatePVectorDiagnosticMacAyeal3d(void);
+		ElementVector* CreatePVectorDiagnosticPattyn(void);
+		ElementVector* CreatePVectorDiagnosticStokes(void);
+	    #endif
+		/*}}}*/
+};
+
+#endif  /* _ICEFRONT_H_ */
Index: /issm/trunk-jpl-damage/src/c/objects/Loads/Load.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Loads/Load.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Loads/Load.h	(revision 11330)
@@ -0,0 +1,36 @@
+/*!\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:*/
+/*{{{1*/
+class Object;
+
+#include "../Object.h"
+#include "../../toolkits/toolkits.h"
+#include "../../Container/Container.h"
+/*}}}*/
+
+class Load: public Object,public Update{
+
+	public: 
+
+		virtual       ~Load(){};
+		
+		/*Virtual functions: {{{1*/
+		virtual void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
+		virtual void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
+		virtual void  CreateKMatrix(Mat Kff, Mat Kfs)=0;
+		virtual void  CreatePVector(Vec pf)=0;
+		virtual void  PenaltyCreateKMatrix(Mat Kff, Mat Kfs, double kmax)=0;
+		virtual void  PenaltyCreatePVector(Vec pf, double kmax)=0;
+		virtual bool  InAnalysis(int analysis_type)=0;
+		/*}}}*/
+};
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Loads/Numericalflux.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Loads/Numericalflux.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Loads/Numericalflux.cpp	(revision 11330)
@@ -0,0 +1,963 @@
+/*!\file Numericalflux.c
+ * \brief: implementation of the Numericalflux object
+ */
+
+/*Headers:*/
+/*{{{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 "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../objects.h"
+/*}}}*/	
+
+/*Load macros*/
+#define NUMVERTICES_INTERNAL 4
+#define NUMVERTICES_BOUNDARY 2
+
+/*Numericalflux constructors and destructor*/
+/*FUNCTION Numericalflux::Numericalflux(){{{1*/
+Numericalflux::Numericalflux(){
+	this->inputs=NULL;
+	this->parameters=NULL;
+	this->helement=NULL;
+	this->element=NULL;
+	this->hnodes=NULL;
+	this->nodes=NULL;
+}
+/*}}}*/
+/*}}}*//*FUNCTION Numericalflux::Numericalflux(int id, int i, IoModel* iomodel, int analysis_type) {{{1*/
+Numericalflux::Numericalflux(int numericalflux_id,int i, IoModel* iomodel, int in_analysis_type){
+
+	/* Intermediary */
+	int  e1,e2;
+	int  i1,i2;
+	int  j;
+	int  pos1,pos2,pos3,pos4;
+	int  num_nodes;
+	int  num_elems;
+
+	/*numericalflux constructor data: */
+	int   numericalflux_elem_ids[2];
+	int   numericalflux_mparid;
+	int   numericalflux_node_ids[4];
+	int   numericalflux_type;
+
+	int    numberofelements;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+
+	/* Get MatPar id */
+	numericalflux_mparid=numberofelements+1; //matlab indexing
+
+	/*First, see wether this is an internal or boundary edge (if e2=NaN)*/
+	if (isnan((double)iomodel->Data(MeshEdgesEnum)[4*i+3])){ //edges are [node1 node2 elem1 elem2]
+		/* Boundary edge, only one element */
+		e1=(int)iomodel->Data(MeshEdgesEnum)[4*i+2];
+		e2=(int)UNDEF;
+		num_elems=1;
+		num_nodes=2;
+		numericalflux_type=BoundaryEnum;
+		numericalflux_elem_ids[0]=(int)e1;
+	}
+	else{
+		/* internal edge: connected to 2 elements */
+		e1=(int)iomodel->Data(MeshEdgesEnum)[4*i+2];
+		e2=(int)iomodel->Data(MeshEdgesEnum)[4*i+3];
+		num_elems=2;
+		num_nodes=4;
+		numericalflux_type=InternalEnum;
+		numericalflux_elem_ids[0]=(int)e1;
+		numericalflux_elem_ids[1]=(int)e2;
+	}
+
+	/*1: Get vertices ids*/
+	i1=(int)iomodel->Data(MeshEdgesEnum)[4*i+0];
+	i2=(int)iomodel->Data(MeshEdgesEnum)[4*i+1];
+
+	if (numericalflux_type==InternalEnum){
+
+		/*Now, we must get the nodes of the 4 nodes located on the edge*/
+
+		/*2: Get the column where these ids are located in the index*/
+		pos1=pos2=pos3=pos4=UNDEF;
+		for(j=0;j<3;j++){
+			if (iomodel->Data(MeshElementsEnum)[3*(e1-1)+j]==i1) pos1=j+1;
+			if (iomodel->Data(MeshElementsEnum)[3*(e1-1)+j]==i2) pos2=j+1;
+			if (iomodel->Data(MeshElementsEnum)[3*(e2-1)+j]==i1) pos3=j+1;
+			if (iomodel->Data(MeshElementsEnum)[3*(e2-1)+j]==i2) pos4=j+1;
+		}
+		_assert_(pos1!=UNDEF && pos2!=UNDEF && pos3!=UNDEF && pos4!=UNDEF);
+
+		/*3: We have the id of the elements and the position of the vertices in the index
+		 * we can compute their dofs!*/
+		numericalflux_node_ids[0]=iomodel->nodecounter+3*(e1-1)+pos1;
+		numericalflux_node_ids[1]=iomodel->nodecounter+3*(e1-1)+pos2;
+		numericalflux_node_ids[2]=iomodel->nodecounter+3*(e2-1)+pos3;
+		numericalflux_node_ids[3]=iomodel->nodecounter+3*(e2-1)+pos4;
+	}
+	else{
+
+		/*2: Get the column where these ids are located in the index*/
+		pos1=pos2=UNDEF;
+		for(j=0;j<3;j++){
+			if (iomodel->Data(MeshElementsEnum)[3*(e1-1)+j]==i1) pos1=j+1;
+			if (iomodel->Data(MeshElementsEnum)[3*(e1-1)+j]==i2) pos2=j+1;
+		}
+		_assert_(pos1!=UNDEF && pos2!=UNDEF);
+
+		/*3: We have the id of the elements and the position of the vertices in the index
+		 * we can compute their dofs!*/
+		numericalflux_node_ids[0]=iomodel->nodecounter+3*(e1-1)+pos1;
+		numericalflux_node_ids[1]=iomodel->nodecounter+3*(e1-1)+pos2;
+	}
+
+	/*Ok, we have everything to build the object: */
+	this->id=numericalflux_id;
+	this->analysis_type=in_analysis_type;
+
+	/*Hooks: */
+	this->hnodes  =new Hook(numericalflux_node_ids,num_nodes);
+	this->helement=new Hook(numericalflux_elem_ids,1); // take only the first element for now
+
+	//intialize  and add as many inputs per element as requested: 
+	this->inputs=new Inputs();
+	this->inputs->AddInput(new IntInput(TypeEnum,numericalflux_type));
+
+	//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+	this->parameters=NULL;
+	this->element=NULL;
+	this->nodes=NULL;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::~Numericalflux(){{{1*/
+Numericalflux::~Numericalflux(){
+	delete inputs;
+	this->parameters=NULL;
+	delete helement;
+	delete hnodes;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Numericalflux::Echo {{{1*/
+void Numericalflux::Echo(void){
+	printf("Numericalflux:\n");
+	printf("   id: %i\n",id);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	hnodes->Echo();
+	helement->Echo();
+	printf("   parameters: %p\n",parameters);
+	printf("   inputs: %p\n",inputs);
+}
+/*}}}*/
+/*FUNCTION Numericalflux::DeepEcho {{{1*/
+void Numericalflux::DeepEcho(void){
+
+	printf("Numericalflux:\n");
+	printf("   id: %i\n",id);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	hnodes->DeepEcho();
+	helement->DeepEcho();
+	printf("   parameters\n");
+	if(parameters)
+	 parameters->DeepEcho();
+	else
+	 printf("      NULL\n");
+	printf("   inputs\n");
+	inputs->DeepEcho();
+	
+}		
+/*}}}*/
+/*FUNCTION Numericalflux::Id {{{1*/
+int    Numericalflux::Id(void){
+	return id;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::MyRank {{{1*/
+int    Numericalflux::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION Numericalflux::Marshall {{{1*/
+void  Numericalflux::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+	char* marshalled_inputs=NULL;
+	int   marshalled_inputs_size;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of Numericalflux: */
+	enum_type=NumericalfluxEnum;
+
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+
+	/*marshall Numericalflux data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&analysis_type,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+
+	/*Marshall hooks: */
+	hnodes->Marshall(&marshalled_dataset);
+	helement->Marshall(&marshalled_dataset);
+
+	/*Marshall inputs: */
+	marshalled_inputs_size=inputs->MarshallSize();
+	marshalled_inputs=inputs->Marshall();
+	memcpy(marshalled_dataset,marshalled_inputs,marshalled_inputs_size*sizeof(char));
+	marshalled_dataset+=marshalled_inputs_size;
+
+	/*parameters: don't do anything about it. parameters are marshalled somewhere else!*/
+
+	xfree((void**)&marshalled_inputs);
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::MarshallSize{{{1*/
+int   Numericalflux::MarshallSize(){
+
+	return sizeof(id)
+		+sizeof(analysis_type)
+		+hnodes->MarshallSize()
+		+helement->MarshallSize()
+		+inputs->MarshallSize()
+		+sizeof(int); //sizeof(int) for enum type
+}
+/*}}}*/
+/*FUNCTION Numericalflux::Demarshall {{{1*/
+void  Numericalflux::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&analysis_type,marshalled_dataset,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+
+	/*demarshall hooks: */
+	hnodes=new Hook(); hnodes->Demarshall(&marshalled_dataset);
+	helement=new Hook(); helement->Demarshall(&marshalled_dataset);
+	
+	/*demarshall inputs: */
+	inputs=(Inputs*)DataSetDemarshallRaw(&marshalled_dataset); 
+
+	/*parameters: may not exist even yet, so let Configure handle it: */
+	this->parameters=NULL;
+	this->element=NULL;
+	this->nodes=NULL;
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION Numericalflux::ObjectEnum{{{1*/
+int Numericalflux::ObjectEnum(void){
+
+	return NumericalfluxEnum;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::copy {{{1*/
+Object* Numericalflux::copy() {
+	
+	Numericalflux* numericalflux=NULL;
+
+	numericalflux=new Numericalflux();
+
+	/*copy fields: */
+	numericalflux->id=this->id;
+	numericalflux->analysis_type=this->analysis_type;
+	if(this->inputs){
+		numericalflux->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		numericalflux->inputs=new Inputs();
+	}
+	/*point parameters: */
+	numericalflux->parameters=this->parameters;
+
+	/*now deal with hooks and objects: */
+	numericalflux->hnodes=(Hook*)this->hnodes->copy();
+	numericalflux->helement=(Hook*)this->helement->copy();
+
+	/*corresponding fields*/
+	numericalflux->nodes  =(Node**)numericalflux->hnodes->deliverp();
+	numericalflux->element=(Element*)numericalflux->helement->delivers();
+
+	return numericalflux;
+}
+/*}}}*/
+
+/*Load virtual functions definitions:*/
+/*FUNCTION Numericalflux::Configure {{{1*/
+void  Numericalflux::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	hnodes->configure(nodesin);
+	helement->configure(elementsin);
+
+	/*Initialize hooked fields*/
+	this->nodes  =(Node**)hnodes->deliverp();
+	this->element=(Element*)helement->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::SetCurrentConfiguration {{{1*/
+void  Numericalflux::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrix {{{1*/
+void  Numericalflux::CreateKMatrix(Mat Kff, Mat Kfs){
+
+	/*recover some parameters*/
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+		case PrognosticAnalysisEnum:
+			Ke=CreateKMatrixPrognostic();
+			break;
+		case BalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixBalancethickness();
+			break;
+		case AdjointBalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixAdjointBalancethickness();
+			break;
+		default:
+			_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVector {{{1*/
+void  Numericalflux::CreatePVector(Vec pf){
+
+	/*recover some parameters*/
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case PrognosticAnalysisEnum:
+			pe=CreatePVectorPrognostic();
+			break;
+		case BalancethicknessAnalysisEnum:
+			pe=CreatePVectorBalancethickness();
+			break;
+		case AdjointBalancethicknessAnalysisEnum:
+			pe=CreatePVectorAdjointBalancethickness();
+			break;
+		default:
+			_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+
+	/*Add to global matrix*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::PenaltyCreateKMatrix {{{1*/
+void  Numericalflux::PenaltyCreateKMatrix(Mat Kff, Mat Kfs,double kmax){
+
+	/*No stiffness loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::PenaltyCreatePVector{{{1*/
+void  Numericalflux::PenaltyCreatePVector(Vec pf,double kmax){
+
+	/*No penalty loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::InAnalysis{{{1*/
+bool Numericalflux::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+
+/*Numericalflux management*/
+/*FUNCTION Numericalflux::CreateKMatrixPrognostic{{{1*/
+ElementMatrix* Numericalflux::CreateKMatrixPrognostic(void){
+
+	int type;
+	inputs->GetInputValue(&type,TypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreateKMatrixPrognosticInternal();
+		case BoundaryEnum:
+			return CreateKMatrixPrognosticBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixPrognosticInternal {{{1*/
+ElementMatrix* Numericalflux::CreateKMatrixPrognosticInternal(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMVERTICES_INTERNAL;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	double     DL1,DL2,Jdet,dt,vx,vy,UdotN;
+	double     xyz_list[NUMVERTICES_INTERNAL][3];
+	double     normal[2];
+	double     B[numdof];
+	double     Bprime[numdof];
+	double     Ke_g1[numdof][numdof];
+	double     Ke_g2[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	Tria*  tria=(Tria*)element;
+	if(tria->IsOnWater()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES_INTERNAL,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes,NUMVERTICES_INTERNAL);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum);
+	GetNormal(&normal[0],xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentBFlux(&B[0],gauss,index1,index2);
+		tria->GetSegmentBprimeFlux(&Bprime[0],gauss,index1,index2);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL1=gauss->weight*Jdet*dt*UdotN/2;
+		DL2=gauss->weight*Jdet*dt*fabs(UdotN)/2;
+
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL1,1,1,0,
+					&Bprime[0],1,numdof,0,
+					&Ke_g1[0][0],0);
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL2,1,1,0,
+					&B[0],1,numdof,0,
+					&Ke_g2[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g1[i][j];
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g2[i][j];
+	}
+	
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixPrognosticBoundary {{{1*/
+ElementMatrix* Numericalflux::CreateKMatrixPrognosticBoundary(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMVERTICES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	double     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN;
+	double     xyz_list[NUMVERTICES_BOUNDARY][3];
+	double     normal[2];
+	double     L[numdof];
+	double     Ke_g[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	ElementMatrix* Ke = NULL;
+	Tria*  tria=(Tria*)element;
+	if(tria->IsOnWater()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],nodes,NUMVERTICES_BOUNDARY);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum); _assert_(vxaverage_input);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum); _assert_(vyaverage_input);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN<=0){
+		return NULL; /*(u,n)<0 -> inflow, PenaltyCreatePVector will take care of it*/
+	}
+	else{
+		Ke=new ElementMatrix(nodes,NUMVERTICES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL=gauss->weight*Jdet*dt*UdotN;
+
+		TripleMultiply(&L[0],1,numdof,1,
+					&DL,1,1,0,
+					&L[0],1,numdof,0,
+					&Ke_g[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g[i][j];
+	} 
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixBalancethickness{{{1*/
+ElementMatrix* Numericalflux::CreateKMatrixBalancethickness(void){
+
+	int type;
+	inputs->GetInputValue(&type,TypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreateKMatrixBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreateKMatrixBalancethicknessBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixBalancethicknessInternal {{{1*/
+ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessInternal(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMVERTICES_INTERNAL;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	double     DL1,DL2,Jdet,vx,vy,UdotN;
+	double     xyz_list[NUMVERTICES_INTERNAL][3];
+	double     normal[2];
+	double     B[numdof];
+	double     Bprime[numdof];
+	double     Ke_g1[numdof][numdof];
+	double     Ke_g2[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	Tria*  tria=(Tria*)element;
+	if(tria->IsOnWater()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES_INTERNAL,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes,NUMVERTICES_INTERNAL);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum);
+	GetNormal(&normal[0],xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentBFlux(&B[0],gauss,index1,index2);
+		tria->GetSegmentBprimeFlux(&Bprime[0],gauss,index1,index2);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL1=gauss->weight*Jdet*UdotN/2;
+		DL2=gauss->weight*Jdet*fabs(UdotN)/2;
+
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL1,1,1,0,
+					&Bprime[0],1,numdof,0,
+					&Ke_g1[0][0],0);
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL2,1,1,0,
+					&B[0],1,numdof,0,
+					&Ke_g2[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g1[i][j];
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g2[i][j];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixBalancethicknessBoundary {{{1*/
+ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessBoundary(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMVERTICES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	double     DL,Jdet,vx,vy,mean_vx,mean_vy,UdotN;
+	double     xyz_list[NUMVERTICES_BOUNDARY][3];
+	double     normal[2];
+	double     L[numdof];
+	double     Ke_g[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	ElementMatrix* Ke = NULL;
+	Tria*  tria=(Tria*)element;
+	if(tria->IsOnWater()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],nodes,NUMVERTICES_BOUNDARY);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN<=0){
+		return NULL; /*(u,n)<0 -> inflow, PenaltyCreatePVector will take care of it*/
+	}
+	else{
+		Ke=new ElementMatrix(nodes,NUMVERTICES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL=gauss->weight*Jdet*UdotN;
+
+		TripleMultiply(&L[0],1,numdof,1,
+					&DL,1,1,0,
+					&L[0],1,numdof,0,
+					&Ke_g[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g[i][j];
+	} 
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixAdjointBalancethickness{{{1*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethickness(void){
+
+	int type;
+	inputs->GetInputValue(&type,TypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreateKMatrixAdjointBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreateKMatrixAdjointBalancethicknessBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixAdjointBalancethicknessInternal {{{1*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessInternal(void){
+
+	ElementMatrix* Ke=CreateKMatrixBalancethicknessInternal();
+	if (Ke) Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixAdjointBalancethicknessBoundary {{{1*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessBoundary(void){
+
+	ElementMatrix* Ke=CreateKMatrixBalancethicknessBoundary();
+	if(Ke) Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorPrognostic{{{1*/
+ElementVector* Numericalflux::CreatePVectorPrognostic(void){
+
+	int type;
+	inputs->GetInputValue(&type,TypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreatePVectorPrognosticInternal();
+		case BoundaryEnum:
+			return CreatePVectorPrognosticBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorPrognosticInternal{{{1*/
+ElementVector* Numericalflux::CreatePVectorPrognosticInternal(void){
+
+	/*Nothing added to PVector*/
+	return NULL;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorPrognosticBoundary{{{1*/
+ElementVector* Numericalflux::CreatePVectorPrognosticBoundary(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMVERTICES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	double     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN,thickness;
+	double     xyz_list[NUMVERTICES_BOUNDARY][3];
+	double     normal[2];
+	double     L[numdof];
+	GaussTria *gauss;
+
+	/*Initialize Load Vector and return if necessary*/
+	ElementVector* pe = NULL;
+	Tria*  tria=(Tria*)element;
+	if(tria->IsOnWater()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],nodes,NUMVERTICES_BOUNDARY);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vxaverage_input   =tria->inputs->GetInput(VxEnum);                     _assert_(vxaverage_input); 
+	Input* vyaverage_input   =tria->inputs->GetInput(VyEnum);                     _assert_(vyaverage_input);
+	Input* spcthickness_input=tria->inputs->GetInput(PrognosticSpcthicknessEnum); _assert_(spcthickness_input);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN>0){
+		return NULL; /*(u,n)>0 -> outflow, PenaltyCreateKMatrix will take care of it*/
+	}
+	else{
+		pe=new ElementVector(nodes,NUMVERTICES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		spcthickness_input->GetInputValue(&thickness,gauss);
+		if(isnan(thickness)) _error_("Cannot weakly apply constraint because NaN was provided");
+
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL= - gauss->weight*Jdet*dt*UdotN*thickness;
+
+		for(i=0;i<numdof;i++) pe->values[i] += DL*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorBalancethickness{{{1*/
+ElementVector* Numericalflux::CreatePVectorBalancethickness(void){
+
+	int type;
+	inputs->GetInputValue(&type,TypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreatePVectorBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreatePVectorBalancethicknessBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorBalancethicknessInternal{{{1*/
+ElementVector* Numericalflux::CreatePVectorBalancethicknessInternal(void){
+
+	/*Nothing added to PVector*/
+	return NULL;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorBalancethicknessBoundary{{{1*/
+ElementVector* Numericalflux::CreatePVectorBalancethicknessBoundary(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMVERTICES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	double     DL,Jdet,vx,vy,mean_vx,mean_vy,UdotN,thickness;
+	double     xyz_list[NUMVERTICES_BOUNDARY][3];
+	double     normal[2];
+	double     L[numdof];
+	GaussTria *gauss;
+
+	/*Initialize Load Vector and return if necessary*/
+	ElementVector* pe = NULL;
+	Tria*  tria=(Tria*)element;
+	if(tria->IsOnWater()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],nodes,NUMVERTICES_BOUNDARY);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum); _assert_(vxaverage_input); 
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum); _assert_(vyaverage_input);
+	Input* thickness_input=tria->inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN>0){
+		return NULL; /*(u,n)>0 -> outflow, PenaltyCreateKMatrix will take care of it*/
+	}
+	else{
+		pe=new ElementVector(nodes,NUMVERTICES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		thickness_input->GetInputValue(&thickness,gauss);
+
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL= - gauss->weight*Jdet*UdotN*thickness;
+
+		for(i=0;i<numdof;i++) pe->values[i] += DL*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorAdjointBalancethickness{{{1*/
+ElementVector* Numericalflux::CreatePVectorAdjointBalancethickness(void){
+
+	/*No PVector for the Adjoint*/
+	return NULL;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::GetNormal {{{1*/
+void Numericalflux:: GetNormal(double* normal,double xyz_list[4][3]){
+
+	/*Build unit outward pointing vector*/
+	double vector[2];
+	double norm;
+
+	vector[0]=xyz_list[1][0] - xyz_list[0][0];
+	vector[1]=xyz_list[1][1] - xyz_list[0][1];
+
+	norm=sqrt(pow(vector[0],2.0)+pow(vector[1],2.0));
+
+	normal[0]= + vector[1]/norm;
+	normal[1]= - vector[0]/norm;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Loads/Numericalflux.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Loads/Numericalflux.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Loads/Numericalflux.h	(revision 11330)
@@ -0,0 +1,100 @@
+/*!\file Numericalflux.h
+ * \brief: header file for icefront object
+ */
+
+#ifndef _NUMERICALFLUX_H_
+#define _NUMERICALFLUX_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Load.h"
+class Hook;
+class Parameters;
+class Inputs;
+class IoModel;
+class ElementMatrix;
+class ElementVector;
+/*}}}*/
+
+class Numericalflux: public Load {
+
+	public: 
+		int         id;
+		int analysis_type;
+
+		/*Hooks*/
+		Hook*       helement;
+		Hook*       hnodes;
+
+		/*Corresponding fields*/
+		Element* element;
+		Node**   nodes;
+
+		Parameters *parameters;
+		Inputs     *inputs;
+
+
+		/*Numericalflux constructors,destructors {{{1*/
+		Numericalflux();
+		Numericalflux(int numericalflux_id,int i, IoModel* iomodel,int analysis_type);
+		~Numericalflux();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{1*/
+		void    InputUpdateFromVector(double* vector, int name, int type){/*Do nothing*/}
+		void    InputUpdateFromVector(int* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVector(bool* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromMatrixDakota(double* matrix, int nrows, int ncols, int name, int type){/*Do nothing*/}
+		void    InputUpdateFromVectorDakota(double* vector, int name, int type){/*Do nothing*/}
+		void    InputUpdateFromVectorDakota(int* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(bool* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromConstant(double constant, int name){/*Do nothing*/};
+		void    InputUpdateFromConstant(int constant, int name){/*Do nothing*/};
+		void    InputUpdateFromConstant(bool constant, int name){_error_("Not implemented yet!");}
+		void    InputUpdateFromSolution(double* solution){_error_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+		/*Load virtual functions definitions: {{{1*/
+		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(Mat Kff, Mat Kfs);
+		void  CreatePVector(Vec pf);
+		void  PenaltyCreateKMatrix(Mat Kff, Mat kfs, double kmax);
+		void  PenaltyCreatePVector(Vec pf, double kmax);
+		bool  InAnalysis(int analysis_type);
+		/*}}}*/
+		/*Numericalflux management:{{{1*/
+		void  GetNormal(double* normal,double xyz_list[4][3]);
+		ElementMatrix* CreateKMatrixPrognostic(void);
+		ElementMatrix* CreateKMatrixPrognosticInternal(void);
+		ElementMatrix* CreateKMatrixPrognosticBoundary(void);
+		ElementMatrix* CreateKMatrixBalancethickness(void);
+		ElementMatrix* CreateKMatrixBalancethicknessInternal(void);
+		ElementMatrix* CreateKMatrixBalancethicknessBoundary(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethickness(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethicknessInternal(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethicknessBoundary(void);
+		ElementVector* CreatePVectorPrognostic(void);
+		ElementVector* CreatePVectorPrognosticInternal(void);
+		ElementVector* CreatePVectorPrognosticBoundary(void);
+		ElementVector* CreatePVectorBalancethickness(void);
+		ElementVector* CreatePVectorBalancethicknessInternal(void);
+		ElementVector* CreatePVectorBalancethicknessBoundary(void);
+		ElementVector* CreatePVectorAdjointBalancethickness(void);
+		/*}}}*/
+
+};
+
+#endif  /* _NUMERICALFLUX_H_ */
Index: /issm/trunk-jpl-damage/src/c/objects/Loads/Pengrid.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Loads/Pengrid.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Loads/Pengrid.cpp	(revision 11330)
@@ -0,0 +1,702 @@
+/*!\file Pengrid.c
+ * \brief: implementation of the Pengrid object
+ */
+
+/*Headers*/
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+/*}}}*/
+	
+/*Element macros*/
+#define NUMVERTICES   1
+
+/*Pengrid constructors and destructor*/
+/*FUNCTION Pengrid::Pengrid(){{{1*/
+Pengrid::Pengrid(){
+	this->inputs=NULL;
+	this->parameters=NULL;
+	this->hnode=NULL;
+	this->node=NULL;
+	this->helement=NULL;
+	this->element=NULL;
+	this->hmatpar=NULL;
+	this->matpar=NULL;
+	
+	/*not active, not zigzagging: */
+	active=0;
+	zigzag_counter=0;
+
+}
+/*}}}1*/
+/*FUNCTION Pengrid::Pengrid(int index, int id, IoModel* iomodel,int analysis_type){{{1*/
+Pengrid::Pengrid(int id, int index, IoModel* iomodel, int in_analysis_type){ //i is the element index
+
+	int i,j;
+	int pengrid_node_id;
+	int pengrid_matpar_id;
+	int pengrid_element_id;
+
+	int numberofvertices;
+	int numberofelements;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+
+	/*Some checks if debugging activated*/
+	_assert_(iomodel->singlenodetoelementconnectivity);
+	_assert_(index>=0 && index<numberofvertices);
+	_assert_(id);
+
+	/*id: */
+	this->id=id;
+	this->analysis_type=in_analysis_type;
+	
+	/*hooks: */
+	pengrid_node_id=iomodel->nodecounter+index+1;
+	pengrid_element_id=iomodel->singlenodetoelementconnectivity[index];
+	_assert_(pengrid_element_id);
+	pengrid_matpar_id=numberofelements+1; //refers to the constant material parameters object
+
+	this->hnode=new Hook(&pengrid_node_id,1);
+	this->helement=new Hook(&pengrid_element_id,1);
+	this->hmatpar=new Hook(&pengrid_matpar_id,1);
+
+	//initialize inputs: none needed
+	this->inputs=new Inputs();
+
+	//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+	this->parameters=NULL;
+	this->node=NULL;
+	this->element=NULL;
+	this->matpar=NULL;
+
+	//let's not forget internals
+	this->active=0;
+	this->zigzag_counter=0;
+
+}
+/*}}}*/
+/*FUNCTION Pengrid::~Pengrid(){{{1*/
+Pengrid::~Pengrid(){
+	delete inputs;
+	delete hnode;
+	delete helement;
+	delete hmatpar;
+	return;
+}
+/*}}}1*/
+			
+/*Object virtual functions definitions:*/
+/*FUNCTION Pengrid::Echo {{{1*/
+void Pengrid::Echo(void){
+	this->DeepEcho();
+}
+/*}}}1*/
+/*FUNCTION Pengrid::DeepEcho{{{1*/
+void Pengrid::DeepEcho(void){
+
+	printf("Pengrid:\n");
+	printf("   id: %i\n",id);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	hnode->DeepEcho();
+	helement->DeepEcho();
+	hmatpar->DeepEcho();
+	printf("   active %i\n",this->active);
+	printf("   zigzag_counter %i\n",this->zigzag_counter);
+	printf("   parameters\n");
+	parameters->DeepEcho();
+	printf("   inputs\n");
+	inputs->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION Pengrid::Id {{{1*/
+int    Pengrid::Id(void){ return id; }
+/*}}}1*/
+/*FUNCTION Pengrid::MyRank {{{1*/
+int    Pengrid::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}1*/
+#ifdef _SERIAL_
+/*FUNCTION Pengrid::Marshall {{{1*/
+void  Pengrid::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+	char* marshalled_inputs=NULL;
+	int   marshalled_inputs_size;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of Tria: */
+	enum_type=PengridEnum;
+
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+
+	/*marshall Tria data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&analysis_type,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+	memcpy(marshalled_dataset,&active,sizeof(active));marshalled_dataset+=sizeof(active);
+	memcpy(marshalled_dataset,&zigzag_counter,sizeof(zigzag_counter));marshalled_dataset+=sizeof(zigzag_counter);
+
+	/*Marshall hooks: */
+	hnode->Marshall(&marshalled_dataset);
+	helement->Marshall(&marshalled_dataset);
+	hmatpar->Marshall(&marshalled_dataset);
+
+	/*Marshall inputs: */
+	marshalled_inputs_size=inputs->MarshallSize();
+	marshalled_inputs=inputs->Marshall();
+	memcpy(marshalled_dataset,marshalled_inputs,marshalled_inputs_size*sizeof(char));
+	marshalled_dataset+=marshalled_inputs_size;
+
+	/*parameters: don't do anything about it. parameters are marshalled somewhere else!*/
+
+	xfree((void**)&marshalled_inputs);
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+/*FUNCTION Pengrid::MarshallSize {{{1*/
+int   Pengrid::MarshallSize(){
+	
+	return sizeof(id)
+		+sizeof(analysis_type)
+		+sizeof(active)
+		+sizeof(zigzag_counter)
+		+hnode->MarshallSize()
+		+helement->MarshallSize()
+		+hmatpar->MarshallSize()
+		+inputs->MarshallSize()
+		+sizeof(int); //sizeof(int) for enum type
+}
+/*}}}*/
+/*FUNCTION Pengrid::Demarshall {{{1*/
+void  Pengrid::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&analysis_type,marshalled_dataset,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+	memcpy(&active,marshalled_dataset,sizeof(active));marshalled_dataset+=sizeof(active);
+	memcpy(&zigzag_counter,marshalled_dataset,sizeof(zigzag_counter));marshalled_dataset+=sizeof(zigzag_counter);
+
+	/*demarshall hooks: */
+	hnode=new Hook(); hnode->Demarshall(&marshalled_dataset);
+	helement=new Hook(); helement->Demarshall(&marshalled_dataset);
+	hmatpar=new Hook(); hmatpar->Demarshall(&marshalled_dataset);
+	
+	/*demarshall inputs: */
+	inputs=(Inputs*)DataSetDemarshallRaw(&marshalled_dataset); 
+
+	/*parameters: may not exist even yet, so let Configure handle it: */
+	this->parameters=NULL;
+	this->node=NULL;
+	this->element=NULL;
+	this->matpar=NULL;
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION Pengrid::ObjectEnum{{{1*/
+int Pengrid::ObjectEnum(void){
+
+	return PengridEnum;
+}
+/*}}}1*/
+/*FUNCTION Icefront::copy {{{1*/
+Object* Pengrid::copy() {
+	
+	Pengrid* pengrid=NULL;
+
+	pengrid=new Pengrid();
+
+	/*copy fields: */
+	pengrid->id=this->id;
+	pengrid->analysis_type=this->analysis_type;
+	if(this->inputs){
+		pengrid->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		pengrid->inputs=new Inputs();
+	}
+	/*point parameters: */
+	pengrid->parameters=this->parameters;
+
+	/*now deal with hooks and objects: */
+	pengrid->hnode=(Hook*)this->hnode->copy();
+	pengrid->hmatpar=(Hook*)this->hmatpar->copy();
+	pengrid->helement=(Hook*)this->helement->copy();
+
+	/*corresponding fields*/
+	pengrid->node  =(Node*)pengrid->hnode->delivers();
+	pengrid->matpar =(Matpar*)pengrid->hmatpar->delivers();
+	pengrid->element=(Element*)pengrid->helement->delivers();
+
+	//let's not forget internals
+	pengrid->active=this->active=0;
+	pengrid->zigzag_counter=this->zigzag_counter=0;
+
+	return pengrid;
+
+}
+/*}}}*/
+
+/*Load virtual functions definitions:*/
+/*FUNCTION Pengrid::Configure {{{1*/
+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;
+}
+/*}}}1*/
+/*FUNCTION Pengrid::SetCurrentConfiguration {{{1*/
+void  Pengrid::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}1*/
+/*FUNCTION Pengrid::CreateKMatrix {{{1*/
+void  Pengrid::CreateKMatrix(Mat Kff, Mat Kfs){
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}1*/
+/*FUNCTION Pengrid::CreatePVector {{{1*/
+void  Pengrid::CreatePVector(Vec pf){
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}1*/
+/*FUNCTION Pengrid::PenaltyCreateMatrix {{{1*/
+void  Pengrid::PenaltyCreateKMatrix(Mat Kff, Mat Kfs,double kmax){
+
+	/*Retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case DiagnosticHorizAnalysisEnum: case AdjointHorizAnalysisEnum:
+			Ke=PenaltyCreateKMatrixDiagnosticStokes(kmax);
+			break;
+		case ThermalAnalysisEnum:
+			Ke=PenaltyCreateKMatrixThermal(kmax);
+			break;
+		case MeltingAnalysisEnum:
+			Ke=PenaltyCreateKMatrixMelting(kmax);
+			break;
+		default:
+			_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}1*/
+/*FUNCTION Pengrid::PenaltyCreatePVector {{{1*/
+void  Pengrid::PenaltyCreatePVector(Vec pf,double 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 DiagnosticHorizAnalysisEnum: case AdjointHorizAnalysisEnum:
+			break;
+		default:
+			_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+
+	/*Add to global Vector*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}1*/
+/*FUNCTION Pengrid::InAnalysis{{{1*/
+bool Pengrid::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type)return true;
+	else return false;
+}
+/*}}}*/
+
+/*Update virtual functions definitions:*/
+/*FUNCTION Pengrid::InputUpdateFromVector(double* vector, int name, int type) {{{1*/
+void  Pengrid::InputUpdateFromVector(double* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromVector(int* vector, int name, int type) {{{1*/
+void  Pengrid::InputUpdateFromVector(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromVector(bool* vector, int name, int type) {{{1*/
+void  Pengrid::InputUpdateFromVector(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromMatrixDakota(double* vector, int nrows, int ncols, int name, int type) {{{1*/
+void  Pengrid::InputUpdateFromMatrixDakota(double* matrix, int nrows, int ncols, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromVectorDakota(double* vector, int name, int type) {{{1*/
+void  Pengrid::InputUpdateFromVectorDakota(double* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromVectorDakota(int* vector, int name, int type) {{{1*/
+void  Pengrid::InputUpdateFromVectorDakota(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromVectorDakota(bool* vector, int name, int type) {{{1*/
+void  Pengrid::InputUpdateFromVectorDakota(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromConstant(double constant, int name) {{{1*/
+void  Pengrid::InputUpdateFromConstant(double constant, int name){
+	switch(name){
+
+		case MeltingOffsetEnum:
+			inputs->AddInput(new DoubleInput(name,constant));
+			return;
+
+	}
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromConstant(int constant, int name) {{{1*/
+void  Pengrid::InputUpdateFromConstant(int constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromConstant(bool constant, int name) {{{1*/
+void  Pengrid::InputUpdateFromConstant(bool constant, int name){
+
+	switch(name){
+
+		case ResetPenaltiesEnum:
+			if (constant) zigzag_counter=0;
+			return;
+
+	}
+}
+/*}}}*/
+/*FUNCTION Pengrid::InputUpdateFromSolution{{{1*/
+void  Pengrid::InputUpdateFromSolution(double* solution){
+	/*Nothing updated yet*/
+}
+/*}}}*/		
+
+/*Pengrid management:*/
+/*FUNCTION Pengrid::ConstraintActivate {{{1*/
+void  Pengrid::ConstraintActivate(int* punstable){
+
+	int analysis_type;
+
+	/*Retrieve parameters: */
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	if (analysis_type==DiagnosticHorizAnalysisEnum){
+		/*No penalty to check*/
+		return;
+	}
+	else if (analysis_type==ThermalAnalysisEnum){
+		ConstraintActivateThermal(punstable);
+	}
+	else if (analysis_type==MeltingAnalysisEnum){
+		/*No penalty to check*/
+		return;
+	}
+	else{
+		_error_("analysis: %s not supported yet",EnumToStringx(analysis_type));
+	}
+
+}
+/*}}}1*/
+/*FUNCTION Pengrid::ConstraintActivateThermal {{{1*/
+void  Pengrid::ConstraintActivateThermal(int* punstable){
+
+	//   The penalty is stable if it doesn't change during to successive iterations.   
+
+	int    found=0;
+	const int numnodes=1;
+	double pressure;
+	double temperature;
+	double t_pmp;
+	int    new_active;
+	int    unstable=0;
+	int    reset_penalties=0;
+	int    penalty_lock;
+
+	/*recover pointers: */
+	Penta* penta=(Penta*)element;
+	
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if (node->IsClone()){
+		unstable=0;
+		*punstable=unstable;
+		return;
+	}
+
+	//First recover pressure and temperature values, using the element: */
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	penta->GetInputValue(&temperature,node,TemperaturePicardEnum);
+
+	//Recover our data:
+	parameters->FindParam(&penalty_lock,ThermalPenaltyLockEnum);
+	
+	//Compute pressure melting point
+	t_pmp=matpar->TMeltingPoint(pressure);
+
+	//Figure out if temperature is over melting_point, in which case, this penalty needs to be activated.
+
+	if (temperature>t_pmp){
+		new_active=1;
+	}
+	else{
+		new_active=0;
+	}
+
+
+	//Figure out stability of this penalty
+	if (active==new_active){
+		unstable=0;
+	}
+	else{
+		unstable=1;
+		if(penalty_lock)zigzag_counter++;
+	}
+
+	/*If penalty keeps zigzagging more than 5 times: */
+	if(penalty_lock){
+		if(zigzag_counter>penalty_lock){
+			unstable=0;
+			active=1;
+		}
+	}
+
+	//Set penalty flag
+	active=new_active;
+
+	//*Assign output pointers:*/
+	*punstable=unstable;
+}
+/*}}}1*/
+/*FUNCTION Pengrid::PenaltyCreateKMatrixDiagnosticStokes {{{1*/
+ElementMatrix* Pengrid::PenaltyCreateKMatrixDiagnosticStokes(double kmax){
+	
+	const int numdof = NUMVERTICES *NDOF4;
+	double    slope[2];
+	double    penalty_offset;
+	int       approximation;
+
+	Penta* penta=(Penta*)element;
+
+	/*Initialize Element vector and return if necessary*/
+	penta->inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=StokesApproximationEnum &&  approximation!=PattynStokesApproximationEnum) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(&node,1,this->parameters,StokesApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
+	penta->GetInputValue(&slope[0],node,BedSlopeXEnum);
+	penta->GetInputValue(&slope[1],node,BedSlopeYEnum);
+
+	/*Create elementary matrix: add penalty to constrain wb (wb=ub*db/dx+vb*db/dy)*/
+	Ke->values[2*NDOF4+0]=-slope[0]*kmax*pow((double)10.0,penalty_offset);
+	Ke->values[2*NDOF4+1]=-slope[1]*kmax*pow((double)10.0,penalty_offset);
+	Ke->values[2*NDOF4+2]= kmax*pow((double)10,penalty_offset);
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,&node,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}1*/
+/*FUNCTION Pengrid::PenaltyCreateKMatrixMelting {{{1*/
+ElementMatrix* Pengrid::PenaltyCreateKMatrixMelting(double kmax){
+
+	const int numdof=NUMVERTICES*NDOF1;
+	double pressure,temperature,t_pmp;
+	double penalty_factor;
+
+	Penta* penta=(Penta*)element;
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if (node->IsClone()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(&node,1,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	penta->GetInputValue(&temperature,node,TemperatureEnum);
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+	
+	/*Compute pressure melting point*/
+	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
+
+	/*Add penalty load*/
+	if (temperature<t_pmp){ //If T<Tpmp, there must be no melting. Therefore, melting should be  constrained to 0 when T<Tpmp, instead of using spcs, use penalties
+		Ke->values[0]=kmax*pow((double)10,penalty_factor);
+	}
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}1*/
+/*FUNCTION Pengrid::PenaltyCreateKMatrixThermal {{{1*/
+ElementMatrix* Pengrid::PenaltyCreateKMatrixThermal(double kmax){
+
+	const int numdof=NUMVERTICES*NDOF1;
+	double    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((double)10,penalty_factor);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}1*/
+/*FUNCTION Pengrid::PenaltyCreatePVectorMelting {{{1*/
+ElementVector* Pengrid::PenaltyCreatePVectorMelting(double kmax){
+	
+	const int numdof=NUMVERTICES*NDOF1;
+	double pressure;
+	double temperature;
+	double melting_offset;
+	double t_pmp;
+	double dt,penalty_factor;
+
+	/*recover pointers: */
+	Penta* penta=(Penta*)element;
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if (node->IsClone()) return NULL;
+	ElementVector* pe=new ElementVector(&node,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	penta->GetInputValue(&temperature,node,TemperatureEnum);
+	inputs->GetInputValue(&melting_offset,MeltingOffsetEnum);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	/*Compute pressure melting point*/
+	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
+
+	/*Add penalty load
+	  This time, the penalty must have the same value as the one used for the thermal computation
+	  so that the corresponding melting can be computed correctly
+	  In the thermal computation, we used kmax=melting_offset, and the same penalty_factor*/
+	if (temperature<t_pmp){ //%no melting
+		pe->values[0]=0;
+	}
+	else{
+		if (dt) pe->values[0]=melting_offset*pow((double)10,penalty_factor)*(temperature-t_pmp)/dt;
+		else    pe->values[0]=melting_offset*pow((double)10,penalty_factor)*(temperature-t_pmp);
+	}
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}1*/
+/*FUNCTION Pengrid::PenaltyCreatePVectorThermal {{{1*/
+ElementVector* Pengrid::PenaltyCreatePVectorThermal(double kmax){
+
+	const int numdof=NUMVERTICES*NDOF1;
+	double pressure;
+	double t_pmp;
+	double penalty_factor;
+
+	Penta* penta=(Penta*)element;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementVector* pe=new ElementVector(&node,1,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	/*Compute pressure melting point*/
+	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
+
+	pe->values[0]=kmax*pow((double)10,penalty_factor)*t_pmp;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}1*/
+/*FUNCTION Pengrid::ResetConstraint {{{1*/
+void  Pengrid::ResetConstraint(void){
+	active=0;
+	zigzag_counter=0;
+}
+/*}}}1*/
+/*FUNCTION Pengrid::UpdateInputs {{{1*/
+void  Pengrid::UpdateInputs(double* solution){
+	_error_("not supported yet!");
+}
+/*}}}1*/
Index: /issm/trunk-jpl-damage/src/c/objects/Loads/Pengrid.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Loads/Pengrid.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Loads/Pengrid.h	(revision 11330)
@@ -0,0 +1,99 @@
+/*!\file Pengrid.h
+ * \brief: header file for pengrid object */
+
+#ifndef _PENGRID_H_
+#define _PENGRID_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Load.h"
+class Hook;
+class Inputs;
+class Parameters;
+class IoModel;
+/*}}}*/
+
+class Pengrid: public Load{
+
+	private: 
+
+		int		id;
+		int analysis_type;
+		
+		/*Hooks*/
+		Hook* hnode;  //hook to 1 node
+		Hook* helement;  //hook to 1 element
+		Hook* hmatpar; //hook to 1 matpar
+
+		/*Corresponding fields*/
+		Node    *node;
+		Element *element;
+		Matpar  *matpar;
+
+		Parameters* parameters; //pointer to solution parameters
+		Inputs*  inputs;
+	
+		/*internals: */
+		int active;
+		int zigzag_counter;
+
+	public:
+
+		/*Pengrid constructors, destructors {{{1*/
+		Pengrid();
+		Pengrid(int index, int id, IoModel* iomodel,int analysis_type);
+		~Pengrid();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{1*/
+		void  InputUpdateFromVector(double* vector, int name, int type);
+		void  InputUpdateFromVector(int* vector, int name, int type);
+		void  InputUpdateFromVector(bool* vector, int name, int type);
+		void  InputUpdateFromMatrixDakota(double* matrix ,int nrows, int ncols, int name, int type);
+		void  InputUpdateFromVectorDakota(double* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
+		void  InputUpdateFromConstant(double constant, int name);
+		void  InputUpdateFromConstant(int constant, int name);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromSolution(double* solution);
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+		/*Load virtual functions definitions: {{{1*/
+		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(Mat Kff, Mat Kfs);
+		void  CreatePVector(Vec pf);
+		void  PenaltyCreateKMatrix(Mat Kff, Mat kfs, double kmax);
+		void  PenaltyCreatePVector(Vec pf, double kmax);
+		bool  InAnalysis(int analysis_type);
+		/*}}}*/
+		/*Pengrid management {{{1*/
+		ElementMatrix* PenaltyCreateKMatrixDiagnosticStokes(double kmax);
+		ElementMatrix* PenaltyCreateKMatrixThermal(double kmax);
+		ElementMatrix* PenaltyCreateKMatrixMelting(double kmax);
+		ElementVector* PenaltyCreatePVectorThermal(double kmax);
+		ElementVector* PenaltyCreatePVectorMelting(double kmax);
+		void  ConstraintActivate(int* punstable);
+		void  ConstraintActivateThermal(int* punstable);
+		void  UpdateInputs(double* solution);
+		void  ResetConstraint(void);
+		/*}}}*/
+
+};
+
+#endif  /* _PENGRID_H_ */
+
+
Index: /issm/trunk-jpl-damage/src/c/objects/Loads/Penpair.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Loads/Penpair.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Loads/Penpair.cpp	(revision 11330)
@@ -0,0 +1,408 @@
+/*!\file Penpair.c
+ * \brief: implementation of the Penpair object
+ */
+
+/*Headers*/
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES 2
+
+/*Penpair constructors and destructor*/
+/*FUNCTION Penpair::constructor {{{1*/
+Penpair::Penpair(){
+
+	this->hnodes=NULL;
+	this->nodes=NULL;
+	this->parameters=NULL;
+	return;
+}
+/*}}}1*/
+/*FUNCTION Penpair::creation {{{1*/
+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;
+}
+/*}}}1*/
+/*FUNCTION Penpair::destructor {{{1*/
+Penpair::~Penpair(){
+	delete hnodes;
+	return;
+}
+/*}}}1*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Penpair::Echo {{{1*/
+void Penpair::Echo(void){
+
+	int i;
+
+	printf("Penpair:\n");
+	printf("   id: %i\n",id);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	hnodes->Echo();
+	
+	return;
+}
+/*}}}1*/
+/*FUNCTION Penpair::DeepEcho {{{1*/
+void Penpair::DeepEcho(void){
+
+	printf("Penpair:\n");
+	printf("   id: %i\n",id);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	hnodes->DeepEcho();
+
+	return;
+}		
+/*}}}1*/
+/*FUNCTION Penpair::Id {{{1*/
+int    Penpair::Id(void){ return id; }
+/*}}}1*/
+/*FUNCTION Penpair::MyRank {{{1*/
+int    Penpair::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}1*/
+#ifdef _SERIAL_
+/*FUNCTION Penpair::Marshall {{{1*/
+void  Penpair::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of Penpair: */
+	enum_type=PenpairEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*marshall Penpair data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&analysis_type,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+
+	/*Marshall hooks*/
+	hnodes->Marshall(&marshalled_dataset);
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}1*/
+/*FUNCTION Penpair::MarshallSize {{{1*/
+int   Penpair::MarshallSize(){
+
+	return sizeof(id)+
+		+sizeof(analysis_type)
+		+hnodes->MarshallSize()
+		+sizeof(int); //sizeof(int) for enum type
+}
+/*}}}1*/
+/*FUNCTION Penpair::Demarshall {{{1*/
+void  Penpair::Demarshall(char** pmarshalled_dataset){
+
+	int i;
+	char* marshalled_dataset=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&analysis_type,marshalled_dataset,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+
+	/*demarshall hooks: */
+	hnodes=new Hook(); hnodes->Demarshall(&marshalled_dataset);
+
+	/*pointers are garbabe, until configuration is carried out: */
+	nodes=NULL;
+	parameters=NULL;
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}1*/
+#endif
+/*FUNCTION Penpair::ObjectEnum{{{1*/
+int Penpair::ObjectEnum(void){
+
+	return PenpairEnum;
+}
+/*}}}1*/
+/*FUNCTION Penpair::copy {{{1*/
+Object* Penpair::copy() {
+	
+	Penpair* penpair=NULL;
+
+	penpair=new Penpair();
+
+	/*copy fields: */
+	penpair->id=this->id;
+	penpair->analysis_type=this->analysis_type;
+
+	/*now deal with hooks and objects: */
+	penpair->hnodes=(Hook*)this->hnodes->copy();
+	penpair->nodes =(Node**)penpair->hnodes->deliverp();
+
+	/*point parameters: */
+	penpair->parameters=this->parameters;
+
+	return penpair;
+
+}
+/*}}}*/
+		
+/*Load virtual functions definitions:*/
+/*FUNCTION Penpair::Configure {{{1*/
+void  Penpair::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	hnodes->configure(nodesin);
+
+	/*Initialize hooked fields*/
+	this->nodes  =(Node**)hnodes->deliverp();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+}
+/*}}}1*/
+/*FUNCTION Penpair::SetCurrentConfiguration {{{1*/
+void  Penpair::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}1*/
+/*FUNCTION Penpair::CreateKMatrix {{{1*/
+void  Penpair::CreateKMatrix(Mat Kff, Mat 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;
+
+}
+/*}}}1*/
+/*FUNCTION Penpair::CreatePVector {{{1*/
+void  Penpair::CreatePVector(Vec pf){
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}1*/
+/*FUNCTION Penpair::PenaltyCreateKMatrix {{{1*/
+void  Penpair::PenaltyCreateKMatrix(Mat Kff, Mat Kfs,double kmax){
+
+	/*Retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case DiagnosticHorizAnalysisEnum:
+			Ke=PenaltyCreateKMatrixDiagnosticHoriz(kmax);
+			break;
+		case PrognosticAnalysisEnum:
+			Ke=PenaltyCreateKMatrixPrognostic(kmax);
+			break;
+		default:
+			_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+
+	/*Add to global Vector*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}1*/
+/*FUNCTION Penpair::PenaltyCreatePVector {{{1*/
+void  Penpair::PenaltyCreatePVector(Vec pf,double kmax){
+	/*No loads applied, do nothing: */
+	return;
+}
+/*}}}1*/
+/*FUNCTION Penpair::InAnalysis{{{1*/
+bool Penpair::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type)return true;
+	else return false;
+}
+/*}}}*/
+
+/*Update virtual functions definitions:*/
+/*FUNCTION Penpair::InputUpdateFromConstant(double constant, int name) {{{1*/
+void  Penpair::InputUpdateFromConstant(double constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Penpair::InputUpdateFromConstant(int constant, int name) {{{1*/
+void  Penpair::InputUpdateFromConstant(int constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Penpair::InputUpdateFromConstant(bool constant, int name) {{{1*/
+void  Penpair::InputUpdateFromConstant(bool constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Penpair::InputUpdateFromVector(double* vector, int name, int type) {{{1*/
+void  Penpair::InputUpdateFromVector(double* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Penpair::InputUpdateFromVector(int* vector, int name, int type) {{{1*/
+void  Penpair::InputUpdateFromVector(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Penpair::InputUpdateFromVector(bool* vector, int name, int type) {{{1*/
+void  Penpair::InputUpdateFromVector(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+
+/*Penpair management:*/
+/*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticHoriz{{{1*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticHoriz(double kmax){
+
+	int    approximation0=nodes[0]->GetApproximation();
+	int    approximation1=nodes[1]->GetApproximation();
+
+	switch(approximation0){
+		case MacAyealApproximationEnum:
+			switch(approximation1){
+				case MacAyealApproximationEnum: return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				case PattynApproximationEnum:   return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				default: _error_("not supported yet");
+			}
+		case PattynApproximationEnum:
+			switch(approximation1){
+				case MacAyealApproximationEnum: return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				case PattynApproximationEnum:   return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				default: _error_("not supported yet");
+			}
+		case StokesApproximationEnum:
+			switch(approximation1){
+				case StokesApproximationEnum: return PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				case NoneApproximationEnum: return   PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				default: _error_("not supported yet");
+			}
+		case NoneApproximationEnum:
+			switch(approximation1){
+				case StokesApproximationEnum: return PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				case NoneApproximationEnum: return   PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				default: _error_("not supported yet");
+			}
+		default: _error_("not supported yet");
+	}
+}
+/*}}}1*/
+/*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticMacAyealPattyn {{{1*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticMacAyealPattyn(double kmax){
+	
+	const int numdof=NUMVERTICES*NDOF2;
+	double penalty_offset;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
+
+	//Create elementary matrix: add penalty to 
+	Ke->values[0*numdof+0]=+kmax*pow((double)10.0,penalty_offset);
+	Ke->values[0*numdof+2]=-kmax*pow((double)10.0,penalty_offset);
+	Ke->values[2*numdof+0]=-kmax*pow((double)10.0,penalty_offset);
+	Ke->values[2*numdof+2]=+kmax*pow((double)10.0,penalty_offset);
+
+	Ke->values[1*numdof+1]=+kmax*pow((double)10.0,penalty_offset);
+	Ke->values[1*numdof+3]=-kmax*pow((double)10.0,penalty_offset);
+	Ke->values[3*numdof+1]=-kmax*pow((double)10.0,penalty_offset);
+	Ke->values[3*numdof+3]=+kmax*pow((double)10.0,penalty_offset);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}1*/
+/*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticStokes {{{1*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticStokes(double kmax){
+	
+	const int numdof=NUMVERTICES*NDOF4;
+	double penalty_offset;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
+
+	//Create elementary matrix: add penalty to 
+	Ke->values[0*numdof+0]=+kmax*pow((double)10.0,penalty_offset);
+	Ke->values[0*numdof+4]=-kmax*pow((double)10.0,penalty_offset);
+	Ke->values[4*numdof+0]=-kmax*pow((double)10.0,penalty_offset);
+	Ke->values[4*numdof+4]=+kmax*pow((double)10.0,penalty_offset);
+
+	Ke->values[1*numdof+1]=+kmax*pow((double)10.0,penalty_offset);
+	Ke->values[1*numdof+5]=-kmax*pow((double)10.0,penalty_offset);
+	Ke->values[5*numdof+1]=-kmax*pow((double)10.0,penalty_offset);
+	Ke->values[5*numdof+5]=+kmax*pow((double)10.0,penalty_offset);
+	
+	Ke->values[2*numdof+2]=+kmax*pow((double)10.0,penalty_offset);
+	Ke->values[2*numdof+6]=-kmax*pow((double)10.0,penalty_offset);
+	Ke->values[6*numdof+2]=-kmax*pow((double)10.0,penalty_offset);
+	Ke->values[6*numdof+6]=+kmax*pow((double)10.0,penalty_offset);
+
+	Ke->values[3*numdof+3]=+kmax*pow((double)10.0,penalty_offset);
+	Ke->values[3*numdof+7]=-kmax*pow((double)10.0,penalty_offset);
+	Ke->values[7*numdof+3]=-kmax*pow((double)10.0,penalty_offset);
+	Ke->values[7*numdof+7]=+kmax*pow((double)10.0,penalty_offset);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}1*/
+/*FUNCTION Penpair::PenaltyCreateKMatrixPrognostic {{{1*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixPrognostic(double kmax){
+
+	const int numdof=NUMVERTICES*NDOF1;
+	double penalty_factor;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_factor,PrognosticPenaltyFactorEnum);
+
+	//Create elementary matrix: add penalty to 
+	Ke->values[0*numdof+0]=+kmax*pow((double)10.0,penalty_factor);
+	Ke->values[0*numdof+1]=-kmax*pow((double)10.0,penalty_factor);
+	Ke->values[1*numdof+0]=-kmax*pow((double)10.0,penalty_factor);
+	Ke->values[1*numdof+1]=+kmax*pow((double)10.0,penalty_factor);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}1*/
Index: /issm/trunk-jpl-damage/src/c/objects/Loads/Penpair.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Loads/Penpair.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Loads/Penpair.h	(revision 11330)
@@ -0,0 +1,80 @@
+/*!\file Penpair.h
+ * \brief: header file for penpair object */
+
+#ifndef _PENPAIR_H_
+#define _PENPAIR_H_
+
+/*Headers:*/
+/*{{{1*/
+#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: {{{1*/
+		Penpair();
+		Penpair(int penpair_id,int* penpair_node_ids,int analysis_type);
+		~Penpair();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{1*/
+		void  InputUpdateFromVector(double* vector, int name, int type);
+		void  InputUpdateFromVector(int* vector, int name, int type);
+		void  InputUpdateFromVector(bool* vector, int name, int type);
+		void  InputUpdateFromMatrixDakota(double* matrix, int nrow, int ncols,int name, int type){_error_("Not implemented yet!");}
+		void  InputUpdateFromVectorDakota(double* vector, int name, int type){_error_("Not implemented yet!");}
+		void  InputUpdateFromVectorDakota(int* vector, int name, int type){_error_("Not implemented yet!");}
+		void  InputUpdateFromVectorDakota(bool* vector, int name, int type){_error_("Not implemented yet!");}
+		void  InputUpdateFromConstant(double constant, int name);
+		void  InputUpdateFromConstant(int constant, int name);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromSolution(double* solution){_error_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+			/*Load virtual functions definitions: {{{1*/
+		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(Mat Kff, Mat Kfs);
+		void  CreatePVector(Vec pf);
+		void  PenaltyCreateKMatrix(Mat Kff, Mat kfs, double kmax);
+		void  PenaltyCreatePVector(Vec pf, double kmax);
+		bool  InAnalysis(int analysis_type);
+		/*}}}*/
+			/*Penpair management: {{{1*/
+		ElementMatrix* PenaltyCreateKMatrixDiagnosticHoriz(double kmax);
+		ElementMatrix* PenaltyCreateKMatrixDiagnosticMacAyealPattyn(double kmax);
+		ElementMatrix* PenaltyCreateKMatrixDiagnosticStokes(double kmax);
+		ElementMatrix* PenaltyCreateKMatrixPrognostic(double kmax);
+		/*}}}*/
+};
+
+#endif  /* _PENPAIR_H_ */
+
+
Index: /issm/trunk-jpl-damage/src/c/objects/Loads/Riftfront.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Loads/Riftfront.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Loads/Riftfront.cpp	(revision 11330)
@@ -0,0 +1,1035 @@
+/*!\file Riftfront.cpp
+ * \brief: implementation of the Riftfront object
+ */
+
+/*Headers:*/
+/*{{{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 "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../modules/ModelProcessorx/ModelProcessorx.h"
+#include "../objects.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES 2
+
+/*Riftfront constructors and destructor*/
+/*FUNCTION Riftfront::Riftfront(){{{1*/
+Riftfront::Riftfront(){
+	this->inputs=NULL;
+	this->parameters=NULL;
+	this->hnodes=NULL;
+	this->helements=NULL;
+	this->hmatpar=NULL;
+	this->nodes=NULL;
+	this->elements=NULL;
+	this->matpar=NULL;
+}
+/*}}}*/
+/*FUNCTION Riftfront::Riftfront(int id, int i, IoModel* iomodel,int analysis_type){{{1*/
+Riftfront::Riftfront(int riftfront_id,int i, IoModel* iomodel,int riftfront_analysis_type){
+
+	/*data: */
+	int    riftfront_node_ids[2];
+	int    riftfront_elem_ids[2];
+	int    riftfront_matpar_id;
+	int    riftfront_type;
+	int    riftfront_fill;
+	double riftfront_friction;
+	double riftfront_fractionincrement;
+	bool   riftfront_shelf;
+	int    numberofelements;
+	int    penalty_lock;
+
+	/*intermediary: */
+	int el1    ,el2;
+	int node1  ,node2;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&penalty_lock,DiagnosticRiftPenaltyLockEnum);
+
+	/*Ok, retrieve all the data needed to add a penalty between the two nodes: */
+	el1=(int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+2);
+	el2=(int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+3); 
+
+	node1=(int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+0); 
+	node2=(int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+1);
+
+	/*id: */
+	this->id=riftfront_id;
+	this->analysis_type=riftfront_analysis_type;
+
+	/*hooks: */
+	riftfront_node_ids[0]=iomodel->nodecounter+node1;
+	riftfront_node_ids[1]=iomodel->nodecounter+node2;
+	riftfront_elem_ids[0]=el1;
+	riftfront_elem_ids[1]=el2;
+	riftfront_matpar_id=numberofelements+1; //matlab indexing
+
+	/*Hooks: */
+	this->hnodes=new Hook(riftfront_node_ids,2);
+	this->helements=new Hook(riftfront_elem_ids,2);
+	this->hmatpar=new Hook(&riftfront_matpar_id,1);
+
+	/*computational parameters: */
+	this->active=0;
+	this->frozen=0;
+	this->counter=0;
+	this->prestable=0;
+	this->penalty_lock=penalty_lock;
+	this->material_converged=0;
+	this->normal[0]=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+4);
+	this->normal[1]=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+5);
+	this->length=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+6);
+	this->fraction=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+9);
+	this->state=(int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+11);
+
+	//intialize inputs, and add as many inputs per element as requested: 
+	this->inputs=new Inputs();
+		
+	riftfront_type=SegmentRiftfrontEnum;
+	riftfront_fill = (int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+7);
+	riftfront_friction=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+8);
+	riftfront_fractionincrement=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+10);
+	riftfront_shelf=(bool)iomodel->Data(MaskVertexonfloatingiceEnum)[node1-1];
+
+	this->inputs->AddInput(new IntInput(TypeEnum,riftfront_type));
+	this->inputs->AddInput(new IntInput(FillEnum,riftfront_fill));
+	this->inputs->AddInput(new DoubleInput(FrictionEnum,riftfront_friction));
+	this->inputs->AddInput(new DoubleInput(FractionIncrementEnum,riftfront_fractionincrement));
+	this->inputs->AddInput(new BoolInput(SegmentOnIceShelfEnum,riftfront_shelf));
+	
+	//parameters and hooked fields: we still can't point to them, they may not even exist. Configure will handle this.
+	this->parameters=NULL;
+	this->nodes= NULL;
+	this->elements= NULL;
+	this->matpar= NULL;
+		
+}
+/*}}}1*/
+/*FUNCTION Riftfront::~Riftfront(){{{1*/
+Riftfront::~Riftfront(){
+	delete inputs;
+	this->parameters=NULL;
+
+	delete hnodes;
+	delete helements;
+	delete hmatpar;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Riftfront::Echo {{{1*/
+void Riftfront::Echo(void){
+
+	Input* input=NULL;
+	int fill;
+	double friction,fractionincrement;
+
+	
+	/*recover some inputs first: */
+	input=(Input*)this->inputs->GetInput(FillEnum); input->GetInputValue(&fill);
+	input=(Input*)this->inputs->GetInput(FrictionEnum); input->GetInputValue(&friction);
+	input=(Input*)this->inputs->GetInput(FractionIncrementEnum); input->GetInputValue(&fractionincrement);
+
+	printf("Riftfront:\n");
+	printf("   id: %i\n",id);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	printf("   hnodes: %p\n",hnodes);
+	printf("   helements: %p\n",helements);
+	printf("   hmatpar: %p\n",hmatpar);
+	printf("   parameters: %p\n",parameters);
+	printf("   inputs: %p\n",inputs);
+	printf("   internal parameters: \n");
+	printf("   normal: %g|%g\n",normal[0],normal[1]);
+	printf("   length: %g\n",length);
+	printf("   penalty_lock: %i\n",penalty_lock);
+	printf("   active: %s\n",active ? "true":"false");
+	printf("   counter: %i\n",counter);
+	printf("   prestable: %s\n",prestable ? "true":"false");
+	printf("   material_converged: %s\n",material_converged ? "true":"false");
+	printf("   fill: %i\n",fill);
+	printf("   friction: %g\n",friction);
+	printf("   fraction: %g\n",fraction);
+	printf("   fractionincrement: %g\n",fractionincrement);
+	printf("   state: %i\n",state);
+	printf("   frozen: %s\n",frozen ? "true":"false");
+		
+}
+/*}}}1*/
+/*FUNCTION Riftfront::DeepEcho{{{1*/
+void Riftfront::DeepEcho(void){
+
+	printf("Riftfront:\n");
+	printf("   id: %i\n",id);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	hnodes->DeepEcho();
+	helements->DeepEcho();
+	hmatpar->DeepEcho();
+	printf("   parameters\n");
+	if(parameters)parameters->DeepEcho();
+	printf("   inputs\n");
+	if(inputs)inputs->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION Riftfront::Id {{{1*/
+int    Riftfront::Id(void){ return id; }
+/*}}}1*/
+/*FUNCTION Riftfront::MyRank {{{1*/
+int    Riftfront::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}1*/
+#ifdef _SERIAL_
+/*FUNCTION Riftfront::Marshall {{{1*/
+void  Riftfront::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+	char* marshalled_inputs=NULL;
+	int   marshalled_inputs_size;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of Riftfront: */
+	enum_type=RiftfrontEnum;
+
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+
+	/*marshall Riftfront data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&analysis_type,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+	memcpy(marshalled_dataset,&active,sizeof(active));marshalled_dataset+=sizeof(active);
+	memcpy(marshalled_dataset,&normal,sizeof(normal));marshalled_dataset+=sizeof(normal);
+	memcpy(marshalled_dataset,&length,sizeof(length));marshalled_dataset+=sizeof(length);
+	memcpy(marshalled_dataset,&fraction,sizeof(fraction));marshalled_dataset+=sizeof(fraction);
+	memcpy(marshalled_dataset,&frozen,sizeof(frozen));marshalled_dataset+=sizeof(frozen);
+	memcpy(marshalled_dataset,&state,sizeof(state));marshalled_dataset+=sizeof(state);
+	memcpy(marshalled_dataset,&counter,sizeof(counter));marshalled_dataset+=sizeof(counter);
+	memcpy(marshalled_dataset,&prestable,sizeof(prestable));marshalled_dataset+=sizeof(prestable);
+	memcpy(marshalled_dataset,&penalty_lock,sizeof(penalty_lock));marshalled_dataset+=sizeof(penalty_lock);
+	memcpy(marshalled_dataset,&material_converged,sizeof(material_converged));marshalled_dataset+=sizeof(material_converged);
+
+	/*Marshall hooks: */
+	hnodes->Marshall(&marshalled_dataset);
+	helements->Marshall(&marshalled_dataset);
+	hmatpar->Marshall(&marshalled_dataset);
+
+	/*Marshall inputs: */
+	marshalled_inputs_size=inputs->MarshallSize();
+	marshalled_inputs=inputs->Marshall();
+	memcpy(marshalled_dataset,marshalled_inputs,marshalled_inputs_size*sizeof(char));
+	marshalled_dataset+=marshalled_inputs_size;
+
+	/*parameters: don't do anything about it. parameters are marshalled somewhere else!*/
+
+	xfree((void**)&marshalled_inputs);
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+/*FUNCTION Riftfront::MarshallSize {{{1*/
+int   Riftfront::MarshallSize(){
+	
+	return sizeof(id)
+		+sizeof(analysis_type)
+		+sizeof(active)
+		+sizeof(normal)
+		+sizeof(length)
+		+sizeof(fraction)
+		+sizeof(frozen)
+		+sizeof(state)
+		+sizeof(counter)
+		+sizeof(prestable)
+		+sizeof(penalty_lock)
+		+sizeof(material_converged)
+		+hnodes->MarshallSize()
+		+helements->MarshallSize()
+		+hmatpar->MarshallSize()
+		+inputs->MarshallSize()
+		+sizeof(int); //sizeof(int) for enum type
+}
+/*}}}*/
+/*FUNCTION Riftfront::Demarshall {{{1*/
+void  Riftfront::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&analysis_type,marshalled_dataset,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+	memcpy(&active,marshalled_dataset,sizeof(active));marshalled_dataset+=sizeof(active);
+	memcpy(&normal,marshalled_dataset,sizeof(normal));marshalled_dataset+=sizeof(normal);
+	memcpy(&length,marshalled_dataset,sizeof(length));marshalled_dataset+=sizeof(length);
+	memcpy(&fraction,marshalled_dataset,sizeof(fraction));marshalled_dataset+=sizeof(fraction);
+	memcpy(&frozen,marshalled_dataset,sizeof(frozen));marshalled_dataset+=sizeof(frozen);
+	memcpy(&state,marshalled_dataset,sizeof(state));marshalled_dataset+=sizeof(state);
+	memcpy(&counter,marshalled_dataset,sizeof(counter));marshalled_dataset+=sizeof(counter);
+	memcpy(&prestable,marshalled_dataset,sizeof(prestable));marshalled_dataset+=sizeof(prestable);
+	memcpy(&penalty_lock,marshalled_dataset,sizeof(penalty_lock));marshalled_dataset+=sizeof(penalty_lock);
+	memcpy(&material_converged,marshalled_dataset,sizeof(material_converged));marshalled_dataset+=sizeof(material_converged);
+
+	/*demarshall hooks: */
+	hnodes=new Hook();    hnodes->Demarshall(&marshalled_dataset);
+	helements=new Hook(); helements->Demarshall(&marshalled_dataset);
+	hmatpar=new Hook();   hmatpar->Demarshall(&marshalled_dataset);
+
+	/*pointers are garbabe, until configuration is carried out: */
+	nodes=NULL;
+	elements=NULL;
+	matpar=NULL;
+	
+	/*demarshall inputs: */
+	inputs=(Inputs*)DataSetDemarshallRaw(&marshalled_dataset); 
+
+	/*parameters: may not exist even yet, so let Configure handle it: */
+	this->parameters=NULL;
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+#endif
+/*FUNCTION Riftfront::ObjectEnum{{{1*/
+int Riftfront::ObjectEnum(void){
+
+	return RiftfrontEnum;
+
+}
+/*}}}1*/
+/*FUNCTION Riftfront::copy {{{1*/
+Object* Riftfront::copy() {
+	
+	Riftfront* riftfront=NULL;
+
+	riftfront=new Riftfront();
+
+	/*copy fields: */
+	riftfront->id=this->id;
+	riftfront->analysis_type=this->analysis_type;
+	if(this->inputs){
+		riftfront->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		riftfront->inputs=new Inputs();
+	}
+	/*point parameters: */
+	riftfront->parameters=this->parameters;
+
+	/*now deal with hooks and objects: */
+	riftfront->hnodes=(Hook*)this->hnodes->copy();
+	riftfront->helements=(Hook*)this->helements->copy();
+	riftfront->hmatpar=(Hook*)this->hmatpar->copy();
+
+	/*corresponding fields*/
+	riftfront->nodes   =(Node**)riftfront->hnodes->deliverp();
+	riftfront->elements=(Element**)riftfront->helements->deliverp();
+	riftfront->matpar  =(Matpar*)riftfront->hmatpar->delivers();
+
+	/*internal data: */
+	riftfront->penalty_lock=this->penalty_lock;
+	riftfront->active=this->active;
+	riftfront->frozen=this->frozen;
+	riftfront->state=this->state;
+	riftfront->counter=this->counter;
+	riftfront->prestable=this->prestable;
+	riftfront->material_converged=this->material_converged;
+	riftfront->normal[0]=this->normal[0];
+	riftfront->normal[1]=this->normal[1];
+	riftfront->length=this->length;
+	riftfront->fraction=this->fraction;
+	
+	return riftfront;
+
+}
+/*}}}*/
+		
+/*Update virtual functions definitions:*/
+/*FUNCTION Riftfront::InputUpdateFromConstant(bool constant,int name) {{{1*/
+void  Riftfront::InputUpdateFromConstant(bool constant,int name){
+
+	/*Check that name is a Riftfront input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new BoolInput(name,constant));
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::InputUpdateFromConstant(double constant,int name) {{{1*/
+void  Riftfront::InputUpdateFromConstant(double constant,int name){
+
+	/*Check that name is a Riftfront input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new DoubleInput(name,constant));
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::InputUpdateFromConstant(double* constant,int name) {{{1*/
+void    Riftfront::InputUpdateFromVector(double* vector, int name, int type){
+
+	/*Check that name is a Riftfront input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	_error_("not implemented yet");
+	//this->inputs->AddInput(new DoubleInput(name,constant));
+
+}
+/*}}}*/
+
+
+/*Load virtual functions definitions:*/
+/*FUNCTION Riftfront::Configure {{{1*/
+void  Riftfront::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	hnodes->configure(nodesin);
+	helements->configure(elementsin);
+	hmatpar->configure(materialsin);
+
+	/*Initialize hooked fields*/
+	this->nodes   =(Node**)hnodes->deliverp();
+	this->elements=(Element**)helements->deliverp();
+	this->matpar  =(Matpar*)hmatpar->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::SetCurrentConfiguration {{{1*/
+void  Riftfront::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::PenaltyCreateKMatrix {{{1*/
+void  Riftfront::PenaltyCreateKMatrix(Mat Kff, Mat Kfs,double kmax){
+
+	/*Retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case DiagnosticHorizAnalysisEnum:
+			Ke=PenaltyCreateKMatrixDiagnosticHoriz(kmax);
+			break;
+		case AdjointHorizAnalysisEnum:
+			Ke=PenaltyCreateKMatrixDiagnosticHoriz(kmax);
+			break;
+		default:
+			_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+
+	/*Add to global Vector*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}1*/
+/*FUNCTION Riftfront::PenaltyCreatePVector {{{1*/
+void  Riftfront::PenaltyCreatePVector(Vec pf,double kmax){
+
+	/*Retrieve parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case DiagnosticHorizAnalysisEnum:
+			pe=PenaltyCreatePVectorDiagnosticHoriz(kmax);
+			break;
+		case AdjointHorizAnalysisEnum:
+			/*No penalty applied on load vector*/
+			break;
+		default:
+			_error_("analysis %i (%s) not supported yet",analysis_type,EnumToStringx(analysis_type));
+	}
+
+	/*Add to global Vector*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}1*/
+/*FUNCTION Riftfront::CreateKMatrix {{{1*/
+void  Riftfront::CreateKMatrix(Mat Kff, Mat Kfs){
+	/*do nothing: */
+	return;
+}
+/*}}}1*/
+/*FUNCTION Riftfront::CreatePVector {{{1*/
+void  Riftfront::CreatePVector(Vec pf){
+	/*do nothing: */
+	return;
+}
+/*}}}1*/
+/*FUNCTION Riftfront::InAnalysis{{{1*/
+bool Riftfront::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+
+/*Riftfront numerics*/
+/*FUNCTION Riftfront::PenaltyCreateKMatrixDiagnosticHoriz {{{1*/
+ElementMatrix* Riftfront::PenaltyCreateKMatrixDiagnosticHoriz(double kmax){
+
+	const int   numdof = NDOF2*NUMVERTICES;
+	int         i,j;
+	int         dofs[1]             = {0};
+	double      Ke_gg[4][4];
+	double      thickness;
+	double      h[2];
+	double      penalty_offset;
+	double      friction;
+
+	/*Objects: */
+	Tria       *tria1               = NULL;
+	Tria       *tria2               = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_(" only Tria element allowed for Riftfront load!");
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*Initialize Element Matrix*/
+	if(!this->active) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*Get some parameters: */
+	this->parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
+	this->inputs->GetInputValue(&friction,FrictionEnum);
+	tria1->GetInputValue(&h[0],nodes[0],ThicknessEnum);
+	tria2->GetInputValue(&h[1],nodes[1],ThicknessEnum);
+	if (h[0]!=h[1])_error_(" different thicknesses not supported for rift fronts");
+	thickness=h[0];
+
+	/*There is contact, we need to constrain the normal velocities (zero penetration), and the 
+	 *contact slip friction. */
+
+	/*From Peter Wriggers book (Computational Contact Mechanics, p191): */
+	Ke->values[0*numdof+0]+= +pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[0*numdof+1]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[0*numdof+2]+= -pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[0*numdof+3]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+
+	Ke->values[1*numdof+0]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[1*numdof+1]+= +pow(normal[1],2)*kmax*pow(10,penalty_offset);
+	Ke->values[1*numdof+2]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[1*numdof+3]+= -pow(normal[1],2)*kmax*pow(10,penalty_offset);
+
+	Ke->values[2*numdof+0]+= -pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[2*numdof+1]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[2*numdof+2]+= +pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[2*numdof+3]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+
+	Ke->values[3*numdof+0]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[3*numdof+1]+= -pow(normal[1],2)*kmax*pow(10,penalty_offset);
+	Ke->values[3*numdof+2]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[3*numdof+3]+= +pow(normal[1],2)*kmax*pow(10,penalty_offset);
+
+	/*Now take care of the friction: of type sigma=frictiontangent_velocity2-tangent_velocity1)*/
+
+	Ke->values[0*numdof+0]+= +pow(normal[1],2)*thickness*length*friction;
+	Ke->values[0*numdof+1]+= -normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[0*numdof+2]+= -pow(normal[1],2)*thickness*length*friction;
+	Ke->values[0*numdof+3]+= +normal[0]*normal[1]*thickness*length*friction;
+
+	Ke->values[1*numdof+0]+= -normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[1*numdof+1]+= +pow(normal[0],2)*thickness*length*friction;
+	Ke->values[1*numdof+2]+= +normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[1*numdof+3]+= -pow(normal[0],2)*thickness*length*friction;
+
+	Ke->values[2*numdof+0]+= -pow(normal[1],2)*thickness*length*friction;
+	Ke->values[2*numdof+1]+= +normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[2*numdof+2]+= +pow(normal[1],2)*thickness*length*friction;
+	Ke->values[2*numdof+3]+= -normal[0]*normal[1]*thickness*length*friction;
+
+	Ke->values[3*numdof+0]+= +normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[3*numdof+1]+= -pow(normal[0],2)*thickness*length*friction;
+	Ke->values[3*numdof+2]+= -normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[3*numdof+3]+= +pow(normal[0],2)*thickness*length*friction;
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}1*/
+/*FUNCTION Riftfront::PenaltyCreatePVectorDiagnosticHoriz {{{1*/
+ElementVector* Riftfront::PenaltyCreatePVectorDiagnosticHoriz(double kmax){
+
+	const int   numdof = NDOF2*NUMVERTICES;
+	int         i,j;
+	double      rho_ice;
+	double      rho_water;
+	double      gravity;
+	double      thickness;
+	double      h[2];
+	double      bed;
+	double      b[2];
+	double      pressure;
+	double      pressure_litho;
+	double      pressure_air;
+	double      pressure_melange;
+	double      pressure_water;
+	int         fill;
+	bool        shelf;
+
+	/*Objects: */
+	Tria       *tria1               = NULL;
+	Tria       *tria2               = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_(" only Tria element allowed for Riftfront load!");
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*Initialize Element Matrix*/
+	if(this->active) return NULL; /*The penalty is active. No loads implied here.*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Get some inputs: */
+	this->inputs->GetInputValue(&fill,FillEnum);
+	this->inputs->GetInputValue(&shelf,SegmentOnIceShelfEnum);
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+	gravity=matpar->GetG();
+	tria1->GetInputValue(&h[0],nodes[0],ThicknessEnum);
+	tria2->GetInputValue(&h[1],nodes[1],ThicknessEnum);
+	if (h[0]!=h[1])_error_(" different thicknesses not supported for rift fronts");
+	thickness=h[0];
+	tria1->GetInputValue(&b[0],nodes[0],BedEnum);
+	tria2->GetInputValue(&b[1],nodes[1],BedEnum);
+	if (b[0]!=b[1])_error_(" different beds not supported for rift fronts");
+	bed=b[0];
+
+	/*Ok, this rift is opening. We should put loads on both sides of the rift flanks. Because we are dealing with contact mechanics, 
+	 * and we want to avoid zigzagging of the loads, we want lump the loads onto nodes, not onto surfaces between nodes.:*/
+
+	/*Ok, to compute the pressure, we are going to need material properties, thickness and bed for the two nodes. We assume those properties to 
+	 * be the same across the rift.: */
+
+	/*Ok, now compute the pressure (in norm) that is being applied to the flanks, depending on the type of fill: */
+	if(fill==WaterEnum){
+		if(shelf){
+			/*We are on an ice shelf, hydrostatic equilibrium is used to determine the pressure for water fill: */
+			pressure=rho_ice*gravity*pow(thickness,(double)2)/(double)2  - rho_water*gravity*pow(bed,(double)2)/(double)2; 
+		}
+		else{
+			//We are on an icesheet, we assume the water column fills the entire front: */
+			pressure=rho_ice*gravity*pow(thickness,(double)2)/(double)2  - rho_water*gravity*pow(thickness,(double)2)/(double)2; 
+		}
+	}
+	else if(fill==AirEnum){
+		pressure=rho_ice*gravity*pow(thickness,(double)2)/(double)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_("%s%i%s","fill type ",fill," not supported on ice sheets yet.");
+
+		pressure_litho=rho_ice*gravity*pow(thickness,(double)2)/(double)2;
+		pressure_air=0;
+		pressure_melange=rho_ice*gravity*pow(fraction*thickness,(double)2)/(double)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_("%s%i%s","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;
+}
+/*}}}1*/
+/*FUNCTION Riftfront::Constrain {{{1*/
+#define _ZIGZAGCOUNTER_
+
+int Riftfront::Constrain(int* punstable){
+
+	const int   numnodes        = 2;
+	double      max_penetration;
+	double      penetration;
+	int         activate;
+	int         found;
+	int         unstable;
+	double      vx1;
+	double      vy1;
+	double      vx2;
+	double      vy2;
+	double      fractionincrement;
+
+	/*Objects: */
+	Tria       *tria1           = NULL;
+	Tria       *tria2           = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_(" only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*Is this constraint frozen? In which case we don't touch: */
+	if (this->frozen){
+		*punstable=0;
+		return 1;
+	}
+
+	/*Is this rift segment state specified by user input? :*/
+	if (this->state==OpenEnum || this->state==ClosedEnum){
+
+		if(this->state==OpenEnum)this->active=0;
+		if(this->state==ClosedEnum)this->active=1;
+		
+		/*this segment is like frozen, no instability here: */
+		*punstable=0;
+		return 1;
+	}
+
+
+	/*recover parameters: */
+	this->inputs->GetInputValue(&fractionincrement,FractionIncrementEnum);
+
+	/*First recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*activation: */
+	if(penetration<0)activate=1;
+	else  activate=0;
+
+	/*Here, we try to avoid zigzaging. When a penalty activates and deactivates for more than penalty_lock times, 
+	 * we increase the fraction of melange:*/
+	if(this->counter>this->penalty_lock){
+		/*reset counter: */
+		this->counter=0;
+		/*increase melange fraction: */
+		this->fraction+=fractionincrement;
+		if (this->fraction>1)this->fraction=(double)1.0;
+		//printf("riftfront %i fraction: %g\n",this->Id(),this->fraction);
+	}
+
+	//Figure out stability of this penalty
+	if(this->active==activate){
+		unstable=0;
+	}
+	else{
+		unstable=1;
+		this->counter++;
+	}
+
+	//Set penalty flag
+	this->active=activate;
+
+	//if ((penetration>0) && (this->active==1))printf("Riftfront %i wants to be released\n",Id());
+
+	/*assign output pointer: */
+	*punstable=unstable;
+	return 1;
+}
+/*}}}1*/
+/*FUNCTION Riftfront::FreezeConstraints{{{1*/
+void   Riftfront::FreezeConstraints(void){
+
+	/*Just set frozen flag to 1: */
+	this->frozen=1;
+
+}
+/*}}}1*/
+/*FUNCTION Riftfront::IsFrozen{{{1*/
+bool   Riftfront::IsFrozen(void){
+
+	/*Just set frozen flag to 1: */
+	if(this->frozen)return 1;
+	else return 0;
+}
+/*}}}1*/
+/*FUNCTION Riftfront::IsMaterialStable {{{1*/
+int   Riftfront::IsMaterialStable(void){
+
+	int found=0;
+	double converged=0;
+
+	this->inputs->GetInputValue(&converged,ConvergedEnum);
+
+	if(converged){
+		/*ok, material non-linearity has converged. If that was already the case, we keep 
+		 * constraining the rift front. If it was not, and this is the first time the material 
+		 * has converged, we start constraining now!: */
+		this->material_converged=1;
+	}
+
+	return this->material_converged;
+}
+/*}}}1*/
+/*FUNCTION Riftfront::MaxPenetration {{{1*/
+int   Riftfront::MaxPenetration(double* ppenetration){
+
+	const int     numnodes=2;
+	double        max_penetration;
+	double        penetration=0;
+	int           found;
+	double      vx1;
+	double      vy1;
+	double      vx2;
+	double      vy2;
+
+	/*Objects: */
+	Tria       *tria1           = NULL;
+	Tria       *tria2           = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_(" only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	//initialize: 
+	penetration=-1;
+
+	/*recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node1 faces node2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*Now, we return penetration only if we are active!: */
+	if(this->active==0)penetration=-1;
+
+	/*If we are zigzag locked, same thing: */
+	if(this->counter>this->penalty_lock)penetration=-1;
+	
+	/*assign output pointer: */
+	*ppenetration=penetration;
+	return 1;
+}
+/*}}}1*/
+/*FUNCTION Riftfront::Penetration {{{1*/
+int   Riftfront::Penetration(double* ppenetration){
+
+	double    vx1;
+	double    vy1;
+	double    vx2;
+	double    vy2;
+
+	double    penetration;
+	int       found;
+
+	/*Objects: */
+	Tria     *tria1       = NULL;
+	Tria     *tria2       = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_(" only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*First recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*Now, we return penetration only if we are active!: */
+	if(this->active==0)penetration=0;
+	
+	/*assign output pointer: */
+	*ppenetration=penetration;
+	return 1;
+}
+/*}}}1*/
+/*FUNCTION Riftfront::PotentialUnstableConstraint {{{1*/
+int   Riftfront::PotentialUnstableConstraint(int* punstable){
+
+
+	const int   numnodes        = 2;
+	double      max_penetration;
+	double      penetration;
+	int         activate;
+	int         unstable;
+	int         found;
+	double      vx1;
+	double      vy1;
+	double      vx2;
+	double      vy2;
+
+	/*Objects: */
+	Tria       *tria1           = NULL;
+	Tria       *tria2           = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_(" only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*First recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*Ok, we are looking for positive penetration in an active constraint: */
+	if(this->active){
+		if (penetration>=0){
+			unstable=1;
+		}
+		else{
+			unstable=0;
+		}
+	}
+	else{
+		unstable=0;
+	}
+
+	/*assign output pointer: */
+	*punstable=unstable;
+	return 1;
+}
+/*}}}1*/
+/*FUNCTION Riftfront::PreConstrain {{{1*/
+int   Riftfront::PreConstrain(int* punstable){
+
+	const int   numnodes    = 2;
+	double      penetration;
+	int         unstable;
+	int         found;
+	double      vx1;
+	double      vy1;
+	double      vx2;
+	double      vy2;
+
+	/*Objects: */
+	Tria       *tria1       = NULL;
+	Tria       *tria2       = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_(" only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*First recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*Ok, we are preconstraining here. Ie, anything that penetrates is constrained until stability of the entire set 
+	 * of constraints is reached.: */
+	if(penetration<0){
+		if (!this->active){
+			/*This is the first time penetration happens: */
+			this->active=1;
+			unstable=1;
+		}
+		else{
+			/*This constraint was already active: */
+			this->active=1;
+			unstable=0;
+		}
+	}
+	else{
+		/*No penetration happening. : */
+		if (!this->active){
+			/*This penalty was not active, and no penetration happening. Do nonthing: */
+			this->active=0;
+			unstable=0; 
+		}
+		else{
+			/*Ok, this penalty wants to get released. But not now, this is preconstraint, not constraint: */
+			this->active=1;
+			unstable=0;
+		}
+	}
+
+	/*assign output pointer: */
+	*punstable=unstable;
+	return 1;
+}
+/*}}}1*/
+/*FUNCTION Riftfront::PreStable {{{1*/
+bool  Riftfront::PreStable(){
+	return prestable;
+}
+/*}}}1*/
+/*FUNCTION Riftfront::SetPreStable {{{1*/
+void Riftfront::SetPreStable(){
+	prestable=1;
+}
+/*}}}1*/
+/*FUNCTION Riftfront::IsInput{{{1*/
+bool Riftfront::IsInput(int name){
+	if (
+				name==ConvergedEnum ||
+				name==ThicknessEnum ||
+				name==SurfaceEnum ||
+				name==BedEnum 
+		){
+		return true;
+	}
+	else return false;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Loads/Riftfront.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Loads/Riftfront.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Loads/Riftfront.h	(revision 11330)
@@ -0,0 +1,107 @@
+/*!\file Riftfront.h
+ * \brief: header file for riftfront object
+ */
+
+#ifndef _RIFTFRONT_H_
+#define _RIFTFRONT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Load.h"
+class Hook;
+class Parameters;
+class Inputs;
+class IoModel;
+/*}}}*/
+
+class Riftfront: public Load {
+
+	public:
+		int		id;
+		int     analysis_type;
+
+		/*hooks: */
+		Hook* hnodes;
+		Hook* helements;
+		Hook* hmatpar;
+		
+		/*Corresponding fields*/
+		Matpar   *matpar;
+		Node    **nodes;
+		Element **elements;
+
+		/*computational: */
+		int      penalty_lock;
+		bool     active;
+		bool     frozen;
+		int      counter;
+		bool     prestable;
+		bool     material_converged;
+		double   normal[2];
+		double   length;
+		double   fraction;
+		int      state;
+		
+		Parameters* parameters; //pointer to solution parameters
+		Inputs*  inputs;
+
+
+		/*Riftfrontconstructors,destructors: {{{1*/
+		Riftfront();
+		Riftfront(int riftfront_id,int i, IoModel* iomodel,int analysis_type);
+		~Riftfront();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{1*/
+		void    InputUpdateFromVector(double* vector, int name, int type);
+		void    InputUpdateFromVector(int* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVector(bool* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromMatrixDakota(double* matrix, int nrows,int ncols, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(double* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(int* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(bool* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromConstant(double constant, int name);
+		void    InputUpdateFromConstant(int constant, int name){_error_("Not implemented yet!");}
+		void    InputUpdateFromConstant(bool constant, int name);
+		void    InputUpdateFromSolution(double* solution){_error_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+		/*Load virtual functions definitions: {{{1*/
+		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(Mat Kff, Mat Kfs);
+		void  CreatePVector(Vec pf);
+		void  PenaltyCreateKMatrix(Mat Kff, Mat kfs, double kmax);
+		void  PenaltyCreatePVector(Vec pf, double kmax);
+		bool  InAnalysis(int analysis_type);
+		/*}}}*/
+		/*Riftfront specific routines: {{{1*/
+		bool  PreStable();
+		ElementMatrix* PenaltyCreateKMatrixDiagnosticHoriz(double kmax);
+		ElementVector* PenaltyCreatePVectorDiagnosticHoriz(double kmax);
+		void  SetPreStable();
+		int   PreConstrain(int* punstable);
+		int   Constrain(int* punstable);
+		void  FreezeConstraints(void);
+		bool  IsFrozen(void);
+		int   Penetration(double* ppenetration);
+		int   MaxPenetration(double* ppenetration);
+		int   PotentialUnstableConstraint(int* punstable);
+		int   IsMaterialStable(void);
+		bool  IsInput(int name);
+		/*}}}*/
+};
+
+#endif  /* _RIFTFRONT_H_ */
Index: /issm/trunk-jpl-damage/src/c/objects/Materials/Material.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Materials/Material.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Materials/Material.h	(revision 11330)
@@ -0,0 +1,27 @@
+/*!\file:  Material.h
+ * \brief abstract class for Material object
+ */ 
+
+
+#ifndef _MATERIAL_H_
+#define _MATERIAL_H_
+
+/*Headers:*/
+/*{{{1*/
+class Object;
+#include "../Object.h"
+#include "../../toolkits/toolkits.h"
+/*}}}*/
+
+class Material: public Object,public Update{
+
+	public: 
+		virtual       ~Material(){};
+
+		/*Numerics*/
+		virtual void   InputDuplicate(int original_enum,int new_enum)=0;
+		virtual void   Configure(Elements* elements)=0;
+		virtual void   GetVectorFromInputs(Vec vector,int input_enum)=0;
+
+};
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Materials/Matice.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Materials/Matice.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Materials/Matice.cpp	(revision 11330)
@@ -0,0 +1,774 @@
+/*!\file Matice.c
+ * \brief: implementation of the Matice object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+		
+/*Matice constructors and destructor*/
+/*FUNCTION Matice::Matice(){{{1*/
+Matice::Matice(){
+	this->inputs=NULL;
+	this->helement=NULL;
+	return;
+}
+/*}}}*/
+/*FUNCTION Matice::Matice(int id, int index, IoModel* iomodel, int num_vertices){{{1*/
+Matice::Matice(int matice_mid,int index, IoModel* iomodel){
+
+	/*Intermediaries:*/
+	int    i;
+	int    matice_eid;
+
+	/*Initialize id*/
+	this->mid=matice_mid;
+
+	/*Initialize inputs*/
+	this->inputs=new Inputs();
+
+	/*Initialize inputs from IoModel*/
+	this->InputUpdateFromIoModel(index,iomodel);
+
+	/*Hooks: */
+	matice_eid=index+1;
+	this->helement=new Hook(&matice_eid,1);
+
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Matice::~Matice(){{{1*/
+Matice::~Matice(){
+	delete helement;
+	delete inputs;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Matice::Echo {{{1*/
+void Matice::Echo(void){
+
+	printf("Matice:\n");
+	printf("   mid: %i\n",mid);
+	printf("   inputs:\n");
+	inputs->Echo();
+	printf("   element:\n");
+	helement->Echo();
+}
+/*}}}*/
+/*FUNCTION Matice::DeepEcho {{{1*/
+void Matice::DeepEcho(void){
+
+	printf("Matice:\n");
+	printf("   mid: %i\n",mid);
+	printf("   inputs:\n");
+	inputs->DeepEcho();
+	printf("   element:\n");
+	helement->Echo();
+}		
+/*}}}*/
+/*FUNCTION Matice::Id {{{1*/
+int    Matice::Id(void){ return mid; }
+/*}}}*/
+/*FUNCTION Matice::MyRank {{{1*/
+int    Matice::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION Matice::Marshall {{{1*/
+void  Matice::Marshall(char** pmarshalled_dataset){
+
+	/*Intermediaries*/
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+	char* marshalled_inputs=NULL;
+	int   marshalled_inputs_size;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of Matice: */
+	enum_type=MaticeEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*marshall Matice data: */
+	memcpy(marshalled_dataset,&mid,sizeof(mid));marshalled_dataset+=sizeof(mid);
+
+	/*Marshall hooks: */
+	helement->Marshall(&marshalled_dataset);
+
+	/*Marshall inputs: */
+	marshalled_inputs_size=inputs->MarshallSize();
+	marshalled_inputs=inputs->Marshall();
+	memcpy(marshalled_dataset,marshalled_inputs,marshalled_inputs_size*sizeof(char));
+	marshalled_dataset+=marshalled_inputs_size;
+
+	*pmarshalled_dataset=marshalled_dataset;
+
+	/*clean up and return*/
+	xfree((void**)&marshalled_inputs);
+}
+/*}}}*/
+/*FUNCTION Matice::MarshallSize{{{1*/
+int   Matice::MarshallSize(){
+
+	return sizeof(mid)
+	  +helement->MarshallSize()
+	  +inputs->MarshallSize()
+	  +sizeof(int); //sizeof(int) for enum type
+}
+/*}}}*/
+/*FUNCTION Matice::Demarshall {{{1*/
+void  Matice::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&mid,marshalled_dataset,sizeof(mid));marshalled_dataset+=sizeof(mid);
+
+	/*demarshall hooks: */
+	helement=new Hook(); helement->Demarshall(&marshalled_dataset);
+
+	/*demarshall inputs: */
+	inputs=(Inputs*)DataSetDemarshallRaw(&marshalled_dataset); 
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION Matice::ObjectEnum{{{1*/
+int Matice::ObjectEnum(void){
+
+	return MaticeEnum;
+
+}
+/*}}}*/
+/*FUNCTION Matice::copy {{{1*/
+Object* Matice::copy() {
+
+	/*Output*/
+	Matice* matice=NULL;
+
+	/*Initialize output*/
+	matice=new Matice();
+
+	/*copy fields: */
+	matice->mid=this->mid;
+	matice->helement=(Hook*)this->helement->copy();
+	if(this->inputs) matice->inputs=(Inputs*)this->inputs->Copy();
+	else  matice->inputs=new Inputs();
+
+	return matice;
+}
+/*}}}*/
+
+/*Matice management*/
+/*FUNCTION Matice::Configure {{{1*/
+void  Matice::Configure(Elements* elementsin){
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	helement->configure(elementsin);
+}
+/*}}}*/
+/*FUNCTION Matice::SetCurrentConfiguration {{{1*/
+void  Matice::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}*/
+/*FUNCTION Matice::GetB {{{1*/
+double Matice::GetB(){
+
+	/*Output*/
+	double B;
+
+	inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	return B;
+}
+/*}}}*/
+/*FUNCTION Matice::GetBbar {{{1*/
+double Matice::GetBbar(){
+
+	/*Output*/
+	double Bbar;
+
+	inputs->GetInputAverage(&Bbar,MaterialsRheologyBbarEnum);
+	return Bbar;
+}
+/*}}}*/
+/*FUNCTION Matice::GetN {{{1*/
+double Matice::GetN(){
+
+	/*Output*/
+	double n;
+
+	inputs->GetInputAverage(&n,MaterialsRheologyNEnum);
+	return n;
+}
+/*}}}*/
+/*FUNCTION Matice::GetVectorFromInputs{{{1*/
+void  Matice::GetVectorFromInputs(Vec vector,int input_enum){
+
+	/*Intermediaries*/
+	Element *element= NULL;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that input_enum is a material input*/
+	if (!IsInput(input_enum)) return;
+
+	switch(element->ObjectEnum()){
+
+		case TriaEnum:{
+
+			/*Prepare index list*/
+			int doflist1[3];
+			for(int i=0;i<3;i++) doflist1[i]=((Tria*)element)->nodes[i]->GetVertexDof();
+
+			/*Get input (either in element or material)*/
+			Input* input=inputs->GetInput(input_enum);
+			if(!input) _error_("Input %s not found in material",EnumToStringx(input_enum));
+
+			/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
+			input->GetVectorFromInputs(vector,&doflist1[0]);}
+			break;
+
+		default: _error_("element %s not implemented yet",EnumToStringx(element->ObjectEnum()));
+	}
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosity2d {{{1*/
+void  Matice::GetViscosity2d(double* pviscosity, double* epsilon){
+	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
+												    B
+	  viscosity= -------------------------------------------------------------------
+						  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+
+	  where viscosity is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	  vector, and n the flow law exponent.
+
+	  If epsilon is NULL, it means this is the first time SystemMatrices is being run, and we 
+	  return 10^14, initial viscosity.
+	  */
+
+	/*output: */
+	double viscosity;
+
+	/*input strain rate: */
+	double exx,eyy,exy;
+
+	/*Intermediary: */
+	double A,e;
+	double B,n;
+
+	/*Get B and n*/
+	B=GetBbar();
+	n=GetN();
+
+	if (n==1){
+		/*Viscous behaviour! viscosity=B: */
+		viscosity=B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
+			viscosity=0.5*pow((double)10,(double)14);
+		}
+		else{
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			exy=*(epsilon+2);
+
+			/*Build viscosity: viscosity=B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+			if(A==0){
+				/*Maxiviscositym viscosity for 0 shear areas: */
+				viscosity=2.5*pow((double)10,(double)17);
+			}
+			else{
+				e=(n-1)/(2*n);
+				viscosity=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Return: */
+	*pviscosity=viscosity;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosity3d {{{1*/
+void  Matice::GetViscosity3d(double* pviscosity3d, double* epsilon){
+
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *                                               B
+	 * viscosity3d= -------------------------------------------------------------------
+	 *                      2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 *     where mu is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	 *     vector, and n the flow law exponent.
+	 *
+	 * If epsilon is NULL, it means this is the first time Emg is being run, and we 
+	 * return g, initial viscosity.
+	 */
+	
+	/*output: */
+	double viscosity3d;
+
+	/*input strain rate: */
+	double exx,eyy,exy,exz,eyz;
+
+	/*Intermediaries: */
+	double A,e;
+	double B,n;
+
+	/*Get B and n*/
+	B=GetB();
+	n=GetN();
+
+	if (n==1){
+		/*Viscous behaviour! viscosity3d=B: */
+		viscosity3d=B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
+				(epsilon[3]==0) && (epsilon[4]==0)){
+			viscosity3d=0.5*pow((double)10,(double)14);
+		}
+		else{
+
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			exy=*(epsilon+2);
+			exz=*(epsilon+3);
+			eyz=*(epsilon+4);
+
+			/*Build viscosity: viscosity3d=2*B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+pow(exz,2)+pow(eyz,2)+exx*eyy;
+			if(A==0){
+				/*Maxiviscosity3dm viscosity for 0 shear areas: */
+				viscosity3d=2.25*pow((double)10,(double)17);
+			}
+			else{
+				e=(n-1)/2/n;
+			
+				viscosity3d=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity3d<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Assign output pointers:*/
+	*pviscosity3d=viscosity3d;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosity3dStokes {{{1*/
+void  Matice::GetViscosity3dStokes(double* pviscosity3d, double* epsilon){
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *                                          B
+	 * viscosity3d= -------------------------------------------------------------------
+	 *                   2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 *     where mu is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	 *     vector, and n the flow law exponent.
+	 *
+	 * If epsilon is NULL, it means this is the first time Emg is being run, and we 
+	 * return g, initial viscosity.
+	 */
+	
+	/*output: */
+	double viscosity3d;
+
+	/*input strain rate: */
+	double exx,eyy,exy,exz,eyz,ezz;
+
+	/*Intermediaries: */
+	double A,e;
+	double B,n;
+	double eps0;
+
+	/*Get B and n*/
+	eps0=pow((double)10,(double)-27);
+	B=GetB();
+	n=GetN();
+	
+	if (n==1){
+		/*Viscous behaviour! viscosity3d=B: */
+		viscosity3d=B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
+				(epsilon[3]==0) && (epsilon[4]==0) && (epsilon[5]==0)){
+			viscosity3d=0.5*pow((double)10,(double)14);
+		}
+		else{
+
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			ezz=*(epsilon+2); //not used
+			exy=*(epsilon+3);
+			exz=*(epsilon+4);
+			eyz=*(epsilon+5);
+
+			/*Build viscosity: viscosity3d=B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+pow(exz,2)+pow(eyz,2)+exx*eyy+pow(eps0,2);
+			if(A==0){
+				/*Maxiviscosity3dm viscosity for 0 shear areas: */
+				viscosity3d=2.25*pow((double)10,(double)17);
+			}
+			else{
+				e=(n-1)/2/n;
+				viscosity3d=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity3d<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Assign output pointers:*/
+	*pviscosity3d=viscosity3d;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosityComplement {{{1*/
+void  Matice::GetViscosityComplement(double* pviscosity_complement, double* epsilon){
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *  										                1
+	 * viscosity= -------------------------------------------------------------------
+	 *  				  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 * If epsilon is NULL, it means this is the first time Gradjb is being run, and we 
+	 * return mu20, initial viscosity.
+	 */
+	
+	/*output: */
+	double viscosity_complement;
+
+	/*input strain rate: */
+	double exx,eyy,exy;
+
+	/*Intermediary value A and exponent e: */
+	double A,e;
+	double 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((double)10,(double)17);
+		}
+		else{
+			e=(n-1)/(2*n);
+		
+			viscosity_complement=1/(2*pow(A,e));
+		}
+	}
+	else{
+		viscosity_complement=4.5*pow((double)10,(double)17);
+	}
+
+	/*Checks in debugging mode*/
+	_assert_(B>0);
+	_assert_(n>0);
+	_assert_(viscosity_complement>0);
+		
+	/*Return: */
+	*pviscosity_complement=viscosity_complement;
+}
+/*}}}*/
+/*FUNCTION Matice::InputDuplicate{{{1*/
+void  Matice::InputDuplicate(int original_enum,int new_enum){
+
+	/*Call inputs method*/
+	if (IsInput(original_enum)) inputs->DuplicateInput(original_enum,new_enum);
+
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromVector(double* vector, int name, int type) {{{1*/
+void  Matice::InputUpdateFromVector(double* vector, int name, int type){
+
+	/*Intermediaries*/
+	Element *element      = NULL;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			switch(element->ObjectEnum()){
+
+				case TriaEnum:
+					double values[3];
+					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexDof()];
+					this->inputs->AddInput(new TriaP1Input(name,values));
+					return;
+
+				default: _error_("element %s not implemented yet",EnumToStringx(element->ObjectEnum()));
+			}
+		default: _error_("type %i (%s) not implemented yet",type,EnumToStringx(type));
+	}
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromVector(int* vector, int name, int type) {{{1*/
+void  Matice::InputUpdateFromVector(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromVector(bool* vector, int name, int type) {{{1*/
+void  Matice::InputUpdateFromVector(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromVectorDakota(double* vector, int name, int type) {{{1*/
+void  Matice::InputUpdateFromVectorDakota(double* vector, int name, int type){
+
+	/*Intermediaries*/
+	Element *element      = NULL;
+	Parameters* parameters= NULL;
+	int         dim;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			switch(element->ObjectEnum()){
+
+				case TriaEnum:
+					double values[3];
+					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetSidList()]; //use sid list, to index into serial oriented vector 
+					this->inputs->AddInput(new TriaP1Input(name,values));
+					/*Special case for rheology B in 2D: Pourave land for this solution{{{2*/
+					if(name==MaterialsRheologyBEnum){
+						/*Are we in 2D?:*/
+						if(element->ObjectEnum()==TriaEnum){
+							parameters=((Tria*)(element))->parameters;
+						}
+						else{
+							parameters=((Penta*)(element))->parameters;
+						}
+						parameters->FindParam(&dim,MeshDimensionEnum);
+						if(dim==2){
+							/*Dupliacte rheology input: */
+							this->inputs->AddInput(new TriaP1Input(MaterialsRheologyBbarEnum,values));
+						}
+					}
+					/*}}}*/
+					return;
+
+				default: _error_("element %s not implemented yet",EnumToStringx(element->ObjectEnum()));
+			}
+		default: _error_("type %i (%s) not implemented yet",type,EnumToStringx(type));
+	}
+
+
+
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromMatrixDakota(int* vector, int name, int type) {{{1*/
+void  Matice::InputUpdateFromMatrixDakota(double* matrix, int nrows, int ncols,int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromVectorDakota(int* vector, int name, int type) {{{1*/
+void  Matice::InputUpdateFromVectorDakota(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromVectorDakota(bool* vector, int name, int type) {{{1*/
+void  Matice::InputUpdateFromVectorDakota(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromConstant(double constant, int name) {{{1*/
+void  Matice::InputUpdateFromConstant(double constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromConstant(int constant, int name) {{{1*/
+void  Matice::InputUpdateFromConstant(int constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromConstant(bool constant, int name) {{{1*/
+void  Matice::InputUpdateFromConstant(bool constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromSolution{{{1*/
+void  Matice::InputUpdateFromSolution(double* solution){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromIoModel{{{1*/
+void Matice::InputUpdateFromIoModel(int index, IoModel* iomodel){
+
+	int i,j;
+
+	int    dim;
+	bool   control_analysis;
+	int    num_control_type;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
+
+	/*if 2d*/
+	if(dim==2){
+
+		/*Intermediaries*/
+		const int num_vertices = 3; //Tria has 3 vertices
+		double    nodeinputs[num_vertices];
+		double    cmmininputs[num_vertices];
+		double    cmmaxinputs[num_vertices];
+
+		/*Get B*/
+		if (iomodel->Data(MaterialsRheologyBEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
+			this->inputs->AddInput(new TriaP1Input(MaterialsRheologyBbarEnum,nodeinputs));
+		}
+
+		/*Get n*/
+		if (iomodel->Data(MaterialsRheologyNEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
+			this->inputs->AddInput(new TriaP1Input(MaterialsRheologyNEnum,nodeinputs));
+		}
+
+		/*Control Inputs*/
+		#ifdef _HAVE_CONTROL_
+		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+			for(i=0;i<num_control_type;i++){
+				switch((int)iomodel->Data(InversionControlParametersEnum)[i]){
+					case MaterialsRheologyBbarEnum:
+						if (iomodel->Data(MaterialsRheologyBEnum)){
+							_assert_(iomodel->Data(MaterialsRheologyBEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(MaterialsRheologyBbarEnum,TriaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						}
+						break;
+				}
+			}
+		}
+		#endif
+	}
+
+	/*if 3d*/
+	#ifdef _HAVE_THREED_
+	else if(dim==3){
+
+		/*Intermediaries*/
+		const int num_vertices = 6; //Penta has 6 vertices
+		double    nodeinputs[num_vertices];
+		double    cmmininputs[num_vertices];
+		double    cmmaxinputs[num_vertices];
+
+		/*Get B*/
+		if (iomodel->Data(MaterialsRheologyBEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
+			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,nodeinputs));
+		}
+
+		/*Get n*/
+		if (iomodel->Data(MaterialsRheologyNEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
+			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyNEnum,nodeinputs));
+		}
+
+		/*Control Inputs*/
+		#ifdef _HAVE_CONTROL_
+		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+			for(i=0;i<num_control_type;i++){
+				switch((int)iomodel->Data(InversionControlParametersEnum)[i]){
+					case MaterialsRheologyBbarEnum:
+						if (iomodel->Data(MaterialsRheologyBEnum)){
+							_assert_(iomodel->Data(MaterialsRheologyBEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						}
+						break;
+				}
+			}
+		}
+		#endif
+	}
+	#endif
+	else{
+		_error_(" Mesh type not supported yet!");
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Matice::IsInput{{{1*/
+bool Matice::IsInput(int name){
+	if (
+				name==MaterialsRheologyBEnum ||
+				name==MaterialsRheologyBbarEnum ||
+				name==MaterialsRheologyNEnum
+		){
+		return true;
+	}
+	else return false;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Materials/Matice.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Materials/Matice.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Materials/Matice.h	(revision 11330)
@@ -0,0 +1,77 @@
+/*!\file Matice.h
+ * \brief: header file for matice object
+ */
+
+#ifndef MATICE_H_
+#define MATICE_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Material.h"
+class IoModel;
+/*}}}*/
+
+class Matice: public Material{
+
+	private: 
+		/*Id*/
+		int	   mid;
+
+		/*hooks: */
+		Hook* helement;
+
+	public:
+		/*WARNING: input should not be public but it is an easy way to update B from T (using UpdateFromSolution) from Pentas*/
+		Inputs*  inputs;
+
+		/*Matice constructors, destructors: {{{1*/
+		Matice();
+		Matice(int mid,int i, IoModel* iomodel);
+		~Matice();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Update virtual functions definitions: {{{1*/
+		void  InputUpdateFromVector(double* vector, int name, int type);
+		void  InputUpdateFromVector(int* vector, int name, int type);
+		void  InputUpdateFromVector(bool* vector, int name, int type);
+		void  InputUpdateFromMatrixDakota(double* matrix, int nrow, int ncols, int name, int type);
+		void  InputUpdateFromVectorDakota(double* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
+		void  InputUpdateFromConstant(double constant, int name);
+		void  InputUpdateFromConstant(int constant, int name);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromSolution(double* solution);
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
+		/*}}}*/
+		/*Material virtual functions resolution: {{{1*/
+		void   InputDuplicate(int original_enum,int new_enum);
+		void   Configure(Elements* elements);
+		void   GetVectorFromInputs(Vec vector,int input_enum);
+		/*}}}*/
+		/*Matice Numerics: {{{1*/
+		void   SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin);
+		void   GetViscosity2d(double* pviscosity, double* pepsilon);
+		void   GetViscosity3d(double* pviscosity3d, double* pepsilon);
+		void   GetViscosity3dStokes(double* pviscosity3d, double* epsilon);
+		void   GetViscosityComplement(double* pviscosity_complement, double* pepsilon);
+		double GetB();
+		double GetBbar();
+		double GetN();
+		bool   IsInput(int name);
+		/*}}}*/
+};
+
+#endif  /* _MATICE_H_ */
Index: /issm/trunk-jpl-damage/src/c/objects/Materials/Matpar.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Materials/Matpar.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Materials/Matpar.cpp	(revision 11330)
@@ -0,0 +1,462 @@
+/*!\file Matpar.c
+ * \brief: implementation of the Matpar object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+		
+/*Matpar constructors and destructor*/
+/*FUNCTION Matpar::Matpar() {{{1*/
+Matpar::Matpar(){
+	return;
+}
+/*}}}1*/
+/*FUNCTION Matpar::Matpar(int matpar_mid,IoModel* iomodel){{{1*/
+Matpar::Matpar(int matpar_mid, IoModel* iomodel){
+
+	this->mid                       = matpar_mid;
+	iomodel->Constant(&this->rho_ice,MaterialsRhoIceEnum);
+	iomodel->Constant(&this->rho_water,MaterialsRhoWaterEnum);
+	iomodel->Constant(&this->mu_water,MaterialsMuWaterEnum);
+	iomodel->Constant(&this->heatcapacity,MaterialsHeatcapacityEnum);
+	iomodel->Constant(&this->thermalconductivity,MaterialsThermalconductivityEnum);
+	iomodel->Constant(&this->latentheat,MaterialsLatentheatEnum);
+	iomodel->Constant(&this->beta,MaterialsBetaEnum);
+	iomodel->Constant(&this->meltingpoint,MaterialsMeltingpointEnum);
+	iomodel->Constant(&this->referencetemperature,ConstantsReferencetemperatureEnum);
+	iomodel->Constant(&this->mixed_layer_capacity,MaterialsMixedLayerCapacityEnum);
+	iomodel->Constant(&this->thermal_exchange_velocity,MaterialsThermalExchangeVelocityEnum);
+	iomodel->Constant(&this->g,ConstantsGEnum);
+	
+	iomodel->Constant(&this->hydro_CR,HydrologyCREnum);
+	iomodel->Constant(&this->kn,HydrologyKnEnum);
+	iomodel->Constant(&this->hydro_n,HydrologyNEnum);
+	iomodel->Constant(&this->hydro_p,HydrologyPEnum);
+	iomodel->Constant(&this->hydro_q,HydrologyQEnum);
+}
+/*}}}1*/
+/*FUNCTION Matpar::~Matpar() {{{1*/
+Matpar::~Matpar(){
+	return;
+}
+/*}}}1*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Matpar::Echo {{{1*/
+void Matpar::Echo(void){
+
+	printf("Matpar:\n");
+	printf("   mid: %i\n",mid);
+	printf("   rho_ice: %g\n",rho_ice);
+	printf("   rho_water: %g\n",rho_water);
+	printf("   mu_water: %g\n",mu_water);
+	printf("   heatcapacity: %g\n",heatcapacity);
+	printf("   thermalconductivity: %g\n",thermalconductivity);
+	printf("   latentheat: %g\n",latentheat);
+	printf("   beta: %g\n",beta);
+	printf("   meltingpoint: %g\n",meltingpoint);
+	printf("   referencetemperature: %g\n",referencetemperature);
+	printf("   mixed_layer_capacity: %g\n",mixed_layer_capacity);
+	printf("   thermal_exchange_velocity: %g\n",thermal_exchange_velocity);
+	printf("   g: %g\n",g);
+	return;
+}
+/*}}}1*/
+/*FUNCTION Matpar::DeepEcho {{{1*/
+void Matpar::DeepEcho(void){
+
+	printf("Matpar:\n");
+	printf("   mid: %i\n",mid);
+	printf("   rho_ice: %g\n",rho_ice);
+	printf("   rho_water: %g\n",rho_water);
+	printf("   mu_water: %g\n",mu_water);
+	printf("   heatcapacity: %g\n",heatcapacity);
+	printf("   thermalconductivity: %g\n",thermalconductivity);
+	printf("   latentheat: %g\n",latentheat);
+	printf("   beta: %g\n",beta);
+	printf("   meltingpoint: %g\n",meltingpoint);
+	printf("   referencetemperature: %g\n",referencetemperature);
+	printf("   mixed_layer_capacity: %g\n",mixed_layer_capacity);
+	printf("   thermal_exchange_velocity: %g\n",thermal_exchange_velocity);
+	printf("   g: %g\n",g);
+	return;
+}		
+/*}}}1*/
+/*FUNCTION Matpar::Id {{{1*/
+int    Matpar::Id(void){ return mid; }
+/*}}}1*/
+/*FUNCTION Matpar::MyRank {{{1*/
+int    Matpar::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}1*/
+#ifdef _SERIAL_
+/*FUNCTION Matpar::Marshall {{{1*/
+void  Matpar::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of Matpar: */
+	enum_type=MatparEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*marshall Matpar data: */
+	memcpy(marshalled_dataset,&mid,sizeof(mid));marshalled_dataset+=sizeof(mid);
+	memcpy(marshalled_dataset,&rho_ice,sizeof(rho_ice));marshalled_dataset+=sizeof(rho_ice);
+	memcpy(marshalled_dataset,&rho_water,sizeof(rho_water));marshalled_dataset+=sizeof(rho_water);
+	memcpy(marshalled_dataset,&mu_water,sizeof(mu_water));marshalled_dataset+=sizeof(mu_water);
+	memcpy(marshalled_dataset,&heatcapacity,sizeof(heatcapacity));marshalled_dataset+=sizeof(heatcapacity);
+	memcpy(marshalled_dataset,&thermalconductivity,sizeof(thermalconductivity));marshalled_dataset+=sizeof(thermalconductivity);
+	memcpy(marshalled_dataset,&latentheat,sizeof(latentheat));marshalled_dataset+=sizeof(latentheat);
+	memcpy(marshalled_dataset,&beta,sizeof(beta));marshalled_dataset+=sizeof(beta);
+	memcpy(marshalled_dataset,&meltingpoint,sizeof(meltingpoint));marshalled_dataset+=sizeof(meltingpoint);
+	memcpy(marshalled_dataset,&referencetemperature,sizeof(referencetemperature));marshalled_dataset+=sizeof(referencetemperature);
+	memcpy(marshalled_dataset,&mixed_layer_capacity,sizeof(mixed_layer_capacity));marshalled_dataset+=sizeof(mixed_layer_capacity);
+	memcpy(marshalled_dataset,&thermal_exchange_velocity,sizeof(thermal_exchange_velocity));marshalled_dataset+=sizeof(thermal_exchange_velocity);
+	memcpy(marshalled_dataset,&g,sizeof(g));marshalled_dataset+=sizeof(g);
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}1*/
+/*FUNCTION Matpar::MarshallSize {{{1*/
+int   Matpar::MarshallSize(){
+
+	return sizeof(mid)+
+		sizeof(rho_ice)+
+		sizeof(rho_water)+
+		sizeof(mu_water)+
+		sizeof(heatcapacity)+
+		sizeof(thermalconductivity)+
+		sizeof(latentheat)+
+		sizeof(beta)+
+		sizeof(meltingpoint)+
+		sizeof(referencetemperature)+
+		sizeof(mixed_layer_capacity)+
+		sizeof(thermal_exchange_velocity)+
+		sizeof(g)+
+		sizeof(int); //sizeof(int) for enum type
+}
+/*}}}1*/
+/*FUNCTION Matpar::Demarshall {{{1*/
+void  Matpar::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+
+	memcpy(&mid,marshalled_dataset,sizeof(mid));marshalled_dataset+=sizeof(mid);
+	memcpy(&rho_ice,marshalled_dataset,sizeof(rho_ice));marshalled_dataset+=sizeof(rho_ice);
+	memcpy(&rho_water,marshalled_dataset,sizeof(rho_water));marshalled_dataset+=sizeof(rho_water);
+	memcpy(&mu_water,marshalled_dataset,sizeof(mu_water));marshalled_dataset+=sizeof(mu_water);
+	memcpy(&heatcapacity,marshalled_dataset,sizeof(heatcapacity));marshalled_dataset+=sizeof(heatcapacity);
+	memcpy(&thermalconductivity,marshalled_dataset,sizeof(thermalconductivity));marshalled_dataset+=sizeof(thermalconductivity);
+	memcpy(&latentheat,marshalled_dataset,sizeof(latentheat));marshalled_dataset+=sizeof(latentheat);
+	memcpy(&beta,marshalled_dataset,sizeof(beta));marshalled_dataset+=sizeof(beta);
+	memcpy(&meltingpoint,marshalled_dataset,sizeof(meltingpoint));marshalled_dataset+=sizeof(meltingpoint);
+	memcpy(&referencetemperature,marshalled_dataset,sizeof(referencetemperature));marshalled_dataset+=sizeof(referencetemperature);
+	memcpy(&mixed_layer_capacity,marshalled_dataset,sizeof(mixed_layer_capacity));marshalled_dataset+=sizeof(mixed_layer_capacity);
+	memcpy(&thermal_exchange_velocity,marshalled_dataset,sizeof(thermal_exchange_velocity));marshalled_dataset+=sizeof(thermal_exchange_velocity);
+	memcpy(&g,marshalled_dataset,sizeof(g));marshalled_dataset+=sizeof(g);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}1*/
+#endif
+/*FUNCTION Matpar::ObjectEnum{{{1*/
+int Matpar::ObjectEnum(void){
+
+	return MatparEnum;
+
+}
+/*}}}1*/
+/*FUNCTION Matpar::copy {{{1*/
+Object* Matpar::copy() {
+	return new Matpar(*this); 
+}
+/*}}}1*/
+
+/*Update virtual functions definitions:*/
+/*FUNCTION Matpar::InputUpdateFromVector(double* vector, int name, int type) {{{1*/
+void   Matpar::InputUpdateFromVector(double* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromVector(int* vector, int name, int type) {{{1*/
+void   Matpar::InputUpdateFromVector(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromVector(bool* vector, int name, int type) {{{1*/
+void   Matpar::InputUpdateFromVector(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromVectorDakota(double* vector, int name, int type) {{{1*/
+void   Matpar::InputUpdateFromVectorDakota(double* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromVectorDakota(int* vector, int name, int type) {{{1*/
+void   Matpar::InputUpdateFromVectorDakota(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromVectorDakota(bool* vector, int name, int type) {{{1*/
+void   Matpar::InputUpdateFromVectorDakota(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromMatrixDakota(int* vector, int name, int type) {{{1*/
+void  Matpar::InputUpdateFromMatrixDakota(double* matrix, int nrows, int ncols,int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromConstant(double constant, int name) {{{1*/
+void   Matpar::InputUpdateFromConstant(double constant, int name){
+
+	switch(name){
+		case MaterialsRhoIceEnum:
+			this->rho_ice=constant;
+			break;
+
+		case MaterialsRhoWaterEnum:
+			this->rho_water=constant;
+			break;
+
+		case MaterialsMuWaterEnum:
+			this->mu_water=constant;
+			break;
+
+		case MaterialsHeatcapacityEnum:
+			this->heatcapacity=constant;
+			break;
+
+		case MaterialsThermalconductivityEnum:
+			this->thermalconductivity=constant;
+			break;
+
+		case  MaterialsLatentheatEnum:
+			this->latentheat=constant;
+			break;
+
+		case  MaterialsBetaEnum:
+			this->beta=constant;
+			break;
+
+		case  MaterialsMeltingpointEnum:
+			this->meltingpoint=constant;
+			break;
+
+		case  ConstantsReferencetemperatureEnum:
+			this->referencetemperature=constant;
+			break;
+
+		case  MaterialsMixedLayerCapacityEnum:
+			this->mixed_layer_capacity=constant;
+			break;
+
+		case  MaterialsThermalExchangeVelocityEnum:
+			this->thermalconductivity=constant;
+			break;
+
+		case  ConstantsGEnum:
+			this->g=constant;
+			break;
+
+		default: 
+			break;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromConstant(int constant, int name) {{{1*/
+void   Matpar::InputUpdateFromConstant(int constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromConstant(bool constant, int name) {{{1*/
+void   Matpar::InputUpdateFromConstant(bool constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matpar::InputUpdateFromSolution{{{1*/
+void   Matpar::InputUpdateFromSolution(double* solution){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+
+/*Matpar management: */
+/*FUNCTION Matpar::Configure {{{1*/
+void  Matpar::Configure(Elements* elementsin){
+
+	/*nothing done yet!*/
+
+}
+/*}}}*/
+/*FUNCTION Matpar::GetBeta {{{1*/
+double Matpar::GetBeta(){
+	return beta;
+}
+/*}}}1*/
+/*FUNCTION Matpar::GetG {{{1*/
+double Matpar::GetG(){
+	return g;
+}
+/*}}}1*/
+/*FUNCTION Matpar::GetHeatCapacity {{{1*/
+double Matpar::GetHeatCapacity(){
+	return heatcapacity;
+}
+/*}}}1*/
+/*FUNCTION Matpar::GetLatentHeat {{{1*/
+double Matpar::GetLatentHeat(){
+	return latentheat;
+}
+/*}}}1*/
+/*FUNCTION Matpar::GetMeltingPoint {{{1*/
+double Matpar::GetMeltingPoint(){
+	return meltingpoint;
+}
+/*}}}1*/
+/*FUNCTION Matpar::GetReferenceTemperature {{{1*/
+double Matpar::GetReferenceTemperature(){
+	return referencetemperature;
+}
+/*}}}1*/
+/*FUNCTION Matpar::GetMixedLayerCapacity {{{1*/
+double Matpar::GetMixedLayerCapacity(){
+	return mixed_layer_capacity;
+}
+/*}}}1*/
+/*FUNCTION Matpar::GetRhoIce {{{1*/
+double Matpar::GetRhoIce(){
+	
+	return rho_ice;
+}
+/*}}}1*/
+/*FUNCTION Matpar::GetRhoWater {{{1*/
+double Matpar::GetRhoWater(){
+	return rho_water;
+}
+/*}}}1*/
+/*FUNCTION Matpar::GetMuWater {{{1*/
+double Matpar::GetMuWater(){
+	return mu_water;
+}
+/*}}}1*/
+/*FUNCTION Matpar::GetThermalConductivity {{{1*/
+double Matpar::GetThermalConductivity(){
+	return thermalconductivity;
+}
+/*}}}1*/
+/*FUNCTION Matpar::GetThermalExchangeVelocity {{{1*/
+double Matpar::GetThermalExchangeVelocity(){
+	return thermal_exchange_velocity;
+}
+/*}}}1*/
+/*FUNCTION Matpar::GetKn {{{1*/		 
+double Matpar::GetKn(){			 
+	return kn;		 
+}		 
+/*}}}1*/			 
+/*FUNCTION Matpar::GetHydrologyP {{{1*/			 
+double Matpar::GetHydrologyP(){		 
+	return hydro_p;			 
+}		 
+/*}}}1*/			 
+/*FUNCTION Matqar::GetHydrologyQ {{{1*/			 
+double Matpar::GetHydrologyQ(){		 
+	return hydro_q;			 
+}		 
+/*}}}1*/			 
+/*FUNCTION Matpar::GetHydrologyCR {{{1*/		 
+double Matpar::GetHydrologyCR(){		 
+	return hydro_CR;		 
+}		 
+/*}}}1*/			 
+/*FUNCTION Matpar::GetHydrologyN {{{1*/			 
+double Matpar::GetHydrologyN(){		 
+	return hydro_n;			 
+}		 
+/*}}}1*/ 
+/*FUNCTION Matpar::TMeltingPoint {{{1*/
+double Matpar::TMeltingPoint(double pressure){
+	return meltingpoint-beta*pressure;
+}
+/*}}}1*/
+/*FUNCTION Matpar::PureIceEnthalpy{{{1*/
+double Matpar::PureIceEnthalpy(double pressure){
+	return heatcapacity*(TMeltingPoint(pressure)-referencetemperature);
+}
+/*}}}1*/
+/*FUNCTION Matpar::GetEnthalpyDiffusionParameter{{{1*/
+double Matpar::GetEnthalpyDiffusionParameter(double enthalpy,double pressure){
+	if(enthalpy<PureIceEnthalpy(pressure)){
+		return thermalconductivity/(rho_ice*heatcapacity);
+	}
+	else{
+		return 0.1*thermalconductivity/(rho_ice*heatcapacity);
+	}
+}
+/*}}}1*/
+/*FUNCTION Matpar::EnthalpyToThermal {{{1*/
+void Matpar::EnthalpyToThermal(double* ptemperature,double* pwaterfraction,double enthalpy,double pressure){
+
+	/*Ouput*/
+	double 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;
+}
+/*}}}1*/
+/*FUNCTION Matpar::ThermalToEnthalpy {{{1*/
+void Matpar::ThermalToEnthalpy(double * penthalpy,double temperature,double waterfraction,double pressure){
+
+	/*Ouput*/
+	double enthalpy;
+	
+	if(temperature<TMeltingPoint(pressure)){
+		enthalpy=heatcapacity*(temperature-referencetemperature);
+	}
+	else{
+		enthalpy=PureIceEnthalpy(pressure)+latentheat*waterfraction;
+	}
+
+	/*Assign output pointers:*/
+	*penthalpy=enthalpy;
+}
+/*}}}1*/
Index: /issm/trunk-jpl-damage/src/c/objects/Materials/Matpar.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Materials/Matpar.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Materials/Matpar.h	(revision 11330)
@@ -0,0 +1,102 @@
+/*!\file Matpar.h
+ * \brief: header file for matpar object
+ */
+
+#ifndef _MATPAR_H_
+#define _MATPAR_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Material.h"
+class IoModel;
+/*}}}*/
+
+class Matpar: public Material{
+
+	private: 
+		int	mid;
+		double	rho_ice; 
+		double	rho_water;
+		double  mu_water;
+		double  heatcapacity;
+		double  thermalconductivity;
+		double  latentheat;
+		double  beta;
+		double  meltingpoint;
+		double  referencetemperature;
+		double  mixed_layer_capacity;
+		double  thermal_exchange_velocity;
+		double  g;
+
+		/*hydrology: */		 
+		double  kn;			 
+		double  hydro_p;		 
+		double  hydro_q;		 
+		double  hydro_CR;			 
+		double  hydro_n; 
+
+	public:
+		Matpar();
+		Matpar(int matpar_id, IoModel* iomodel);
+		~Matpar();
+
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{1*/
+		void   InputUpdateFromVector(double* vector, int name, int type);
+		void   InputUpdateFromVector(int* vector, int name, int type);
+		void   InputUpdateFromVector(bool* vector, int name, int type);
+		void   InputUpdateFromMatrixDakota(double* matrix,int nrows,int ncols, int name, int type);
+		void   InputUpdateFromVectorDakota(double* vector, int name, int type);
+		void   InputUpdateFromVectorDakota(int* vector, int name, int type);
+		void   InputUpdateFromVectorDakota(bool* vector, int name, int type);
+		void   InputUpdateFromConstant(double constant, int name);
+		void   InputUpdateFromConstant(int constant, int name);
+		void   InputUpdateFromConstant(bool constant, int name);
+		void   InputUpdateFromSolution(double* solution);
+		void   InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+		/*Material virtual functions resolution: {{{1*/
+		void   InputDuplicate(int original_enum,int new_enum){_error_("not implemented yet");};
+		void   Configure(Elements* elements);
+		void   GetVectorFromInputs(Vec vector,int input_enum){return;}
+		/*}}}*/
+		/*Numerics: {{{1*/
+		double GetG();
+		double GetRhoIce();
+		double GetRhoWater();
+		double GetMuWater();
+		double GetMixedLayerCapacity();
+		double GetThermalExchangeVelocity();
+		double GetHeatCapacity();
+		double GetThermalConductivity();
+		double GetLatentHeat();
+		double GetBeta();
+		double GetMeltingPoint();
+		double GetReferenceTemperature();
+		double GetKn();
+		double GetHydrologyP();
+		double GetHydrologyQ();
+		double GetHydrologyCR();
+		double GetHydrologyN();
+		double TMeltingPoint(double pressure);
+		double PureIceEnthalpy(double pressure);
+		double GetEnthalpyDiffusionParameter(double enthalpy,double pressure);
+		void   EnthalpyToThermal(double* ptemperature,double* pwaterfraction,double enthalpy,double pressure);
+		void   ThermalToEnthalpy(double* penthalpy,double temperature,double waterfraction,double pressure);
+		/*}}}*/
+
+};
+
+#endif  /* _MATPAR_H_ */
Index: /issm/trunk-jpl-damage/src/c/objects/Node.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Node.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Node.cpp	(revision 11330)
@@ -0,0 +1,1096 @@
+/*!\file Node.c
+ * \brief: implementation of the Node object
+ */
+
+/*Include files: {{{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 "./objects.h"
+#include "../Container/Container.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "../modules/modules.h"
+/*}}}*/
+
+/*Node constructors and destructors:*/
+/*FUNCTION Node::Node() default constructor {{{1*/
+Node::Node(){
+		 this->inputs=NULL;
+		 this->hvertex=NULL;
+		 return;
+}
+/*}}}*/
+/*FUNCTION Node::Node(int node_id,int node_sid,int vertex_id,int io_index, IoModel* iomodel,int analysis_type) {{{1*/
+Node::Node(int node_id,int node_sid,int vertex_id,int io_index, IoModel* iomodel,int analysis_type){
+
+	/*Intermediary*/
+	int k,l;
+	int gsize;
+	int dim;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+
+	/*id: */
+	this->id=node_id; 
+	this->sid=node_sid; 
+	this->analysis_type=analysis_type;
+
+	/*Initialize coord_system: Identity matrix by default*/
+	for(k=0;k<3;k++) for(l=0;l<3;l++) this->coord_system[k][l]=0.0;
+	for(k=0;k<3;k++) this->coord_system[k][k]=1.0;
+
+	/*indexing:*/
+	DistributeNumDofs(&this->indexing,analysis_type,iomodel->Data(FlowequationVertexEquationEnum)+io_index); //number of dofs per node
+	gsize=this->indexing.gsize;
+
+	/*Hooks*/
+	this->hvertex=new Hook(&vertex_id,1); //node id is the same as the vertex id, continuous galerkin!
+
+	//intialize inputs, and add as many inputs per element as requested: 
+	this->inputs=new Inputs();
+	if (iomodel->Data(MeshVertexonbedEnum))
+	 this->inputs->AddInput(new BoolInput(MeshVertexonbedEnum,(IssmBool)iomodel->Data(MeshVertexonbedEnum)[io_index]));
+	if (iomodel->Data(MeshVertexonsurfaceEnum))
+	 this->inputs->AddInput(new BoolInput(MeshVertexonsurfaceEnum,(IssmBool)iomodel->Data(MeshVertexonsurfaceEnum)[io_index]));
+	if (iomodel->Data(MaskVertexonfloatingiceEnum))
+	 this->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,(IssmBool)iomodel->Data(MaskVertexonfloatingiceEnum)[io_index]));
+	if (iomodel->Data(MaskVertexongroundediceEnum))
+	 this->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,(IssmBool)iomodel->Data(MaskVertexongroundediceEnum)[io_index]));
+	if (analysis_type==DiagnosticHorizAnalysisEnum)
+	 this->inputs->AddInput(new IntInput(ApproximationEnum,(IssmInt)iomodel->Data(FlowequationVertexEquationEnum)[io_index]));
+	
+	/*set single point constraints: */
+
+	/*spc all nodes on water*/
+	if (!iomodel->Data(MaskVertexonwaterEnum)) _error_("iomodel->nodeonwater is NULL");
+	if (iomodel->Data(MaskVertexonwaterEnum)[io_index]){
+		for(k=1;k<=gsize;k++){
+			this->FreezeDof(k);
+		}
+	}
+
+	/*Diagnostic Horiz*/
+	#ifdef _HAVE_DIAGNOSTIC_
+	if (analysis_type==DiagnosticHorizAnalysisEnum){
+
+		/*Coordinate system provided, convert to coord_system matrix*/
+		_assert_(iomodel->Data(DiagnosticReferentialEnum)); 
+		XZvectorsToCoordinateSystem(&this->coord_system[0][0],iomodel->Data(DiagnosticReferentialEnum)+io_index*6);
+
+		if (dim==3){
+			/*We have a  3d mesh, we may have collapsed elements, hence dead nodes. Freeze them out: */
+			_assert_(iomodel->Data(MeshVertexonbedEnum)); 
+			_assert_(iomodel->Data(FlowequationVertexEquationEnum));
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealApproximationEnum && !iomodel->Data(MeshVertexonbedEnum)[io_index]){
+				for(k=1;k<=gsize;k++) this->FreezeDof(k);
+			}
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealPattynApproximationEnum && iomodel->Data(FlowequationBordermacayealEnum)[io_index]){
+				if(!iomodel->Data(MeshVertexonbedEnum)[io_index]){
+					for(k=1;k<=gsize;k++) this->FreezeDof(k);
+				}
+			}
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealStokesApproximationEnum && iomodel->Data(FlowequationBordermacayealEnum)[io_index]){
+				if(!iomodel->Data(MeshVertexonbedEnum)[io_index]){
+					for(k=1;k<=2;k++) this->FreezeDof(k);
+				}
+			}
+		}
+		/*spc all nodes on hutter*/
+		if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==HutterApproximationEnum){
+			for(k=1;k<=gsize;k++){
+				this->FreezeDof(k);
+			}
+		}
+	}
+	#endif
+
+	/*Diagnostic Hutter*/
+	if (analysis_type==DiagnosticHutterAnalysisEnum){
+		if (!iomodel->Data(FlowequationVertexEquationEnum)) _error_("iomodel->vertices_type is NULL");
+		/*Constrain all nodes that are not Hutter*/
+		if (!iomodel->Data(FlowequationVertexEquationEnum)[io_index]==HutterApproximationEnum){
+			for(k=1;k<=gsize;k++){
+				this->FreezeDof(k);
+			}
+		}
+	}
+
+	/*Prognostic/ Melting/ Slopecompute/ Balancethickness*/
+	if (
+				analysis_type==PrognosticAnalysisEnum || 
+				analysis_type==MeltingAnalysisEnum || 
+				analysis_type==BedSlopeAnalysisEnum || 
+				analysis_type==SurfaceSlopeAnalysisEnum || 
+				analysis_type==BalancethicknessAnalysisEnum
+				){
+		if (dim==3){
+			/*On a 3d mesh, we may have collapsed elements, hence dead nodes. Freeze them out: */
+			_assert_(iomodel->Data(MeshVertexonbedEnum));
+			if (!iomodel->Data(MeshVertexonbedEnum)[io_index]){
+				for(k=1;k<=gsize;k++){
+					this->FreezeDof(k);
+				}
+			}
+		}
+	}
+
+}
+/*}}}*/
+/*FUNCTION Node::~Node(){{{1*/
+Node::~Node(){
+	delete inputs;
+	delete hvertex;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Node::Echo{{{1*/
+void Node::Echo(void){
+
+	printf("Node:\n");
+	printf("   id: %i\n",id);
+	printf("   sid: %i\n",sid);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	indexing.Echo();
+	printf("   hvertex:     not displayed\n");
+	printf("   inputs:      %p\n",inputs);
+
+
+}
+/*}}}*/
+/*FUNCTION Node::DeepEcho{{{1*/
+void Node::DeepEcho(void){
+
+	printf("Node:\n");
+	printf("   id: %i\n",id);
+	printf("   sid: %i\n",sid);
+	printf("   analysis_type: %s\n",EnumToStringx(analysis_type));
+	indexing.DeepEcho();
+	printf("Vertex:\n");
+	hvertex->DeepEcho();
+	printf("   inputs\n");
+
+
+}
+/*}}}*/
+/*FUNCTION Node::Id{{{1*/
+int    Node::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Node::MyRank{{{1*/
+int    Node::MyRank(void){ 
+	extern int my_rank;
+
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION Node::Marshall{{{1*/
+void  Node::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+	char* marshalled_inputs=NULL;
+	int   marshalled_inputssize;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of Node: */
+	enum_type=NodeEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*marshall Node data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&sid,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(marshalled_dataset,&analysis_type,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+	memcpy(marshalled_dataset,&coord_system,9*sizeof(double));marshalled_dataset+=9*sizeof(double);  
+
+	/*marshall objects: */
+	indexing.Marshall(&marshalled_dataset);
+	hvertex->Marshall(&marshalled_dataset);
+
+	/*Marshall inputs: */
+	marshalled_inputssize=inputs->MarshallSize();
+	marshalled_inputs=inputs->Marshall();
+	memcpy(marshalled_dataset,marshalled_inputs,marshalled_inputssize*sizeof(char));
+	marshalled_dataset+=marshalled_inputssize;
+
+	/*Free ressources:*/
+	xfree((void**)&marshalled_inputs);
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+/*FUNCTION Node::MarshallSize{{{1*/
+int   Node::MarshallSize(){
+
+	return sizeof(id)+
+		sizeof(sid)+
+		indexing.MarshallSize()+
+		hvertex->MarshallSize()+
+		inputs->MarshallSize()+
+		sizeof(analysis_type)+
+		9*sizeof(double)+
+		sizeof(int); //sizeof(int) for enum type
+}
+/*}}}*/
+/*FUNCTION Node::Demarshall{{{1*/
+void  Node::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&sid,marshalled_dataset,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(&analysis_type,marshalled_dataset,sizeof(analysis_type));marshalled_dataset+=sizeof(analysis_type);
+	memcpy(&coord_system,marshalled_dataset,9*sizeof(double));marshalled_dataset+=9*sizeof(double);
+	
+	/*demarshall objects: */
+	indexing.Demarshall(&marshalled_dataset);
+	hvertex=new Hook(); hvertex->Demarshall(&marshalled_dataset);
+
+	/*demarshall inputs: */
+	inputs=(Inputs*)DataSetDemarshallRaw(&marshalled_dataset); 
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION Node::ObjectEnum{{{1*/
+int Node::ObjectEnum(void){
+
+	return NodeEnum;
+
+}
+/*}}}*/
+
+/*Node management:*/
+/*FUNCTION Node::Configure {{{1*/
+void  Node::Configure(DataSet* nodesin,Vertices* verticesin){
+
+	int i;
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and off_sets hidden in hooks: */
+	hvertex->configure(verticesin);
+
+}
+/*FUNCTION Node::SetCurrentConfiguration {{{1*/
+void  Node::SetCurrentConfiguration(DataSet* nodesin,Vertices* verticesin){
+
+}
+/*FUNCTION Node::GetDof {{{1*/
+int   Node::GetDof(int dofindex,int setenum){
+
+	if(setenum==GsetEnum){
+		_assert_(dofindex>=0 && dofindex<indexing.gsize);
+		return indexing.gdoflist[dofindex];
+	}
+	else if(setenum==FsetEnum){
+		_assert_(dofindex>=0 && dofindex<indexing.fsize);
+		return indexing.fdoflist[dofindex];
+	}
+	else if(setenum==SsetEnum){
+		_assert_(dofindex>=0 && dofindex<indexing.ssize);
+		return indexing.sdoflist[dofindex];
+	}
+	else _error_("%s%s%s"," set of enum type ",EnumToStringx(setenum)," not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Node::GetDofList1{{{1*/
+int  Node::GetDofList1(void){
+
+	Vertex* vertex=NULL;
+
+	vertex=(Vertex*)this->hvertex->delivers();
+
+	return vertex->dof;
+}
+/*}}}*/
+/*FUNCTION Node::GetDofList{{{1*/
+void  Node::GetDofList(int* outdoflist,int approximation_enum,int setenum){
+	int i;
+	int count=0;
+	int count2=0;
+		
+	if(approximation_enum==NoneApproximationEnum){
+		if(setenum==GsetEnum)for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=indexing.gdoflist[i];
+		if(setenum==FsetEnum)for(i=0;i<this->indexing.fsize;i++) outdoflist[i]=indexing.fdoflist[i];
+		if(setenum==SsetEnum)for(i=0;i<this->indexing.ssize;i++) outdoflist[i]=indexing.sdoflist[i];
+	}
+	else{
+
+		if(setenum==GsetEnum){
+			if(indexing.doftype){
+				count=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.doftype[i]==approximation_enum){
+						outdoflist[count]=indexing.gdoflist[i];
+						count++;
+					}
+				}
+				_assert_(count); //at least one dof should be the approximation requested
+			}
+			else for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=indexing.gdoflist[i];
+		}
+		else if(setenum==FsetEnum){
+			if(indexing.doftype){
+				count=0;
+				count2=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.f_set[i]){
+						if(indexing.doftype[i]==approximation_enum){
+							outdoflist[count]=indexing.fdoflist[count2];
+							count++;
+						}
+						count2++;
+					}
+				}
+			}
+			else for(i=0;i<this->indexing.fsize;i++) outdoflist[i]=indexing.fdoflist[i];
+		}
+		else if(setenum==SsetEnum){
+			if(indexing.doftype){
+				count=0;
+				count2=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.s_set[i]){
+						if(indexing.doftype[i]==approximation_enum){
+							outdoflist[count]=indexing.sdoflist[count2];
+							count++;
+						}
+						count2++;
+					}
+				}
+			}
+			else for(i=0;i<this->indexing.ssize;i++) outdoflist[i]=indexing.sdoflist[i];
+		}
+		else _error_("%s%s%s"," set of enum type ",EnumToStringx(setenum)," not supported yet!");
+	}
+}
+/*}}}*/
+/*FUNCTION Node::GetSidList{{{1*/
+int  Node::GetSidList(void){
+
+	Vertex* vertex=NULL;
+
+	vertex=(Vertex*)this->hvertex->delivers();
+
+	return vertex->sid;
+}
+/*}}}*/
+/*FUNCTION Node::GetLocalDofList{{{1*/
+void  Node::GetLocalDofList(int* outdoflist,int approximation_enum,int setenum){
+	int i;
+	int count=0;
+	int count2=0;
+		
+	if(approximation_enum==NoneApproximationEnum){
+		if(setenum==GsetEnum)for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=i;
+		else if(setenum==FsetEnum){
+			count=0;
+			for(i=0;i<this->indexing.gsize;i++){
+				if(indexing.f_set[i]){
+					outdoflist[count]=i;
+					count++;
+				}
+			}
+		}
+		else if(setenum==SsetEnum){
+			count=0;
+			for(i=0;i<this->indexing.gsize;i++){
+				if(indexing.s_set[i]){
+					outdoflist[count]=i;
+					count++;
+				}
+			}
+		}
+		else _error_("%s%s%s"," 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_("%s%s%s"," set of enum type ",EnumToStringx(setenum)," not supported yet!");
+	}
+}
+/*}}}*/
+/*FUNCTION Node::Sid{{{1*/
+int    Node::Sid(void){ return sid; }
+/*}}}*/
+/*FUNCTION Node::GetVertexId {{{1*/
+int   Node::GetVertexId(void){
+
+	Vertex*  vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	return vertex->id;
+}
+/*}}}*/
+/*FUNCTION Node::GetVertexDof {{{1*/
+int   Node::GetVertexDof(void){
+
+	Vertex*  vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	return vertex->dof;
+}
+/*}}}*/
+#ifdef _HAVE_DIAGNOSTIC_
+/*FUNCTION Node::GetCoordinateSystem{{{1*/
+void Node::GetCoordinateSystem(double* coord_system_out){
+
+	/*Copy coord_system*/
+	for(int k=0;k<3;k++) for(int l=0;l<3;l++) coord_system_out[3*k+l]=this->coord_system[k][l];
+
+}
+/*}}}*/
+#endif
+/*FUNCTION Node::SetVertexDof {{{1*/
+void   Node::SetVertexDof(int in_dof){
+
+	Vertex*  vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	vertex->dof=in_dof;
+
+}
+/*}}}*/
+/*FUNCTION Node::InAnalysis{{{1*/
+bool Node::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+
+/*Node numerics:*/
+/*FUNCTION Node::ApplyConstraints{{{1*/
+void  Node::ApplyConstraint(int dof,double value){
+
+	int index;
+
+	/*Dof should be added in the s set, describing which 
+	 * dofs are constrained to a certain value (dirichlet boundary condition*/
+	DofInSSet(dof-1);
+	this->indexing.svalues[dof-1]=value;
+}
+/*}}}*/
+/*FUNCTION Node::RelaxConstraint{{{1*/
+void  Node::RelaxConstraint(int dof){
+
+	/*Dof should be added to the f-set, and taken out of the s-set:*/
+	DofInFSet(dof-1);
+	this->indexing.svalues[dof-1]=NAN;
+}
+/*}}}*/
+/*FUNCTION Node::CreateVecSets {{{1*/
+void  Node::CreateVecSets(Vec pv_g,Vec pv_f,Vec pv_s){
+
+	double gvalue=1.0; //all nodes are in the g set;
+	double value;
+
+	int i;
+
+	for(i=0;i<this->indexing.gsize;i++){
+
+		/*g set: */
+		VecSetValues(pv_g,1,&indexing.gdoflist[i],&gvalue,INSERT_VALUES);
+		
+		/*f set: */
+		value=(double)this->indexing.f_set[i];
+		VecSetValues(pv_f,1,&indexing.gdoflist[i],&value,INSERT_VALUES);
+
+		/*s set: */
+		value=(double)this->indexing.s_set[i];
+		VecSetValues(pv_s,1,&indexing.gdoflist[i],&value,INSERT_VALUES);
+
+	}
+
+
+}
+/*}}}*/
+/*FUNCTION Node::CreateNodalConstraints{{{1*/
+void  Node::CreateNodalConstraints(Vec ys){
+
+	int i;
+	double* values=NULL;
+	int count;
+
+	/*Recover values for s set and plug them in constraints vector: */
+	if(this->indexing.ssize){
+		values=(double*)xmalloc(this->indexing.ssize*sizeof(double));
+		count=0;
+		for(i=0;i<this->indexing.gsize;i++){
+			if(this->indexing.s_set[i]){
+				values[count]=this->indexing.svalues[i];
+				_assert_(!isnan(values[count]));
+				count++;
+			}
+		}
+		
+		/*Add values into constraint vector: */
+		VecSetValues(ys,this->indexing.ssize,this->indexing.sdoflist,values,INSERT_VALUES);
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&values);
+
+
+}
+/*}}}*/
+/*FUNCTION Node::DofInSSet {{{1*/
+void  Node::DofInSSet(int dof){
+
+	/*Put dof for this node into the s set (ie, this dof will be constrained 
+	 * to a fixed value during computations. */
+
+	this->indexing.f_set[dof]=0; //n splits into f (for which we solve) and s (single point constraints)
+	this->indexing.s_set[dof]=1;
+}
+/*}}}*/
+/*FUNCTION Node::DofInFSet {{{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. */
+
+	this->indexing.f_set[dof]=1; 
+	this->indexing.s_set[dof]=0;
+}
+/*}}}*/
+/*FUNCTION Node::FreezeDof{{{1*/
+void  Node::FreezeDof(int dof){
+	
+	DofInSSet(dof-1); //with 0 displacement for this dof.
+
+}
+/*}}}*/
+/*FUNCTION Node::GetApproximation {{{1*/
+int   Node::GetApproximation(){
+
+	int approximation;
+
+	/*recover parameters: */
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	return approximation;
+}
+/*}}}*/
+/*FUNCTION Node::GetConnectivity {{{1*/
+int Node::GetConnectivity(){
+
+	Vertex*  vertex=NULL;
+	vertex=(Vertex*)hvertex->delivers();
+	return vertex->connectivity;
+}
+/*}}}*/
+/*FUNCTION Node::GetNumberOfDofs{{{1*/
+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_("%s%s%s"," 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_("%s%s%s"," set of enum type ",EnumToStringx(setenum)," not supported yet!");
+	}
+	return numdofs;
+}
+/*}}}*/
+/*FUNCTION Node::GetSigma {{{1*/
+double Node::GetSigma(){
+	Vertex* vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	return vertex->sigma;
+}
+/*}}}*/
+/*FUNCTION Node::GetX {{{1*/
+double Node::GetX(){
+	Vertex* vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	return vertex->x;
+}
+/*}}}*/
+/*FUNCTION Node::GetY {{{1*/
+double Node::GetY(){
+	Vertex* vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	return vertex->y;
+}
+/*}}}*/
+/*FUNCTION Node::GetZ {{{1*/
+double Node::GetZ(){
+	Vertex* vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	return vertex->z;
+}
+/*}}}*/
+/*FUNCTION Node::IsClone {{{1*/
+int   Node::IsClone(){
+	
+	return indexing.clone;
+
+}
+/*}}}*/
+/*FUNCTION Node::IsOnBed {{{1*/
+int   Node::IsOnBed(){
+
+	bool onbed;
+
+	/*recover parameters: */
+	inputs->GetInputValue(&onbed,MeshVertexonbedEnum);
+
+	return onbed;
+}
+/*}}}*/
+/*FUNCTION Node::IsGrounded {{{1*/
+int   Node::IsGrounded(){
+
+	bool onsheet;
+
+	/*recover parameters: */
+	inputs->GetInputValue(&onsheet,MaskVertexongroundediceEnum);
+
+	return onsheet;
+}		
+/*}}}*/
+/*FUNCTION Node::IsFloating {{{1*/
+int   Node::IsFloating(){
+	
+	bool onshelf;
+
+	/*recover parameters: */
+	inputs->GetInputValue(&onshelf,MaskVertexonfloatingiceEnum);
+
+	return onshelf;
+}
+/*}}}*/
+/*FUNCTION Node::IsOnSurface {{{1*/
+int   Node::IsOnSurface(){
+
+	bool onsurface;
+
+	/*recover parameters: */
+	inputs->GetInputValue(&onsurface,MeshVertexonsurfaceEnum);
+
+	return onsurface;
+}
+/*}}}*/
+/*FUNCTION Node::InputUpdateFromVector(double* vector, int name, int type){{{1*/
+void  Node::InputUpdateFromVector(double* vector, int name, int type){
+
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Node::InputUpdateFromVector(int* vector, int name, int type){{{1*/
+void  Node::InputUpdateFromVector(int* vector, int name, int type){
+
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Node::InputUpdateFromVector(bool* vector, int name, int type){{{1*/
+void  Node::InputUpdateFromVector(bool* vector, int name, int type){
+
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Node::InputUpdateFromVectorDakota(double* vector, int name, int type){{{1*/
+void  Node::InputUpdateFromVectorDakota(double* vector, int name, int type){
+
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Node::InputUpdateFromMatrixDakota(double* matrix, int nrows, int ncols, int name, int type){{{1*/
+void  Node::InputUpdateFromMatrixDakota(double* matrix, int nrows, int ncols, int name, int type){
+
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Node::InputUpdateFromVectorDakota(int* vector, int name, int type){{{1*/
+void  Node::InputUpdateFromVectorDakota(int* vector, int name, int type){
+
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Node::InputUpdateFromVectorDakota(bool* vector, int name, int type){{{1*/
+void  Node::InputUpdateFromVectorDakota(bool* vector, int name, int type){
+
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Node::InputUpdateFromConstant(double constant, int name){{{1*/
+void  Node::InputUpdateFromConstant(double constant, int name){
+
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Node::InputUpdateFromConstant(int constant, int name){{{1*/
+void  Node::InputUpdateFromConstant(int constant, int name){
+
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Node::InputUpdateFromConstant(bool constant, int name){{{1*/
+void  Node::InputUpdateFromConstant(bool constant, int name){
+
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Node::UpdateSpcs {{{1*/
+void   Node::UpdateSpcs(double* ys){
+
+	int     count=0;
+	int     i;
+
+	count=0;
+	for(i=0;i<this->indexing.gsize;i++){
+		if(this->indexing.s_set[i]){
+			this->indexing.svalues[i]=ys[this->indexing.sdoflist[count]];
+			count++;
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION Node::VecMerge {{{1*/
+void   Node::VecMerge(Vec ug, double* vector_serial,int setenum){
+
+	double* values=NULL;
+	int*    indices=NULL;
+	int     count=0;
+	int     i;
+
+	if(setenum==FsetEnum){
+		if(this->indexing.fsize){
+			indices=(int*)xmalloc(this->indexing.fsize*sizeof(int));
+			values=(double*)xmalloc(this->indexing.fsize*sizeof(double));
+
+			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: */
+			VecSetValues(ug,this->indexing.fsize,indices,(const double*)values,INSERT_VALUES);
+		}
+	}
+	else if(setenum==SsetEnum){
+		if(this->indexing.ssize){
+			indices=(int*)xmalloc(this->indexing.ssize*sizeof(int));
+			values=(double*)xmalloc(this->indexing.ssize*sizeof(double));
+
+			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: */
+			VecSetValues(ug,this->indexing.ssize,indices,(const double*)values,INSERT_VALUES);
+		}
+	}
+	else _error_("VecMerge can only merge from the s or f-set onto the g-set!");
+
+	/*Free ressources:*/
+	xfree((void**)&values);
+	xfree((void**)&indices);
+}
+/*}}}*/
+/*FUNCTION Node::VecReduce {{{1*/
+void   Node::VecReduce(Vec vector, double* ug_serial,int setenum){
+
+	double* values=NULL;
+	int     count=0;
+	int     i;
+
+	if(setenum==FsetEnum){
+		if(this->indexing.fsize){
+			values=(double*)xmalloc(this->indexing.fsize*sizeof(double));
+
+			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: */
+			VecSetValues(vector,this->indexing.fsize,this->indexing.fdoflist,(const double*)values,INSERT_VALUES);
+		}
+	}
+	else if(setenum==SsetEnum){
+		if(this->indexing.ssize){
+			values=(double*)xmalloc(this->indexing.ssize*sizeof(double));
+
+			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: */
+			VecSetValues(vector,this->indexing.ssize,this->indexing.sdoflist,(const double*)values,INSERT_VALUES);
+		}
+	}
+	else _error_("VecReduce can only merge from the s or f-set onto the g-set!");
+
+	/*Free ressources:*/
+	xfree((void**)&values);
+}
+/*}}}*/
+
+/* DofObject routines:*/
+/*FUNCTION Node::DistributeDofs{{{1*/
+void  Node::DistributeDofs(int* pdofcount,int setenum){
+
+	int i;
+	extern int my_rank;
+	int dofcount;
+
+	dofcount=*pdofcount;
+
+	/*Initialize: */
+	if(setenum==FsetEnum) this->indexing.InitSet(setenum);
+	if(setenum==SsetEnum) this->indexing.InitSet(setenum);
+	
+		
+	/*For clone nodfs, don't distribute dofs, we will get them from another cpu in UpdateCloneDofs!*/
+	if(indexing.clone){
+		return;
+	}
+
+	/*This node should distribute dofs for setenum set (eg, f_set or s_set), go ahead: */
+
+	if(setenum==GsetEnum){
+		for(i=0;i<this->indexing.gsize;i++){
+			indexing.gdoflist[i]=dofcount+i;
+		}
+		dofcount+=this->indexing.gsize;
+	}
+	else if(setenum==FsetEnum){
+		for(i=0;i<this->indexing.fsize;i++){
+			indexing.fdoflist[i]=dofcount+i;
+		}
+		dofcount+=this->indexing.fsize;
+	}
+	else if(setenum==SsetEnum){
+		for(i=0;i<this->indexing.ssize;i++){
+			indexing.sdoflist[i]=dofcount+i;
+		}
+		dofcount+=this->indexing.ssize;
+	}
+	else _error_("%s%s%s"," set of enum type ",EnumToStringx(setenum)," not supported yet!");
+
+
+	/*Assign output pointers: */
+	*pdofcount=dofcount;
+
+}
+/*}}}*/
+/*FUNCTION Node::Off_setDofs{{{1*/
+void  Node::OffsetDofs(int dofcount,int setenum){
+	
+	int i;
+	extern int my_rank;
+	
+	if(indexing.clone){
+		/*This node is a clone, don't off_set the dofs!: */
+		return;
+	}
+
+	/*This node should off_set the dofs, go ahead: */
+	if(setenum==GsetEnum){
+		for(i=0;i<this->indexing.gsize;i++) indexing.gdoflist[i]+=dofcount;
+	}
+	else if(setenum==FsetEnum){
+		for(i=0;i<this->indexing.fsize;i++) indexing.fdoflist[i]+=dofcount;
+	}
+	else if(setenum==SsetEnum){
+		for(i=0;i<this->indexing.ssize;i++) indexing.sdoflist[i]+=dofcount;
+	}
+	else _error_("%s%s%s"," set of enum type ",EnumToStringx(setenum)," not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Node::ShowTrueDofs{{{1*/
+void  Node::ShowTrueDofs(int* truedofs, int ncols,int setenum){
+
+	int j;
+	extern int my_rank;
+	
+	/*Are we a clone? : */
+	if(indexing.clone)return;
+
+	/*Ok, we are not a clone, just plug our dofs into truedofs: */
+	if(setenum==GsetEnum)for(j=0;j<this->indexing.gsize;j++)  *(truedofs+ncols*sid+j)=indexing.gdoflist[j];
+	else if(setenum==FsetEnum)for(j=0;j<this->indexing.fsize;j++)  *(truedofs+ncols*sid+j)=indexing.fdoflist[j];
+	else if(setenum==SsetEnum)for(j=0;j<this->indexing.ssize;j++)  *(truedofs+ncols*sid+j)=indexing.sdoflist[j];
+	else _error_("%s%s%s"," set of enum type ",EnumToStringx(setenum)," not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Node::UpdateCloneDofs{{{1*/
+void  Node::UpdateCloneDofs(int* alltruedofs,int ncols,int setenum){
+
+	int j;
+	extern int my_rank;
+	
+	/*If we are not a clone, don't update, we already have dofs!: */
+	if(indexing.clone==0)return;
+
+
+	/*Ok, we are a clone node, but we did not create the dofs for this node.
+	 *      * Therefore, our doflist is garbage right now. Go pick it up in the alltruedofs: */
+	if(setenum==GsetEnum)for(j=0;j<this->indexing.gsize;j++) indexing.gdoflist[j]=*(alltruedofs+ncols*sid+j);
+	else if(setenum==FsetEnum)for(j=0;j<this->indexing.fsize;j++) indexing.fdoflist[j]=*(alltruedofs+ncols*sid+j);
+	else if(setenum==SsetEnum)for(j=0;j<this->indexing.ssize;j++) indexing.sdoflist[j]=*(alltruedofs+ncols*sid+j);
+	else _error_("%s%s%s"," set of enum type ",EnumToStringx(setenum)," not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Node::SetClone {{{1*/
+void  Node::SetClone(int* minranks){
+
+	extern int my_rank;
+
+	if (minranks[sid]==my_rank){
+		indexing.clone=0;
+	}
+	else{
+		/*!there is a cpu with lower rank that has the same node, 
+		therefore, I am a clone*/
+		indexing.clone=1; 	
+	}
+
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Node.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Node.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Node.h	(revision 11330)
@@ -0,0 +1,116 @@
+/*!\file Node.h
+ * \brief: header file for node object
+ */
+
+#ifndef _NODE_H_
+#define _NODE_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Object.h"
+#include "../shared/shared.h"
+class  Inputs;
+class  Hook;
+class  DofIndexing;
+class  IoModel;
+class  DataSet;
+class  Vertices;
+#include "./Update.h"
+/*}}}*/
+
+class Node: public Object ,public Update{
+
+	public: 
+
+		int	    id;  //unique arbitrary id.
+		int     sid; //sid for "serial" id, ie the rank of this node in the nodes dataset, if the dataset was serial on 1 cpu.
+				
+		DofIndexing    indexing;
+		Hook*          hvertex;
+		Inputs*        inputs; //properties of this node
+		int            analysis_type;
+		double         coord_system[3][3];
+
+		/*Node constructors, destructors {{{1*/
+		Node();
+		Node(int node_id,int node_sid, int vertex_id,int io_index, IoModel* iomodel,int analysis_type);
+		~Node();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy(){_error_("Not implemented yet (similar to Elements)");};
+		/*}}}*/
+		/*Update virtual functions definitions: {{{1*/
+		
+		void  InputUpdateFromVector(double* vector, int name, int type);
+		void  InputUpdateFromVector(int* vector, int name, int type);
+		void  InputUpdateFromVector(bool* vector, int name, int type);
+		void  InputUpdateFromMatrixDakota(double* matrix,int nrows, int ncols, int name, int type);
+		void  InputUpdateFromVectorDakota(double* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
+		void  InputUpdateFromConstant(double constant, int name);
+		void  InputUpdateFromConstant(int constant, int name);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromSolution(double* solution){_error_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("Not implemented yet!");}
+		/*}}}*/
+		/*Node numerical routines {{{1*/
+		void   Configure(DataSet* nodes,Vertices* vertices);
+		void   CreateNodalConstraints(Vec ys);
+		void   SetCurrentConfiguration(DataSet* nodes,Vertices* vertices);
+		int    Sid(void); 
+		int    GetVertexDof(void);
+		int    GetVertexId(void);
+#ifdef _HAVE_DIAGNOSTIC_
+		void   GetCoordinateSystem(double* coord_system_out);
+#endif
+		void   SetVertexDof(int in_dof);
+		bool   InAnalysis(int analysis_type);
+		int    GetApproximation();
+		int    GetNumberOfDofs(int approximation_enum,int setenum);
+		int    IsClone();
+		void   ApplyConstraint(int dof,double value);
+		void   RelaxConstraint(int dof);
+		void   DofInSSet(int dof);
+		void   DofInFSet(int dof);
+		int    GetDof(int dofindex,int setenum);
+		void   CreateVecSets(Vec pv_g,Vec pv_f,Vec pv_s);
+		int    GetConnectivity();
+		void   GetDofList(int* poutdoflist,int approximation_enum,int setenum);
+		void   GetLocalDofList(int* poutdoflist,int approximation_enum,int setenum);
+		int    GetDofList1(void);
+		int    GetSidList(void);
+		double GetX();
+		double GetY();
+		double GetZ();
+		double GetSigma();
+		int    IsOnBed();
+		int    IsOnSurface();
+		void   FreezeDof(int dof);
+		int    IsFloating();
+		int    IsGrounded();
+		void   UpdateSpcs(double* ys);
+		void   VecMerge(Vec ug, double* vector_serial,int setnum);
+		void   VecReduce(Vec vector, double* ug_serial,int setnum);
+		
+		/*}}}*/
+		/*Dof Object routines {{{1*/
+		void  DistributeDofs(int* pdofcount,int setenum);
+		void  OffsetDofs(int dofcount,int setenum);
+		void  ShowTrueDofs(int* truerows,int ncols,int setenum);
+		void  UpdateCloneDofs(int* alltruerows,int ncols,int setenum);
+		void  SetClone(int* minranks);
+		/*}}}*/
+};
+
+#endif  /* _NODE_H_ */
Index: /issm/trunk-jpl-damage/src/c/objects/Numerics/ElementMatrix.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Numerics/ElementMatrix.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Numerics/ElementMatrix.cpp	(revision 11330)
@@ -0,0 +1,453 @@
+/*!\file ElementMatrix.cpp
+ * \brief: implementation of the ElementMatrix object, used to plug values from element into global stiffness matrix
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*ElementMatrix constructors and destructor*/
+/*FUNCTION ElementMatrix::ElementMatrix(){{{1*/
+ElementMatrix::ElementMatrix(){
+
+	this->nrows=0;
+	this->ncols=0;
+	this->values=NULL;
+	this->dofsymmetrical=false;
+
+	this->row_fsize=0;
+	this->row_flocaldoflist=NULL;
+	this->row_fglobaldoflist=NULL;
+	this->row_ssize=0;
+	this->row_slocaldoflist=NULL;
+	this->row_sglobaldoflist=NULL;
+
+	this->col_fsize=0;
+	this->col_flocaldoflist=NULL;
+	this->col_fglobaldoflist=NULL;
+	this->col_ssize=0;
+	this->col_slocaldoflist=NULL;
+	this->col_sglobaldoflist=NULL;
+
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::ElementMatrix(ElementMatrix* Ke){{{1*/
+ElementMatrix::ElementMatrix(ElementMatrix* Ke){
+
+	if(!Ke) _error_("Input Element Matrix is a NULL pointer");
+	this->Init(Ke);
+	return;
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2){{{1*/
+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=(int*)xmalloc(Ke2->nrows*sizeof(int));
+
+	/*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=(int*)xmalloc(this->nrows*sizeof(int));
+	this->values=(double*)xcalloc(this->nrows*this->ncols,sizeof(double));
+	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 =(int*)xmalloc(fsize*sizeof(int));
+		this->row_fglobaldoflist=(int*)xmalloc(fsize*sizeof(int));
+		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 =(int*)xmalloc(ssize*sizeof(int));
+		this->row_sglobaldoflist=(int*)xmalloc(ssize*sizeof(int));
+		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*/
+	xfree((void**)&P);
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2,ElementMatrix* Ke3){{{1*/
+ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2,ElementMatrix* Ke3){
+
+	/*Concatenate all matrices*/
+	ElementMatrix* Ke12 =new ElementMatrix(Ke1,Ke2);
+	ElementMatrix* Ke123=new ElementMatrix(Ke12,Ke3);
+
+	/*Initialize current object with this matrix*/
+	this->Init(Ke123);
+
+	/*clean-up*/
+	delete Ke12;
+	delete Ke123;
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::ElementMatrix(Node** nodes,int numnodes,Parameters* parameters,int approximation){{{1*/
+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=(double*)xcalloc(this->nrows*this->ncols,sizeof(double));
+
+	/*g list*/
+	this->gglobaldoflist=GetGlobalDofList(nodes,numnodes,GsetEnum,approximation);
+
+	/*get dof lists for f and s set: */
+	this->row_fsize=GetNumberOfDofs(nodes,numnodes,FsetEnum,approximation);
+	this->row_flocaldoflist =GetLocalDofList( nodes,numnodes,FsetEnum,approximation);
+	this->row_fglobaldoflist=GetGlobalDofList(nodes,numnodes,FsetEnum,approximation);
+	this->row_ssize=GetNumberOfDofs(nodes,numnodes,SsetEnum,approximation);
+	this->row_slocaldoflist =GetLocalDofList( nodes,numnodes,SsetEnum,approximation);
+	this->row_sglobaldoflist=GetGlobalDofList(nodes,numnodes,SsetEnum,approximation);
+
+	/*Because this matrix is "dofsymmetrical" don't do cols, we can pick them up from the rows: */
+	this->col_fsize=0;
+	this->col_flocaldoflist=NULL;
+	this->col_fglobaldoflist=NULL;
+	this->col_ssize=0;
+	this->col_slocaldoflist=NULL;
+	this->col_sglobaldoflist=NULL;
+
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::~ElementMatrix(){{{1*/
+ElementMatrix::~ElementMatrix(){
+	
+	xfree((void**)&this->values);
+	xfree((void**)&this->gglobaldoflist);
+	xfree((void**)&this->row_flocaldoflist);
+	xfree((void**)&this->row_fglobaldoflist);
+	xfree((void**)&this->row_slocaldoflist);
+	xfree((void**)&this->row_sglobaldoflist);
+	xfree((void**)&this->col_flocaldoflist);
+	xfree((void**)&this->col_fglobaldoflist);
+	xfree((void**)&this->col_slocaldoflist);
+	xfree((void**)&this->col_sglobaldoflist);
+}
+/*}}}*/
+
+/*ElementMatrix specific routines: */
+/*FUNCTION ElementMatrix::AddToGlobal{{{1*/
+void ElementMatrix::AddToGlobal(Mat Kff, Mat Kfs){
+
+	int i,j;
+	double* localvalues=NULL;
+
+	/*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=(double*)xmalloc(this->row_fsize*this->row_fsize*sizeof(double));
+			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: */
+			MatSetValues(Kff,this->row_fsize,this->row_fglobaldoflist,this->row_fsize,this->row_fglobaldoflist,(const double*)localvalues,ADD_VALUES);
+
+			/*Free ressources:*/
+			xfree((void**)&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=(double*)xmalloc(this->row_fsize*this->row_ssize*sizeof(double));
+			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: */
+			MatSetValues(Kfs,this->row_fsize,this->row_fglobaldoflist,this->row_ssize,this->row_sglobaldoflist,(const double*)localvalues,ADD_VALUES);
+
+			/*Free ressources:*/
+			xfree((void**)&localvalues);
+		}
+	}
+	else{
+		_error_(" non dofsymmetrical matrix AddToGlobal routine not support yet!");
+	}
+
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::CheckConsistency{{{1*/
+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 (isnan(this->values[i*this->ncols+j])) _error_("NaN found in Element Matrix");
+			if (fabs(this->values[i*this->ncols+j])>1.e+50) _error_("Element Matrix values exceeds 1.e+50");
+		}
+	}
+	#endif
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::Transpose{{{1*/
+void ElementMatrix::Transpose(void){
+
+	/*Intermediaries*/
+	ElementMatrix* Ke_copy=new ElementMatrix(this);
+
+	/*Update sizes*/
+	this->nrows=Ke_copy->ncols;
+	this->ncols=Ke_copy->nrows;
+
+	/*Transpose values*/
+	for (int i=0;i<this->nrows;i++) for(int j=0;j<this->ncols;j++) this->values[i*this->ncols+j]=Ke_copy->values[j*Ke_copy->ncols+i];
+
+	/*Transpose indices*/
+	if(!dofsymmetrical){
+		_error_("not supported yet");
+	}
+
+	/*Clean up and return*/
+	delete Ke_copy;
+	return;
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::Echo{{{1*/
+void ElementMatrix::Echo(void){
+
+	int i,j;
+	printf("Element Matrix echo: \n");
+	printf("   nrows: %i\n",nrows);
+	printf("   ncols: %i\n",ncols);
+	printf("   dofsymmetrical: %s\n",dofsymmetrical?"true":"false");
+
+	printf("   values: \n");
+	for(i=0;i<nrows;i++){
+		printf("      %i: ",i);
+		for(j=0;j<ncols;j++) printf("%10g ",*(values+ncols*i+j));
+		printf("\n");
+	}
+
+	printf("   gglobaldoflist (%p): ",gglobaldoflist);
+	if(gglobaldoflist) for(i=0;i<nrows;i++)printf("%i ",gglobaldoflist[i]); printf("\n");
+
+	printf("   row_fsize: %i\n",row_fsize);
+	printf("   row_flocaldoflist (%p): ",row_flocaldoflist);
+	if(row_flocaldoflist) for(i=0;i<row_fsize;i++)printf("%i ",row_flocaldoflist[i]); printf("\n");
+	printf("   row_fglobaldoflist (%p): ",row_fglobaldoflist);
+	if(row_fglobaldoflist)for(i=0;i<row_fsize;i++)printf("%i ",row_fglobaldoflist[i]); printf("\n");
+
+	printf("   row_ssize: %i\n",row_ssize);
+	printf("   row_slocaldoflist (%p): ",row_slocaldoflist);
+	if(row_slocaldoflist)for(i=0;i<row_ssize;i++)printf("%i ",row_slocaldoflist[i]); printf("\n");
+	printf("   row_sglobaldoflist (%p): ",row_sglobaldoflist);
+	if(row_sglobaldoflist)for(i=0;i<row_ssize;i++)printf("%i ",row_sglobaldoflist[i]); printf("\n");
+
+	if(!dofsymmetrical){
+		printf("   col_fsize: %i\n",col_fsize);
+		printf("   col_flocaldoflist (%p): ",col_flocaldoflist);
+		if(col_flocaldoflist)for(i=0;i<col_fsize;i++)printf("%i ",col_flocaldoflist[i]); printf("\n");
+		printf("   col_fglobaldoflist (%p): ",col_fglobaldoflist);
+		if(col_fglobaldoflist)for(i=0;i<col_fsize;i++)printf("%i ",col_fglobaldoflist[i]); printf("\n");
+
+		printf("   col_ssize: %i\n",col_ssize);
+		printf("   col_slocaldoflist (%p): ",col_slocaldoflist);
+		if(col_slocaldoflist)for(i=0;i<col_ssize;i++)printf("%i ",col_slocaldoflist[i]); printf("\n");
+		printf("   col_sglobaldoflist (%p): ",col_sglobaldoflist);
+		if(col_sglobaldoflist)for(i=0;i<col_ssize;i++)printf("%i ",col_sglobaldoflist[i]); printf("\n");
+	}
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::Init{{{1*/
+void ElementMatrix::Init(ElementMatrix* Ke){
+
+	_assert_(Ke);
+
+	this->nrows =Ke->nrows;
+	this->ncols =Ke->ncols;
+	this->dofsymmetrical=Ke->dofsymmetrical;
+
+	this->values=(double*)xmalloc(this->nrows*this->ncols*sizeof(double));
+	memcpy(this->values,Ke->values,this->nrows*this->ncols*sizeof(double));
+
+	this->gglobaldoflist=(int*)xmalloc(this->nrows*sizeof(int));
+	memcpy(this->gglobaldoflist,Ke->gglobaldoflist,this->nrows*sizeof(int));
+
+	this->row_fsize=Ke->row_fsize;
+	if(this->row_fsize){
+		this->row_flocaldoflist=(int*)xmalloc(this->row_fsize*sizeof(int));
+		memcpy(this->row_flocaldoflist,Ke->row_flocaldoflist,this->row_fsize*sizeof(int));
+		this->row_fglobaldoflist=(int*)xmalloc(this->row_fsize*sizeof(int));
+		memcpy(this->row_fglobaldoflist,Ke->row_fglobaldoflist,this->row_fsize*sizeof(int));
+	}
+	else{
+		this->row_flocaldoflist=NULL;
+		this->row_fglobaldoflist=NULL;
+	}
+
+	this->row_ssize=Ke->row_ssize;
+	if(this->row_ssize){
+		this->row_slocaldoflist=(int*)xmalloc(this->row_ssize*sizeof(int));
+		memcpy(this->row_slocaldoflist,Ke->row_slocaldoflist,this->row_ssize*sizeof(int));
+		this->row_sglobaldoflist=(int*)xmalloc(this->row_ssize*sizeof(int));
+		memcpy(this->row_sglobaldoflist,Ke->row_sglobaldoflist,this->row_ssize*sizeof(int));
+	}
+	else{
+		this->row_slocaldoflist=NULL;
+		this->row_sglobaldoflist=NULL;
+	}
+
+	this->col_fsize=Ke->col_fsize;
+	if(this->col_fsize){
+		this->col_flocaldoflist=(int*)xmalloc(this->col_fsize*sizeof(int));
+		memcpy(this->col_flocaldoflist,Ke->col_flocaldoflist,this->col_fsize*sizeof(int));
+		this->col_fglobaldoflist=(int*)xmalloc(this->col_fsize*sizeof(int));
+		memcpy(this->col_fglobaldoflist,Ke->col_fglobaldoflist,this->col_fsize*sizeof(int));
+	}
+	else{
+		this->col_flocaldoflist=NULL;
+		this->col_fglobaldoflist=NULL;
+	}
+
+	this->col_ssize=Ke->col_ssize;
+	if(this->col_ssize){
+		this->col_slocaldoflist=(int*)xmalloc(this->col_ssize*sizeof(int));
+		memcpy(this->col_slocaldoflist,Ke->col_slocaldoflist,this->col_ssize*sizeof(int));
+		this->col_sglobaldoflist=(int*)xmalloc(this->col_ssize*sizeof(int));
+		memcpy(this->col_sglobaldoflist,Ke->col_sglobaldoflist,this->col_ssize*sizeof(int));
+	}
+	else{
+		this->col_slocaldoflist=NULL;
+		this->col_sglobaldoflist=NULL;
+	}
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::SetDiag{{{1*/
+void ElementMatrix::SetDiag(double scalar){
+
+	int i;
+
+	if(this->nrows!=this->ncols)_error_("need square matrix in input!");
+
+	for(i=0;i<this->nrows;i++){
+		this->values[this->ncols*i+i]=scalar;
+	}
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Numerics/ElementMatrix.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Numerics/ElementMatrix.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Numerics/ElementMatrix.h	(revision 11330)
@@ -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:*/
+/*{{{1*/
+#include "../Object.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+class Node;
+/*}}}*/
+
+class ElementMatrix{
+
+	public:
+	
+		int      nrows;
+		int      ncols;
+		bool     dofsymmetrical;
+		double*  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 {{{1*/
+		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 {{{1*/
+		void AddToGlobal(Mat Kff, Mat Kfs);
+		void Echo(void);
+		void CheckConsistency(void);
+		void Transpose(void);
+		void Init(ElementMatrix* Ke);
+		void SetDiag(double scalar);
+		/*}}}*/
+};
+#endif //#ifndef _ELEMENT_MATRIX_H_
Index: /issm/trunk-jpl-damage/src/c/objects/Numerics/ElementVector.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Numerics/ElementVector.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Numerics/ElementVector.cpp	(revision 11330)
@@ -0,0 +1,258 @@
+/*!\file ElementVector.cpp
+ * \brief: implementation of the ElementVector object, used to plug values from element into global load
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*ElementVector constructors and destructor*/
+/*FUNCTION ElementVector::ElementVector(){{{1*/
+ElementVector::ElementVector(){
+
+	this->nrows=0;
+	this->values=NULL;
+	this->fsize=0;
+	this->flocaldoflist=NULL;
+	this->fglobaldoflist=NULL;
+
+}
+/*}}}*/
+/*FUNCTION ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2){{{1*/
+ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2){
+
+	/*intermediaries*/
+	int i,j,counter;
+	int gsize,fsize,ssize;
+	int* P=NULL;
+	bool found;
+
+	/*If one of the two matrix is NULL, we copy the other one*/
+	if(!pe1 && !pe2){
+		_error_("Two input element matrices are NULL");
+	}
+	else if(!pe1){
+		this->Init(pe2);
+		return;
+	}
+	else if(!pe2){
+		this->Init(pe1);
+		return;
+	}
+
+	/*Initialize itransformation matrix pe[P[i]] = pe2[i]*/
+	P=(int*)xmalloc(pe2->nrows*sizeof(int));
+
+	/*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=(int*)xmalloc(this->nrows*sizeof(int));
+	this->values=(double*)xcalloc(this->nrows,sizeof(double));
+	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 =(int*)xmalloc(fsize*sizeof(int));
+		this->fglobaldoflist=(int*)xmalloc(fsize*sizeof(int));
+		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*/
+	xfree((void**)&P);
+}
+/*}}}*/
+/*FUNCTION ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2,ElementVector* pe3){{{1*/
+ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2,ElementVector* pe3){
+
+	/*Concatenate all matrices*/
+	ElementVector* pe12 =new ElementVector(pe1,pe2);
+	ElementVector* pe123=new ElementVector(pe12,pe3);
+
+	/*Initialize current object with this matrix*/
+	this->Init(pe123);
+
+	/*clean-up*/
+	delete pe12;
+	delete pe123;
+}
+/*}}}*/
+/*FUNCTION ElementVector::ElementVector(Node** nodes,int numnodes,Parameters* parameters,int approximation){{{1*/
+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=(double*)xcalloc(this->nrows,sizeof(double));
+	
+	/*g list*/
+	this->gglobaldoflist=GetGlobalDofList(nodes,numnodes,GsetEnum,approximation);
+
+	/*Get fsize*/
+	this->fsize=GetNumberOfDofs(nodes,numnodes,FsetEnum,approximation);
+	this->flocaldoflist =GetLocalDofList( nodes,numnodes,FsetEnum,approximation);
+	this->fglobaldoflist=GetGlobalDofList(nodes,numnodes,FsetEnum,approximation);
+}
+/*}}}*/
+/*FUNCTION ElementVector::~ElementVector(){{{1*/
+ElementVector::~ElementVector(){
+	
+	xfree((void**)&this->values);
+	xfree((void**)&this->gglobaldoflist);
+	xfree((void**)&this->flocaldoflist);
+	xfree((void**)&this->fglobaldoflist);
+}
+/*}}}*/
+
+/*ElementVector specific routines: */
+/*FUNCTION ElementVector::AddToGlobal(Vec pf){{{1*/
+void ElementVector::AddToGlobal(Vec pf){
+
+	int i;
+	double* localvalues=NULL;
+
+	if(this->fsize){
+		/*first, retrieve values that are in the f-set from the g-set values vector: */
+		localvalues=(double*)xmalloc(this->fsize*sizeof(double));
+		for(i=0;i<this->fsize;i++){
+			localvalues[i]=this->values[this->flocaldoflist[i]];
+		}
+		/*add local values into global  vector, using the fglobaldoflist: */
+		VecSetValues(pf,this->fsize,this->fglobaldoflist,(const double*)localvalues,ADD_VALUES);
+
+		/*Free ressources:*/
+		xfree((void**)&localvalues);
+	}
+}
+/*}}}*/
+/*FUNCTION ElementVector::InsertIntoGlobal(Vec pf){{{1*/
+void ElementVector::InsertIntoGlobal(Vec pf){
+
+	int i;
+	double* localvalues=NULL;
+
+	if(this->fsize){
+		/*first, retrieve values that are in the f-set from the g-set values vector: */
+		localvalues=(double*)xmalloc(this->fsize*sizeof(double));
+		for(i=0;i<this->fsize;i++){
+			localvalues[i]=this->values[this->flocaldoflist[i]];
+		}
+		/*add local values into global  vector, using the fglobaldoflist: */
+		VecSetValues(pf,this->fsize,this->fglobaldoflist,(const double*)localvalues,INSERT_VALUES);
+
+		/*Free ressources:*/
+		xfree((void**)&localvalues);
+	}
+}
+/*}}}*/
+/*FUNCTION ElementVector::Echo{{{1*/
+void ElementVector::Echo(void){
+
+	int i,j;
+	printf("Element Vector echo: \n");
+	printf("   nrows: %i\n",nrows);
+
+	printf("   values: \n");
+	for(i=0;i<nrows;i++){
+		printf("      %i: %10g\n",i,values[i]);
+	}
+
+	printf("   gglobaldoflist (%p): ",gglobaldoflist);
+	if(gglobaldoflist) for(i=0;i<nrows;i++)printf("%i ",gglobaldoflist[i]); printf("\n");
+
+	printf("   fsize: %i\n",fsize);
+	printf("   flocaldoflist (%p): ",flocaldoflist);
+	if(flocaldoflist) for(i=0;i<fsize;i++)printf("%i ",flocaldoflist[i]); printf("\n");
+	printf("   fglobaldoflist (%p): ",fglobaldoflist);
+	if(fglobaldoflist)for(i=0;i<fsize;i++)printf("%i ",fglobaldoflist[i]); printf("\n");
+}
+/*}}}*/
+/*FUNCTION ElementVector::Init{{{1*/
+void ElementVector::Init(ElementVector* pe){
+
+	_assert_(pe);
+
+	this->nrows =pe->nrows;
+
+	this->values=(double*)xmalloc(this->nrows*sizeof(double));
+	memcpy(this->values,pe->values,this->nrows*sizeof(double));
+
+	this->gglobaldoflist=(int*)xmalloc(this->nrows*sizeof(int));
+	memcpy(this->gglobaldoflist,pe->gglobaldoflist,this->nrows*sizeof(int));
+
+	this->fsize=pe->fsize;
+	if(this->fsize){
+		this->flocaldoflist=(int*)xmalloc(this->fsize*sizeof(int));
+		memcpy(this->flocaldoflist,pe->flocaldoflist,this->fsize*sizeof(int));
+		this->fglobaldoflist=(int*)xmalloc(this->fsize*sizeof(int));
+		memcpy(this->fglobaldoflist,pe->fglobaldoflist,this->fsize*sizeof(int));
+	}
+	else{
+		this->flocaldoflist=NULL;
+		this->fglobaldoflist=NULL;
+	}
+}
+/*}}}*/
+/*FUNCTION ElementVector::SetValue{{{1*/
+void ElementVector::SetValue(double scalar){
+
+	int i;
+
+	for(i=0;i<this->nrows;i++)this->values[i]=scalar;
+
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Numerics/ElementVector.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Numerics/ElementVector.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Numerics/ElementVector.h	(revision 11330)
@@ -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:*/
+/*{{{1*/
+#include "../Object.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+class Node;
+/*}}}*/
+
+class ElementVector{
+
+	public:
+	
+		int      nrows;
+		double*  values;
+		
+		//gset
+		int*     gglobaldoflist;
+
+		//fset
+		int      fsize;
+		int*     flocaldoflist;
+		int*     fglobaldoflist;
+		
+		/*ElementVector constructors, destructors {{{1*/
+		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 {{{1*/
+		void AddToGlobal(Vec pf);
+		void InsertIntoGlobal(Vec pf);
+		void Echo(void);
+		void Init(ElementVector* pe);
+		void SetValue(double scalar);
+		/*}}}*/
+};
+#endif //#ifndef _ELEMENT_VECTOR_H_
+
Index: /issm/trunk-jpl-damage/src/c/objects/Object.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Object.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Object.h	(revision 11330)
@@ -0,0 +1,32 @@
+/*
+ * Object.h:
+ * \brief prototype for abstract Object class
+ * \file Object.h
+ * This prototype describes the Object class. This is an abstract class, parent 
+ * to any other objects (Quad, Tria, Node , etc ...), that can be included in a 
+ * DataSet.
+ */
+
+
+#ifndef _OBJECT_H_
+#define _OBJECT_H_
+
+class Object {
+
+	public: 
+
+		virtual       ~Object() {};
+		virtual void  Echo()=0;
+		virtual void  DeepEcho()=0;
+		virtual int   Id()=0;
+		virtual int   MyRank()=0;
+		#ifdef _SERIAL_
+		virtual void  Marshall(char** pmarshalled_dataset)=0;
+		virtual int   MarshallSize()=0;
+		virtual void  Demarshall(char** pmarshalled_dataset)=0;
+		#endif
+		virtual int   ObjectEnum()=0;
+		virtual Object* copy()=0;
+
+};
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/OptArgs.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/OptArgs.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/OptArgs.h	(revision 11330)
@@ -0,0 +1,24 @@
+/*!\file:  OptArgs.h
+ * \brief place holder for optimization function arguments
+ */ 
+
+#ifndef _OPTARGS_H_
+#define _OPTARGS_H_
+
+#ifdef _SERIAL_
+
+#include "mex.h"
+struct OptArgs{
+	char* function_name;
+	mxArray* femmodel;
+};
+
+#else
+
+class Model;
+struct OptArgs{
+	FemModel* femmodel;
+};
+#endif
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/OptPars.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/OptPars.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/OptPars.h	(revision 11330)
@@ -0,0 +1,17 @@
+/*!\file:  OptPars.h
+ * \brief place holder for optimization parameters
+ */ 
+
+#ifndef _OPTPARS_H_
+#define _OPTPARS_H_
+
+struct OptPars{
+
+	double xmin;
+	double xmax;
+	double cm_jump;
+	int maxiter;
+
+};
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Options/Option.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/Option.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/Option.cpp	(revision 11330)
@@ -0,0 +1,116 @@
+/*!\file Option.cpp
+ * \brief: implementation of the optionsobject abstract object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../io/io.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION Option::Option(){{{1*/
+Option::Option(){
+
+	name  =NULL;
+	numel =0;
+	ndims =0;
+	size  =NULL;
+
+}
+/*}}}*/
+/*FUNCTION Option::~Option(){{{1*/
+Option::~Option(){
+
+	if(size) xfree((void**)&size);
+	if(name) xfree((void**)&name);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION Option::Echo {{{1*/
+void  Option::Echo(){
+
+	char  cstr[81];
+	bool  flag=true;
+
+	_printf_(flag,"          name: \"%s\"\n" ,name);
+	_printf_(flag,"         numel: %d\n"     ,numel);
+	_printf_(flag,"         ndims: %d\n"     ,ndims);
+	if(size){
+		StringFromSize(cstr,size,ndims);
+		_printf_(flag,"          size: %s\n" ,cstr);
+	}
+	else _printf_(flag,"          size: [empty]\n" );
+}
+/*}}}*/
+/*FUNCTION Option::DeepEcho() {{{1*/
+void  Option::DeepEcho(){
+
+	char  indent[81]="";
+
+	Option::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Option::DeepEcho(char* indent) {{{1*/
+void  Option::DeepEcho(char* indent){
+
+	char  cstr[81];
+	bool  flag=true;
+
+	_printf_(flag,"%s          name: \"%s\"\n" ,indent,name);
+	_printf_(flag,"%s         numel: %d\n"     ,indent,numel);
+	_printf_(flag,"%s         ndims: %d\n"     ,indent,ndims);
+	if(size){
+		StringFromSize(cstr,size,ndims);
+		_printf_(flag,"%s          size: %s\n" ,indent,cstr);
+	}
+	else _printf_(flag,"%s          size: [empty]\n" ,indent);
+}
+/*}}}*/
+/*FUNCTION Option::Name {{{1*/
+char* Option::Name(){
+
+	return(name);
+}
+/*}}}*/
+/*FUNCTION Option::NumEl {{{1*/
+int   Option::NumEl(){
+
+	return(numel);
+}
+/*}}}*/
+/*FUNCTION Option::NDims {{{1*/
+int   Option::NDims(){
+
+	return(ndims);
+}
+/*}}}*/
+/*FUNCTION Option::Size {{{1*/
+int*  Option::Size(){
+
+	return(size);
+}
+/*}}}*/
+/*FUNCTION Option::Get {{{1*/
+//void* Option::Get(){
+
+//	;
+
+//	return;
+//}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Options/Option.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/Option.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/Option.h	(revision 11330)
@@ -0,0 +1,59 @@
+/*! \file Option.h 
+ *  \brief: header file for option abstract object
+ */
+
+#ifndef _OPTIONOBJECT_H_
+#define _OPTIONOBJECT_H_
+
+/*Headers:{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "../Object.h"
+/*}}}*/
+
+class Option: public Object {
+
+	public:
+
+		char* name;
+		int   numel;
+		int   ndims;
+		int*  size;
+
+		/*Option constructors, destructors {{{1*/
+		Option();
+		~Option();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		virtual void  Echo();
+		virtual void  DeepEcho();
+		virtual void  DeepEcho(char* indent);
+		int   Id(){_error_("Not implemented yet");};
+		int   MyRank(){_error_("Not implemented yet");};
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet");};
+		int   MarshallSize(){_error_("Not implemented yet");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet");};
+		#endif
+		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;
+		virtual void  Get(double* pvalue)=0;
+		virtual void  Get(bool* pvalue)=0;
+		virtual void  Get(char** pvalue)=0;
+		virtual void  Get(char*** ppvalue,int *pnumel)=0;
+		virtual void  Get(double** pvalue,int *pnumel)=0;
+		virtual void  Get(Options** pvalue)=0;
+		virtual void  Get(Options*** ppvalue,int *pnumel)=0;
+
+};
+#endif  /* _OPTIONOBJECT_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/Options/OptionCell.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/OptionCell.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/OptionCell.cpp	(revision 11330)
@@ -0,0 +1,127 @@
+/*!\file OptionCell.cpp
+ * \brief: implementation of the optionscell object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION OptionCell::OptionCell(){{{1*/
+OptionCell::OptionCell(){
+
+	values    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION OptionCell::~OptionCell(){{{1*/
+OptionCell::~OptionCell(){
+
+	if (values){
+		delete values;
+		values    =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION OptionCell::Echo {{{1*/
+void  OptionCell::Echo(){
+
+	char cstr[81];
+	bool flag     = true;
+
+	_printf_(flag,"OptionCell Echo:\n");
+	Option::Echo();
+
+	if (values && size) {
+		StringFromSize(cstr,size,ndims);
+		_printf_(flag,"        values: %s %s\n" ,cstr,"cell");
+	}
+	else _printf_(flag,"        values: [empty]\n" );
+}
+/*}}}*/
+/*FUNCTION OptionCell::DeepEcho() {{{1*/
+void  OptionCell::DeepEcho(){
+
+	char  indent[81]="";
+
+	OptionCell::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION OptionCell::DeepEcho(char* indent) {{{1*/
+void  OptionCell::DeepEcho(char* indent){
+
+	int   i;
+	int*  dims;
+	char  indent2[81];
+	char  cstr[81];
+	bool  flag=true;
+
+	_printf_(flag,"%sOptionCell DeepEcho:\n",indent);
+	Option::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (values->Size()) {
+		dims=(int *) xmalloc(ndims*sizeof(int));
+		for (i=0; i<values->Size(); i++) {
+			ColumnWiseDimsFromIndex(dims,i,size,ndims);
+			StringFromDims(cstr,dims,ndims);
+			_printf_(flag,"%s        values: -------- begin %s --------\n" ,indent,cstr);
+			((Option *)values->GetObjectByOffset(i))->DeepEcho(indent2);
+			_printf_(flag,"%s        values: --------  end  %s --------\n" ,indent,cstr);
+		}
+		xfree((void**)&dims);
+	}
+	else _printf_(flag,"%s        values: [empty]\n" ,indent);
+}
+/*}}}*/
+/*FUNCTION OptionCell::Name {{{1*/
+char* OptionCell::Name(){
+
+	return(Option::Name());
+}
+/*}}}*/
+/*FUNCTION OptionCell::NumEl {{{1*/
+int   OptionCell::NumEl(){
+
+	return(Option::NumEl());
+}
+/*}}}*/
+/*FUNCTION OptionCell::NDims {{{1*/
+int   OptionCell::NDims(){
+
+	return(Option::NDims());
+}
+/*}}}*/
+/*FUNCTION OptionCell::Size {{{1*/
+int*  OptionCell::Size(){
+
+	return(Option::Size());
+}
+/*}}}*/
+/*FUNCTION OptionCell::Get(Options** pvalue) {{{1*/
+void OptionCell::Get(Options** pvalue){
+
+	/*Assign output pointer*/
+	*pvalue=this->values;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Options/OptionCell.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/OptionCell.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/OptionCell.h	(revision 11330)
@@ -0,0 +1,56 @@
+/*! \file OptionCell.h 
+ *  \brief: header file for optioncell object
+ */
+
+#ifndef _OPTIONCELL_H_
+#define _OPTIONCELL_H_
+
+/*Headers:{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./Option.h"
+/*}}}*/
+
+class OptionCell: public Option {
+
+	public:
+
+		Options* values;
+
+		/*OptionCell constructors, destructors {{{1*/
+		OptionCell();
+		~OptionCell();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(char* indent);
+		int   Id(){_error_("Not implemented yet");};
+		int   MyRank(){_error_("Not implemented yet");};
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet");};
+		int   MarshallSize(){_error_("Not implemented yet");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet");};
+		#endif
+		int   ObjectEnum(){return OptionCellEnum;};
+		Object* copy(){_error_("Not implemented yet");};
+		/*}}}*/
+
+		/*virtual functions: */
+		char* Name();
+		int   NumEl();
+		int   NDims();
+		int*  Size();
+		void  Get(double* pvalue){_error_("An OptionCell object cannot return a double");};
+		void  Get(bool* pvalue){  _error_("An OptionCell object cannot return a bool");};
+		void  Get(char** pvalue){ _error_("An OptionCell object cannot return a string");};
+		void  Get(char*** ppvalue,int *pnumel){ _error_("An OptionCell object cannot return a string vec");};
+		void  Get(double** pvalue,int *pnumel){ _error_("An OptionCell object cannot return a double vec");};
+		void  Get(Options** pvalue);
+		void  Get(Options*** ppvalue,int *pnumel){ _error_("An OptionCell object cannot return an Options DataSet vec");};
+
+};
+#endif  /* _OPTIONCELL_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/Options/OptionChar.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/OptionChar.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/OptionChar.cpp	(revision 11330)
@@ -0,0 +1,176 @@
+/*!\file OptionChar.cpp
+ * \brief: implementation of the optionschar object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION OptionChar::OptionChar(){{{1*/
+OptionChar::OptionChar(){
+
+	values    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION OptionChar::~OptionChar(){{{1*/
+OptionChar::~OptionChar(){
+
+	if (values) xfree((void**)&values);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION OptionChar::Echo {{{1*/
+void  OptionChar::Echo(){
+
+	char  cstr[81];
+	bool  flag=true;
+
+	_printf_(flag,"OptionChar Echo:\n");
+	Option::Echo();
+
+	if (values && size) {
+//		if (numel == 1) {
+		if (1) {
+//			_printf_(flag,"        values: \"%s\"\n" ,values[0]);
+			_printf_(flag,"        values: \"%s\"\n" ,values);
+		}
+		else {
+			StringFromSize(cstr,size,ndims);
+			_printf_(flag,"        values: %s %s\n" ,cstr,"char");
+		}
+	}
+	else _printf_(flag,"        values: [empty]\n" );
+}
+/*}}}*/
+/*FUNCTION OptionChar::DeepEcho() {{{1*/
+void  OptionChar::DeepEcho(){
+
+	char  indent[81]="";
+
+	OptionChar::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION OptionChar::DeepEcho(char* indent) {{{1*/
+void  OptionChar::DeepEcho(char* indent){
+
+	int   i,nstr,ipt=0;
+	int*  dims;
+	char  indent2[81];
+	char  cstr[81];
+	bool  flag=true;
+
+	_printf_(flag,"%sOptionChar DeepEcho:\n",indent);
+	Option::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (values) {
+		if (ndims == 2 && size[0] == 1) {
+			_printf_(flag,"%s        values: \"%s\"\n" ,indent,values);
+		}
+		else {
+			nstr=size[0];
+			for (i=2; i<ndims; i++) nstr*=size[i];
+
+			dims=(int *) xmalloc(ndims*sizeof(int));
+			for (i=0; i<nstr; i++) {
+				RowWiseDimsFromIndex(dims,ipt,size,ndims);
+				StringFromDims(cstr,dims,ndims);
+				_printf_(flag,"%s        values%s: \"%.*s\"\n" ,indent,cstr,size[1],&(values[ipt]));
+				ipt+=size[1];
+			}
+			xfree((void**)&dims);
+		}
+	}
+	else _printf_(flag,"%s        values: [empty]\n" ,indent);
+}
+/*}}}*/
+/*FUNCTION OptionChar::Name {{{1*/
+char* OptionChar::Name(){
+
+	return(Option::Name());
+}
+/*}}}*/
+/*FUNCTION OptionChar::NumEl {{{1*/
+int   OptionChar::NumEl(){
+
+	return(Option::NumEl());
+}
+/*}}}*/
+/*FUNCTION OptionChar::NDims {{{1*/
+int   OptionChar::NDims(){
+
+	return(Option::NDims());
+}
+/*}}}*/
+/*FUNCTION OptionChar::Size {{{1*/
+int*  OptionChar::Size(){
+
+	return(Option::Size());
+}
+/*}}}*/
+/*FUNCTION OptionChar::Get(char** pvalue) {{{1*/
+void OptionChar::Get(char** pvalue){
+
+	char* outstring=NULL;
+	int   stringsize;
+
+	stringsize=strlen(this->values)+1;
+
+	outstring=(char*)xmalloc(stringsize*sizeof(char));
+	memcpy(outstring,this->values,stringsize*sizeof(char));
+
+	*pvalue=outstring;
+}
+/*}}}*/
+/*FUNCTION OptionChar::Get(char*** ppvalue,int *pnumel) {{{1*/
+void OptionChar::Get(char*** ppvalue,int *pnumel){
+
+	char* outstring=NULL;
+	int   stringsize;
+	int   i,nstr,ipt=0;
+
+	/*We should first check that the size is at least one*/
+	if(this->NumEl()<=0){
+		_error_("option \"%s\" is empty and cannot return a string vector",this->name);
+	}
+
+	/*Calculate the size and number of strings*/
+	stringsize=this->size[1]+1;
+	nstr=this->size[0];
+	for (i=2; i<this->ndims; i++) nstr*=this->size[i];
+
+	/*Break concatenated string into individual strings*/
+	*ppvalue=(char **) xmalloc(nstr*sizeof(char *));
+	for (i=0; i<nstr; i++) {
+		outstring=(char*)xmalloc(stringsize*sizeof(char));
+		memcpy(outstring,&(this->values[ipt]),(stringsize-1)*sizeof(char));
+		outstring[stringsize-1]='\0';
+		(*ppvalue)[i]=outstring;
+		ipt+=stringsize-1;
+	}
+
+	/*Assign output pointer*/
+	if(numel) *pnumel=nstr;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Options/OptionChar.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/OptionChar.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/OptionChar.h	(revision 11330)
@@ -0,0 +1,56 @@
+/*! \file OptionChar.h 
+ *  \brief: header file for optionchar object
+ */
+
+#ifndef _OPTIONCHAR_H_
+#define _OPTIONCHAR_H_
+
+/*Headers:{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./Option.h"
+/*}}}*/
+
+class OptionChar: public Option {
+
+	public:
+
+		char* values;
+
+		/*OptionChar constructors, destructors {{{1*/
+		OptionChar();
+		~OptionChar();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(char* indent);
+		int   Id(){_error_("Not implemented yet");};
+		int   MyRank(){_error_("Not implemented yet");};
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet");};
+		int   MarshallSize(){_error_("Not implemented yet");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet");};
+		#endif
+		int   ObjectEnum(){return OptionCharEnum;};
+		Object* copy(){_error_("Not implemented yet");};
+		/*}}}*/
+
+		/*virtual functions: */
+		char* Name();
+		int   NumEl();
+		int   NDims();
+		int*  Size();
+		void  Get(double* pvalue){_error_("An OptionChar object cannot return a double");};
+		void  Get(bool* pvalue){  _error_("An OptionChar object cannot return a bool");};
+		void  Get(char** pvalue);
+		void  Get(char*** ppvalue,int *pnumel);
+		void  Get(double** pvalue,int *pnumel){ _error_("An OptionChar object cannot return a double vec");};
+		void  Get(Options** pvalue){ _error_("An OptionChar object cannot return an Options DataSet");};
+		void  Get(Options*** ppvalue,int *pnumel){ _error_("An OptionChar object cannot return an Options DataSet vec");};
+
+};
+#endif  /* _OPTIONCHAR_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/Options/OptionDouble.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/OptionDouble.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/OptionDouble.cpp	(revision 11330)
@@ -0,0 +1,150 @@
+/*!\file OptionDouble.cpp
+ * \brief: implementation of the optionsdouble object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION OptionDouble::OptionDouble(){{{1*/
+OptionDouble::OptionDouble(){
+
+	values    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION OptionDouble::~OptionDouble(){{{1*/
+OptionDouble::~OptionDouble(){
+
+	if (values) xfree((void**)&values);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION OptionDouble::Echo {{{1*/
+void  OptionDouble::Echo(){
+
+	char  cstr[81];
+	bool  flag=true;
+
+	_printf_(flag,"OptionDouble Echo:\n");
+	Option::Echo();
+
+	if (values && size) {
+		if(numel == 1) _printf_(flag,"        values: %g\n" ,values[0]);
+		else {
+			StringFromSize(cstr,size,ndims);
+			_printf_(flag,"        values: %s %s\n" ,cstr,"double");
+		}
+	}
+	else _printf_(flag,"        values: [empty]\n" );
+}
+/*}}}*/
+/*FUNCTION OptionDouble::DeepEcho() {{{1*/
+void  OptionDouble::DeepEcho(){
+
+	char  indent[81]="";
+
+	OptionDouble::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION OptionDouble::DeepEcho(char* indent) {{{1*/
+void  OptionDouble::DeepEcho(char* indent){
+
+	int   i;
+	int*  dims;
+	char  indent2[81];
+	char  cstr[81];
+	bool  flag=true;
+
+	_printf_(flag,"%sOptionDouble DeepEcho:\n",indent);
+	Option::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (values) {
+		dims=(int *) xmalloc(ndims*sizeof(int));
+		if(numel==1) _printf_(flag,"%s        values: %g\n" ,indent,values[0]);
+		else{
+			for (i=0; i<numel; i++) {
+				RowWiseDimsFromIndex(dims,i,size,ndims);
+				StringFromDims(cstr,dims,ndims);
+				_printf_(flag,"%s        values%s: %g\n" ,indent,cstr,values[i]);
+			}
+		}
+		xfree((void**)&dims);
+	}
+	else _printf_(flag,"%s        values: [empty]\n" ,indent);
+}
+/*}}}*/
+/*FUNCTION OptionDouble::Name {{{1*/
+char* OptionDouble::Name(){
+
+	return(Option::Name());
+}
+/*}}}*/
+/*FUNCTION OptionDouble::NumEl {{{1*/
+int   OptionDouble::NumEl(){
+
+	return(Option::NumEl());
+}
+/*}}}*/
+/*FUNCTION OptionDouble::NDims {{{1*/
+int   OptionDouble::NDims(){
+
+	return(Option::NDims());
+}
+/*}}}*/
+/*FUNCTION OptionDouble::Size {{{1*/
+int*  OptionDouble::Size(){
+
+	return(Option::Size());
+}
+/*}}}*/
+/*FUNCTION OptionDouble::Get(double* pvalue) {{{1*/
+void OptionDouble::Get(double* pvalue){
+
+	/*We should first check that the size is one*/
+	if(this->NumEl()!=1){
+		_error_("option \"%s\" has %i elements and cannot return a single double",this->name,this->NumEl());
+	}
+
+	/*Assign output pointer*/
+	*pvalue=this->values[0];
+}
+/*}}}*/
+/*FUNCTION OptionDouble::Get(double** pvalue,int* numel) {{{1*/
+void OptionDouble::Get(double** pvalue,int* numel){
+
+	/*We should first check that the size is at least one*/
+	if(this->NumEl()<=0){
+		_error_("option \"%s\" is empty and cannot return a double vector",this->name);
+	}
+
+	/*Copy vector*/
+	double* outvalue=(double*)xmalloc(this->NumEl()*sizeof(double));
+	for(int i=0;i<this->NumEl();i++) outvalue[i]=this->values[i];
+
+	/*Assign output pointer*/
+	*pvalue=outvalue;
+	if(numel) *numel=this->NumEl();
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Options/OptionDouble.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/OptionDouble.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/OptionDouble.h	(revision 11330)
@@ -0,0 +1,56 @@
+/*! \file OptionDouble.h 
+ *  \brief: header file for optiondouble object
+ */
+
+#ifndef _OPTIONDOUBLE_H_
+#define _OPTIONDOUBLE_H_
+
+/*Headers:{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./Option.h"
+/*}}}*/
+
+class OptionDouble: public Option {
+
+	public:
+
+		double* values;
+
+		/*OptionDouble constructors, destructors {{{1*/
+		OptionDouble();
+		~OptionDouble();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(char* indent);
+		int   Id(){_error_("Not implemented yet");};
+		int   MyRank(){_error_("Not implemented yet");};
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet");};
+		int   MarshallSize(){_error_("Not implemented yet");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet");};
+		#endif
+		int   ObjectEnum(){return OptionDoubleEnum;};
+		Object* copy(){_error_("Not implemented yet");};
+		/*}}}*/
+
+		/*virtual functions: */
+		char* Name();
+		int   NumEl();
+		int   NDims();
+		int*  Size();
+		void  Get(double* pvalue);
+		void  Get(bool* pvalue){  _error_("An OptionDouble object cannot return a bool");};
+		void  Get(char** pvalue){ _error_("An OptionDouble object cannot return a string");};
+		void  Get(char*** ppvalue,int *pnumel){ _error_("An OptionDouble object cannot return a string vec");};
+		void  Get(double** pvalue,int* pnumel);
+		void  Get(Options** pvalue){ _error_("An OptionDouble object cannot return an Options DataSet");};
+		void  Get(Options*** ppvalue,int *pnumel){ _error_("An OptionDouble object cannot return an Options DataSet vec");};
+
+};
+#endif  /* _OPTIONDOUBLE_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/Options/OptionLogical.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/OptionLogical.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/OptionLogical.cpp	(revision 11330)
@@ -0,0 +1,133 @@
+/*!\file OptionLogical.cpp
+ * \brief: implementation of the optionslogical object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION OptionLogical::OptionLogical(){{{1*/
+OptionLogical::OptionLogical(){
+
+	values    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION OptionLogical::~OptionLogical(){{{1*/
+OptionLogical::~OptionLogical(){
+
+	if (values) xfree((void**)&values);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION OptionLogical::Echo {{{1*/
+void  OptionLogical::Echo(){
+
+	char  cstr[81];
+	bool  flag=true;
+
+	_printf_(flag,"OptionLogical Echo:\n");
+	Option::Echo();
+
+	if (values && size) {
+		if(numel == 1) _printf_(flag,"        values: %s\n" ,(values[0] ? "true" : "false"));
+		else{
+			StringFromSize(cstr,size,ndims);
+			_printf_(flag,"        values: %s %s\n" ,cstr,"logical");
+		}
+	}
+	else _printf_(flag,"        values: [empty]\n" );
+}
+/*}}}*/
+/*FUNCTION OptionLogical::DeepEcho() {{{1*/
+void  OptionLogical::DeepEcho(){
+
+	char  indent[81]="";
+
+	OptionLogical::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION OptionLogical::DeepEcho(char* indent) {{{1*/
+void  OptionLogical::DeepEcho(char* indent){
+
+	int   i;
+	int*  dims;
+	char  indent2[81];
+	char  cstr[81];
+	bool  flag=true;
+
+	_printf_(flag,"%sOptionLogical DeepEcho:\n",indent);
+	Option::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (values) {
+		if(numel==1) _printf_(flag,"%s        values: %s\n" ,indent,(values[0] ? "true" : "false"));
+		else{
+			dims=(int *) xmalloc(ndims*sizeof(int));
+			for (i=0; i<numel; i++) {
+				RowWiseDimsFromIndex(dims,i,size,ndims);
+				StringFromDims(cstr,dims,ndims);
+				_printf_(flag,"%s        values%s: %s\n" ,indent,cstr,(values[i] ? "true" : "false"));
+			}
+			xfree((void**)&dims);
+		}
+	}
+	else _printf_(flag,"%s        values: [empty]\n" ,indent);
+}
+/*}}}*/
+/*FUNCTION OptionLogical::Name {{{1*/
+char* OptionLogical::Name(){
+
+	return(Option::Name());
+}
+/*}}}*/
+/*FUNCTION OptionLogical::NumEl {{{1*/
+int   OptionLogical::NumEl(){
+
+	return(Option::NumEl());
+}
+/*}}}*/
+/*FUNCTION OptionLogical::NDims {{{1*/
+int   OptionLogical::NDims(){
+
+	return(Option::NDims());
+}
+/*}}}*/
+/*FUNCTION OptionLogical::Size {{{1*/
+int*  OptionLogical::Size(){
+
+	return(Option::Size());
+}
+/*}}}*/
+/*FUNCTION OptionLogical::Get(bool* pvalue) {{{1*/
+void OptionLogical::Get(bool* pvalue){
+
+	/*We should first check that the size is one*/
+	if(this->NumEl()!=1){
+		_error_("option \"%s\" has %i elements and cannot return a single bool",this->name,this->NumEl());
+	}
+
+	/*Assign output pointer*/
+	*pvalue=this->values[0];
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Options/OptionLogical.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/OptionLogical.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/OptionLogical.h	(revision 11330)
@@ -0,0 +1,56 @@
+/*! \file OptionLogical.h 
+ *  \brief: header file for optionlogical object
+ */
+
+#ifndef _OPTIONLOGICAL_H_
+#define _OPTIONLOGICAL_H_
+
+/*Headers:{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./Option.h"
+/*}}}*/
+
+class OptionLogical: public Option {
+
+	public:
+
+		bool* values;
+
+		/*OptionLogical constructors, destructors {{{1*/
+		OptionLogical();
+		~OptionLogical();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(char* indent);
+		int   Id(){_error_("Not implemented yet");};
+		int   MyRank(){_error_("Not implemented yet");};
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet");};
+		int   MarshallSize(){_error_("Not implemented yet");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet");};
+		#endif
+		int   ObjectEnum(){return OptionLogicalEnum;};
+		Object* copy(){_error_("Not implemented yet");};
+		/*}}}*/
+
+		/*virtual functions: */
+		char* Name();
+		int   NumEl();
+		int   NDims();
+		int*  Size();
+		void  Get(double* pvalue){_error_("An OptionLogical object cannot return a double");};
+		void  Get(bool* pvalue);
+		void  Get(char** pvalue){ _error_("An OptionLogical object cannot return a string");};
+		void  Get(char*** ppvalue,int *pnumel){ _error_("An OptionLogical object cannot return a string vec");};
+		void  Get(double** pvalue,int *pnumel){ _error_("An OptionLogical object cannot return a double vec");};
+		void  Get(Options** pvalue){ _error_("An OptionLogical object cannot return an Options DataSet");};
+		void  Get(Options*** ppvalue,int *pnumel){ _error_("An OptionLogical object cannot return an Options DataSet vec");};
+
+};
+#endif  /* _OPTIONLOGICAL_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/Options/OptionStruct.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/OptionStruct.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/OptionStruct.cpp	(revision 11330)
@@ -0,0 +1,153 @@
+/*!\file OptionStruct.cpp
+ * \brief: implementation of the optionsstruct object
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../io/io.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION OptionStruct::OptionStruct(){{{1*/
+OptionStruct::OptionStruct(){
+
+	values    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION OptionStruct::~OptionStruct(){{{1*/
+OptionStruct::~OptionStruct(){
+
+	int   i;
+
+	if(values){
+		for(i=0; i<numel; i++) {
+			delete values[i];
+			values[i] =NULL;
+		}
+		xfree((void**)&values);
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION OptionStruct::Echo {{{1*/
+void  OptionStruct::Echo(){
+
+	char  cstr[81];
+	bool  flag=true;
+
+	_printf_(flag,"OptionStruct Echo:\n");
+	Option::Echo();
+
+	if (values && size) {
+		StringFromSize(cstr,size,ndims);
+		_printf_(flag,"        values: %s %s\n" ,cstr,"struct");
+	}
+	else _printf_(flag,"        values: [empty]\n" );
+}
+/*}}}*/
+/*FUNCTION OptionStruct::DeepEcho() {{{1*/
+void  OptionStruct::DeepEcho(){
+
+	char  indent[81]="";
+
+	OptionStruct::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION OptionStruct::DeepEcho(char* indent) {{{1*/
+void  OptionStruct::DeepEcho(char* indent){
+
+	int   i,j;
+	int*  dims;
+	char  indent2[81];
+	char  cstr[81];
+	bool  flag=true;
+
+	_printf_(flag,"%sOptionStruct DeepEcho:\n",indent);
+	Option::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (values) {
+		dims=(int *)xmalloc(ndims*sizeof(int));
+		for (i=0; i<numel; i++) {
+			ColumnWiseDimsFromIndex(dims,i,size,ndims);
+			StringFromDims(cstr,dims,ndims);
+			if (values[i]->Size()){
+				_printf_(flag,"%s        values: -------- begin %s --------\n" ,indent,cstr);
+				for (j=0; j<values[i]->Size(); j++) ((Option *)values[i]->GetObjectByOffset(j))->DeepEcho(indent2);
+				_printf_(flag,"%s        values: --------  end  %s --------\n" ,indent,cstr);
+			}
+			else _printf_(flag,"%s        values: %s [empty]\n" ,indent,cstr);
+		}
+		xfree((void**)&dims);
+	}
+	else _printf_(flag,"%s        values: [empty]\n" ,indent);
+}
+/*}}}*/
+/*FUNCTION OptionStruct::Name {{{1*/
+char* OptionStruct::Name(){
+
+	return(Option::Name());
+}
+/*}}}*/
+/*FUNCTION OptionStruct::NumEl {{{1*/
+int   OptionStruct::NumEl(){
+
+	return(Option::NumEl());
+}
+/*}}}*/
+/*FUNCTION OptionStruct::NDims {{{1*/
+int   OptionStruct::NDims(){
+
+	return(Option::NDims());
+}
+/*}}}*/
+/*FUNCTION OptionStruct::Size {{{1*/
+int*  OptionStruct::Size(){
+
+	return(Option::Size());
+}
+/*}}}*/
+/*FUNCTION OptionStruct::Get(Options** pvalue) {{{1*/
+void OptionStruct::Get(Options** pvalue){
+
+	/*We should first check that the size is one*/
+	if(this->NumEl()!=1){
+		_error_("option \"%s\" has %i elements and cannot return a single options dataset",this->name,this->NumEl());
+	}
+
+	/*Assign output pointer*/
+	*pvalue=this->values[0];
+}
+/*}}}*/
+/*FUNCTION OptionStruct::Get(Options*** ppvalue,int* numel) {{{1*/
+void OptionStruct::Get(Options*** ppvalue,int* numel){
+
+	/*We should first check that the size is at least one*/
+	if(this->NumEl()<=0){
+		_error_("option \"%s\" is empty and cannot return an options dataset vector",this->name);
+	}
+
+	/*Assign output pointer*/
+	*ppvalue=this->values;
+	if(numel) *numel=this->NumEl();
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Options/OptionStruct.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/OptionStruct.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/OptionStruct.h	(revision 11330)
@@ -0,0 +1,56 @@
+/*! \file OptionStruct.h 
+ *  \brief: header file for optionstruct object
+ */
+
+#ifndef _OPTIONSTRUCT_H_
+#define _OPTIONSTRUCT_H_
+
+/*Headers:{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./Option.h"
+/*}}}*/
+
+class OptionStruct: public Option {
+
+	public:
+
+		Options** values;
+
+		/*OptionStruct constructors, destructors {{{1*/
+		OptionStruct();
+		~OptionStruct();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(char* indent);
+		int   Id(){_error_("Not implemented yet");};
+		int   MyRank(){_error_("Not implemented yet");};
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet");};
+		int   MarshallSize(){_error_("Not implemented yet");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet");};
+		#endif
+		int   ObjectEnum(){return OptionStructEnum;};
+		Object* copy(){_error_("Not implemented yet");};
+		/*}}}*/
+
+		/*virtual functions: */
+		char* Name();
+		int   NumEl();
+		int   NDims();
+		int*  Size();
+		void  Get(double* pvalue){_error_("An OptionStruct object cannot return a double");};
+		void  Get(bool* pvalue){  _error_("An OptionStruct object cannot return a bool");};
+		void  Get(char** pvalue){ _error_("An OptionStruct object cannot return a string");};
+		void  Get(char*** ppvalue,int *pnumel){ _error_("An OptionStruct object cannot return a string vec");};
+		void  Get(double** pvalue,int *pnumel){ _error_("An OptionStruct object cannot return a double vec");};
+		void  Get(Options** pvalue);
+		void  Get(Options*** ppvalue,int *pnumel);
+
+};
+#endif  /* _OPTIONSTRUCT_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/Options/OptionUtilities.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/OptionUtilities.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/OptionUtilities.cpp	(revision 11330)
@@ -0,0 +1,114 @@
+/*!\file OptionUtilities.cpp
+ * \brief: implementation of the options utilities
+ */
+
+/*Headers:*/
+/*{{{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 "../objects.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*FUNCTION ColumnWiseDimsFromIndex{{{1*/
+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 %d exceeds number of elements %d.",index,aprod);
+
+	/*calculate the dimensions (being careful of integer division)  */
+	for (i=ndims-1; i>=0; i--) {
+		aprod=(int)(((double)aprod+0.5)/(double)size[i]);
+		dims[i]=(int)floor(((double)index+0.5)/(double)aprod);
+		index-=dims[i]*aprod;
+	}
+
+	return(0);
+}/*}}}*/
+/*FUNCTION IndexFromColumnWiseDims{{{1*/
+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 %d of %d exceeds size of %d.",i,dims[i],size[i]);
+	}
+
+	/*calculate the index  */
+	for (i=ndims-1; i>=0; i--){
+		index*=size[i];
+		index+=dims[i];
+	}
+
+	return(index);
+}/*}}}*/
+/*FUNCTION RowWiseDimsFromIndex{{{1*/
+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 %d exceeds number of elements %d.",index,aprod);
+
+	/*calculate the dimensions (being careful of integer division)  */
+	for (i=0; i<ndims; i++) {
+		aprod=(int)(((double)aprod+0.5)/(double)size[i]);
+		dims[i]=(int)floor(((double)index+0.5)/(double)aprod);
+		index-=dims[i]*aprod;
+	}
+
+	return(0);
+}/*}}}*/
+/*FUNCTION IndexFromRowWiseDims{{{1*/
+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 %d of %d exceeds size of %d.",i,dims[i],size[i]);
+	}
+
+	/*calculate the index  */
+	for (i=0; i<ndims; i++) {
+		index*=size[i];
+		index+=dims[i];
+	}
+
+	return(index);
+}/*}}}*/
+/*FUNCTION StringFromDims{{{1*/
+int StringFromDims(char* cstr, int* dims, int ndims) {
+
+	sprintf(&cstr[0],"[");
+	for(int i=0; i<ndims-1; i++) sprintf(&cstr[strlen(cstr)],"%d,",dims[i]);
+	sprintf(&cstr[strlen(cstr)],"%d]",dims[ndims-1]);
+
+	return(0);
+}/*}}}*/
+/*FUNCTION StringFromSize{{{1*/
+int StringFromSize(char* cstr, int* size, int ndims) {
+
+	sprintf(&cstr[0],"[");
+	for(int i=0; i<ndims-1; i++) sprintf(&cstr[strlen(cstr)],"%dx",size[i]);
+	sprintf(&cstr[strlen(cstr)],"%d]",size[ndims-1]);
+
+	return(0);
+}/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Options/OptionUtilities.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Options/OptionUtilities.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Options/OptionUtilities.h	(revision 11330)
@@ -0,0 +1,24 @@
+/*! \file OptionUtilities.h 
+ *  \brief: header file for option object utilities
+ */
+
+#ifndef _OPTIONUTILITIES_H_
+#define _OPTIONUTILITIES_H_
+
+/*Headers:{{{1*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./Option.h"
+/*}}}*/
+
+int ColumnWiseDimsFromIndex(int* dims, int index, int* size, int ndims);
+int IndexFromColumnWiseDims(int* dims, int* size, int ndims);
+int RowWiseDimsFromIndex(int* dims, int index, int* size, int ndims);
+int IndexFromRowWiseDims(int* dims, int* size, int ndims);
+int StringFromDims(char* cstr, int* dims, int ndims);
+int StringFromSize(char* cstr, int* size, int ndims);
+
+#endif  /* _OPTIONUTILITIES_H */
+
Index: /issm/trunk-jpl-damage/src/c/objects/Params/BoolParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/BoolParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/BoolParam.cpp	(revision 11330)
@@ -0,0 +1,149 @@
+/*!\file BoolParam.c
+ * \brief: implementation of the BoolParam object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*BoolParam constructors and destructor*/
+/*FUNCTION BoolParam::BoolParam(){{{1*/
+BoolParam::BoolParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolParam::BoolParam(int enum_type,IssmBool value){{{1*/
+BoolParam::BoolParam(int in_enum_type,IssmBool in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION BoolParam::~BoolParam(){{{1*/
+BoolParam::~BoolParam(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION BoolParam::Echo {{{1*/
+void BoolParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION BoolParam::DeepEcho{{{1*/
+void BoolParam::DeepEcho(void){
+
+	printf("BoolParam:\n");
+	printf("   enum:  %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %s\n",this->value?"true":"false");
+}
+/*}}}*/
+/*FUNCTION BoolParam::Id{{{1*/
+int    BoolParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION BoolParam::MyRank{{{1*/
+int    BoolParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION BoolParam::Marshall{{{1*/
+void  BoolParam::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of BoolParam: */
+	enum_value=BoolParamEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall BoolParam data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&value,sizeof(value));marshalled_dataset+=sizeof(value);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION BoolParam::MarshallSize{{{1*/
+int   BoolParam::MarshallSize(){
+	
+	return sizeof(value)+
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION BoolParam::Demarshall{{{1*/
+void  BoolParam::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&value,marshalled_dataset,sizeof(value));marshalled_dataset+=sizeof(value);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION BoolParam::ObjectEnum{{{1*/
+int BoolParam::ObjectEnum(void){
+
+	return BoolParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION BoolParam::copy{{{1*/
+Object* BoolParam::copy() {
+	
+	return new BoolParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*BoolParam virtual functions definitions: */
+/*FUNCTION BoolParam::GetParameterName{{{1*/
+void BoolParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION BoolParam::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  BoolParam::SetMatlabField(mxArray* dataref){
+	char* name=NULL;
+	this->GetParameterName(&name);
+	mxSetField( dataref, 0, name,mxCreateDoubleScalar((double)value));
+}
+#endif
+/*}}}*/
+/*FUNCTION BoolParam::UnitConversion{{{1*/
+void  BoolParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/BoolParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/BoolParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/BoolParam.h	(revision 11330)
@@ -0,0 +1,88 @@
+/*! \file BoolParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _BOOLPARAM_H_
+#define _BOOLPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class BoolParam: public Param{
+
+	public:
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		IssmBool value;
+
+		/*BoolParam constructors, destructors: {{{1*/
+		BoolParam();
+		BoolParam(int enum_type,IssmBool value);
+		~BoolParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){*pbool=value;}
+		void  GetParameterValue(int* pinteger){_error_("Bool param of enum %i (%s) cannot return an integer",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Bool param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Bool param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double* pdouble){_error_("Bool param of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char** pstring){_error_("Bool param of enum %i (%s) cannot return a string",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Bool param of enum %i (%s) cannot return a string arrayl",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM){_error_("Bool param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM, int* pN){_error_("Bool param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims){_error_("Bool param of enum %i (%s) cannot return a matrix array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Vec* pvec){_error_("Bool param of enum %i (%s) cannot return a Vec",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Mat* pmat){_error_("Bool param of enum %i (%s) cannot return a Mat",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(FILE** pfid){_error_("Bool param of enum %i (%s) cannot return a FILE",enum_type,EnumToStringx(enum_type));}
+
+		void  SetValue(bool boolean){this->value=boolean;}
+		void  SetValue(int integer){this->value=(bool)integer;}
+		void  SetValue(double scalar){this->value=(bool)scalar;}
+		void  SetValue(char* string){_error_("Bool param of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char** stringarray,int M){_error_("Bool param of enum %i (%s) cannot hold a string array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M){_error_("Bool param of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* pdoublearray,int M,int N){_error_("Bool param of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* intarray,int M){_error_("Bool param of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* pintarray,int M,int N){_error_("Bool param of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Vec vec){_error_("Bool param of enum %i (%s) cannot hold a Vec",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Mat mat){_error_("Bool param of enum %i (%s) cannot hold a Mat",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(FILE* fid){_error_("Bool param of enum %i (%s) cannot hold a FILE",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double** array, int M, int* mdim_array, int* ndim_array){_error_("Bool param of enum %i (%s) cannot hold an array of matrices",enum_type,EnumToStringx(enum_type));}
+		void  UnitConversion(int direction_enum);
+		
+		void GetParameterName(char**pname);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+		/*}}}*/
+};
+#endif  /* _BOOLPARAM_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Params/DoubleMatArrayParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/DoubleMatArrayParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/DoubleMatArrayParam.cpp	(revision 11330)
@@ -0,0 +1,399 @@
+/*!\file DoubleMatArrayParam.c
+ * \brief: implementation of the DoubleMatArrayParam object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*DoubleMatArrayParam constructors and destructor*/
+/*FUNCTION DoubleMatArrayParam::DoubleMatArrayParam(){{{1*/
+DoubleMatArrayParam::DoubleMatArrayParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::DoubleMatArrayParam(int enum_type,double** array, int M, int* mdim_array, int* ndim_array){{{1*/
+DoubleMatArrayParam::DoubleMatArrayParam(int in_enum_type,double** in_array, int in_M, int* in_mdim_array, int* in_ndim_array){
+
+	int i;
+	double* matrix=NULL;
+	int     m,n;
+
+	enum_type=in_enum_type;
+	M=in_M;
+	if(M){
+		array=(double**)xmalloc(M*sizeof(double*));
+		mdim_array=(int*)xmalloc(M*sizeof(int));
+		ndim_array=(int*)xmalloc(M*sizeof(int));
+
+		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=(double*)xmalloc(m*n*sizeof(double));
+				memcpy(matrix,in_array[i],m*n*sizeof(double));
+			}
+			else{
+				matrix=NULL;
+			}
+			array[i]=matrix;
+		}
+	}
+	else{
+		array=NULL;
+		mdim_array=NULL;
+		ndim_array=NULL;
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::~DoubleMatArrayParam(){{{1*/
+DoubleMatArrayParam::~DoubleMatArrayParam(){
+
+	int i;
+	double* matrix=NULL;
+
+	xfree((void**)&mdim_array);
+	xfree((void**)&ndim_array);
+
+	for(i=0;i<M;i++){
+		matrix=array[i];
+		xfree((void**)&matrix);
+	}
+	
+	xfree((void**)&array);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleMatArrayParam::Echo {{{1*/
+void DoubleMatArrayParam::Echo(void){
+
+	printf("DoubleMatArrayParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   array size: %i\n",this->M);
+	printf("   array pointer: %p\n",this->array);
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::DeepEcho{{{1*/
+void DoubleMatArrayParam::DeepEcho(void){
+
+	int i,j,k;
+	int m,n;
+	double* matrix=NULL;
+	
+	printf("DoubleMatArrayParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   array size: %i\n",this->M);
+	for(i=0;i<M;i++){
+		printf("   array %i (%ix%i):\n",i,mdim_array[i],ndim_array[i]);
+		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("%g ",*(matrix+n*j+k));
+			printf("\n");
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::Id{{{1*/
+int    DoubleMatArrayParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::MyRank{{{1*/
+int    DoubleMatArrayParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION DoubleMatArrayParam::Marshall{{{1*/
+void  DoubleMatArrayParam::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of DoubleMatArrayParam: */
+	enum_value=DoubleMatArrayParamEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall DoubleMatArrayParam data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&M,sizeof(M));marshalled_dataset+=sizeof(M);
+	if(M){
+		memcpy(marshalled_dataset,mdim_array,M*sizeof(int));marshalled_dataset+=M*sizeof(int);
+		memcpy(marshalled_dataset,ndim_array,M*sizeof(int));marshalled_dataset+=M*sizeof(int);
+		for(i=0;i<M;i++){
+			double* matrix=this->array[i];
+			int     m=this->mdim_array[i];
+			int     n=this->ndim_array[i];
+			memcpy(marshalled_dataset,&m,sizeof(m));marshalled_dataset+=sizeof(m);
+			memcpy(marshalled_dataset,&n,sizeof(n));marshalled_dataset+=sizeof(n);
+			if(m*n)memcpy(marshalled_dataset,matrix,m*n*sizeof(double));marshalled_dataset+=m*n*sizeof(double);
+		}
+	}
+	
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::MarshallSize{{{1*/
+int   DoubleMatArrayParam::MarshallSize(){
+
+	int size=0;
+	int i;
+
+	size+=sizeof(enum_type)+
+		sizeof(M)+
+		M*sizeof(int)+
+		M*sizeof(int);
+
+	for(i=0;i<M;i++){
+		int     m=this->mdim_array[i];
+		int     n=this->ndim_array[i];
+		size+=sizeof(m)+sizeof(n)+m*n*sizeof(double);
+	}
+	size+=sizeof(int); //sizeof(int) for enum value
+
+	return  size;
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::Demarshall{{{1*/
+void  DoubleMatArrayParam::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+	double* matrix=NULL;
+	int     m,n;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum value, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	
+	/*data: */
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	memcpy(&M,marshalled_dataset,sizeof(M));marshalled_dataset+=sizeof(M);
+	if(M){
+		this->mdim_array=(int*)xmalloc(M*sizeof(int));
+		this->ndim_array=(int*)xmalloc(M*sizeof(int));
+		memcpy(this->mdim_array,marshalled_dataset,M*sizeof(int));marshalled_dataset+=M*sizeof(int);
+		memcpy(this->ndim_array,marshalled_dataset,M*sizeof(int));marshalled_dataset+=M*sizeof(int);
+
+		this->array=(double**)xmalloc(M*sizeof(double*));
+		for(i=0;i<M;i++){
+			memcpy(&m,marshalled_dataset,sizeof(m));marshalled_dataset+=sizeof(m);
+			memcpy(&n,marshalled_dataset,sizeof(n));marshalled_dataset+=sizeof(n);
+			if(m*n){
+				matrix=(double*)xmalloc(m*n*sizeof(double));
+				memcpy(matrix,marshalled_dataset,m*n*sizeof(double));marshalled_dataset+=m*n*sizeof(double);
+			}
+			else{
+				matrix=NULL;
+			}
+			this->array[i]=matrix;
+		}
+	}
+	else{
+		this->array=NULL;
+		this->mdim_array=NULL;
+		this->ndim_array=NULL;
+	}
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION DoubleMatArrayParam::ObjectEnum{{{1*/
+int DoubleMatArrayParam::ObjectEnum(void){
+
+	return DoubleMatArrayParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::copy{{{1*/
+Object* DoubleMatArrayParam::copy() {
+	
+	return new DoubleMatArrayParam(this->enum_type,this->array, this->M, this->mdim_array,this->ndim_array);
+
+}
+/*}}}*/
+
+/*DoubleMatArrayParam virtual functions definitions: */
+/*FUNCTION DoubleMatArrayParam::GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims){{{1*/
+void  DoubleMatArrayParam::GetParameterValue(double*** pout_array, int* pout_M,int** pout_mdim_array, int** pout_ndim_array){
+
+	int i,m,n;
+	double* matrix=NULL;
+	double* out_matrix=NULL;
+
+	/*output: */
+	double** 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=(double**)xmalloc(M*sizeof(double*));
+		out_mdim_array=(int*)xmalloc(M*sizeof(int));
+		out_ndim_array=(int*)xmalloc(M*sizeof(int));
+
+		memcpy(out_mdim_array,this->mdim_array,M*sizeof(int));
+		memcpy(out_ndim_array,this->ndim_array,M*sizeof(int));
+
+		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=(double*)xmalloc(m*n*sizeof(double));
+				memcpy(out_matrix,matrix,m*n*sizeof(double));
+			}
+			else{
+				out_matrix=NULL;
+			}
+			out_array[i]=out_matrix;
+		}
+	}
+	else{
+		out_array=NULL;
+		out_matrix=NULL;
+		out_ndim_array=NULL;
+	}
+
+
+	/*Assign output pointers:*/
+	if(pout_M) *pout_M=out_M;
+	if(pout_mdim_array) *pout_mdim_array=out_mdim_array;
+	if(pout_ndim_array) *pout_ndim_array=out_ndim_array;
+	*pout_array=out_array;
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::GetParameterName{{{1*/
+void DoubleMatArrayParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  DoubleMatArrayParam::SetMatlabField(mxArray* dataref){
+	
+	int      i,m,n;
+	double*  matrix=NULL;
+	double*  outmatrix=NULL;
+	char*    name=NULL;
+	mwSize   dims[2]={0};
+	mxArray* pfield=NULL;
+	mxArray* pfield2=NULL;
+	mxArray* pfield3=NULL;
+	
+	this->GetParameterName(&name);
+	dims[0]=this->M;
+	dims[1]=1;
+	pfield=mxCreateCellArray(2,dims);
+
+	for(i=0;i<this->M;i++){
+		matrix=this->array[i];
+		m=this->mdim_array[i];
+		n=this->ndim_array[i];
+		outmatrix=(double*)xmalloc(m*n*sizeof(double));
+		memcpy(outmatrix,matrix,m*n*sizeof(double));
+	
+		pfield2=mxCreateDoubleMatrix(0,0,mxREAL);
+		mxSetM(pfield2,n);
+		mxSetN(pfield2,m);
+		mxSetPr(pfield2,outmatrix);
+
+		//transpose the outmatrix, written directly to matlab! from C to matlab.
+		mexCallMATLAB(1,&pfield3, 1, &pfield2, "transpose");
+	
+		mxSetCell(pfield,i,pfield3);
+	}
+	
+	mxSetField( dataref, 0, name,pfield);
+}
+#endif
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::SetValue(double** array, int M, int* mdim_array, int* ndim_array){{{1*/
+void  DoubleMatArrayParam::SetValue(double** in_array, int in_M, int* in_mdim_array, int* in_ndim_array){
+
+	int i,m,n;
+	double* in_matrix=NULL;
+	double* matrix=NULL;
+
+	/*avoid leak: */
+	xfree((void**)&mdim_array);
+	xfree((void**)&ndim_array);
+	for(i=0;i<M;i++){
+		matrix=array[i];
+		xfree((void**)&matrix);
+	}
+	xfree((void**)&array);
+
+	/*copy data: */
+	this->M=in_M;
+	this->array=(double**)xmalloc(M*sizeof(double*));
+	this->mdim_array=(int*)xmalloc(M*sizeof(int));
+	this->ndim_array=(int*)xmalloc(M*sizeof(int));
+	
+	memcpy(this->mdim_array,in_mdim_array,M*sizeof(double));
+	memcpy(this->ndim_array,in_ndim_array,M*sizeof(double));
+
+	for(i=0;i<M;i++){
+		in_matrix=in_array[i];
+		m=in_mdim_array[i];
+		n=in_ndim_array[i];
+
+		matrix=(double*)xmalloc(m*n*sizeof(double));
+		memcpy(matrix,in_matrix,m*n*sizeof(double));
+
+		this->array[i]=matrix;
+	}
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::UnitConversion{{{1*/
+void  DoubleMatArrayParam::UnitConversion(int direction_enum){
+	/*go through all matrices and convert: */
+	for (int i=0;i<this->M;i++){
+		double* matrix=this->array[i];
+		int     m=this->mdim_array[i];
+		int     n=this->ndim_array[i];
+		::UnitConversion(matrix,m*n,direction_enum,this->enum_type);
+	}
+
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/DoubleMatArrayParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/DoubleMatArrayParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/DoubleMatArrayParam.h	(revision 11330)
@@ -0,0 +1,92 @@
+/*! \file DoubleMatArrayParam.h 
+ *  \brief: header file for object holding an array of serial matrices
+ */
+
+
+#ifndef _DOUBLEMATARRAYPARAM_H_
+#define _DOUBLEMATARRAYPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleMatArrayParam: public Param{
+
+	private: 
+		int      enum_type;
+		double** 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: {{{1*/
+		DoubleMatArrayParam();
+		DoubleMatArrayParam(int enum_type,double** array, int M, int* mdim_array, int* ndim_array);
+		~DoubleMatArrayParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("DoubleMatArray param of enum %i (%s) cannot return a bool",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int* pinteger){_error_("DoubleMatArray param of enum %i (%s) cannot return an integer",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("DoubleMatArray param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("DoubleMatArray param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double* pdouble){_error_("DoubleMatArray param of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char** pstring){_error_("DoubleMatArray param of enum %i (%s) cannot return a string",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("DoubleMatArray param of enum %i (%s) cannot return a string arrayl",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM){_error_("DoubleMatArray param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM, int* pN){_error_("DoubleMatArray param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims);
+		void  GetParameterValue(Vec* pvec){_error_("DoubleMatArray param of enum %i (%s) cannot return a Vec",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Mat* pmat){_error_("DoubleMatArray param of enum %i (%s) cannot return a Mat",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(FILE** pfid){_error_("DoubleMatArray param of enum %i (%s) cannot return a FILE",enum_type,EnumToStringx(enum_type));}
+
+		void  SetValue(bool boolean){_error_("DoubleMatArray param of enum %i (%s) cannot hold a boolean",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int integer){_error_("DoubleMatArray param of enum %i (%s) cannot hold an integer",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double scalar){_error_("DoubleMatArray param of enum %i (%s) cannot hold a scalar",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char* string){_error_("DoubleMatArray param of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char** stringarray,int M){_error_("DoubleMatArray param of enum %i (%s) cannot hold a string array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M){_error_("DoubleMatArray param of enum %i (%s) cannot hold a double vec array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M,int N){_error_("DoubleMatArray param of enum %i (%s) cannot hold a double mat array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* intarray,int M){_error_("DoubleMatArray param of enum %i (%s) cannot hold a int vec array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* intarray,int M,int N){_error_("DoubleMatArray param of enum %i (%s) cannot hold a int mat array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Vec vec){_error_("DoubleMatArray param of enum %i (%s) cannot hold a Vec",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Mat mat){_error_("DoubleMatArray param of enum %i (%s) cannot hold a Mat",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(FILE* fid){_error_("Bool param of enum %i (%s) cannot hold a FILE",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double** array, int M, int* mdim_array, int* ndim_array);
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+
+		/*}}}*/
+};
+#endif  /* _DOUBLEMATARRAYPARAM_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Params/DoubleMatParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/DoubleMatParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/DoubleMatParam.cpp	(revision 11330)
@@ -0,0 +1,239 @@
+/*!\file DoubleMatParam.c
+ * \brief: implementation of the DoubleMatParam object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*DoubleMatParam constructors and destructor*/
+/*FUNCTION DoubleMatParam::DoubleMatParam(){{{1*/
+DoubleMatParam::DoubleMatParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::DoubleMatParam(int enum_type,IssmDoubleMat value){{{1*/
+DoubleMatParam::DoubleMatParam(int in_enum_type,double* in_value, int in_M,int in_N){
+
+	enum_type=in_enum_type;
+	M=in_M;
+	N=in_N;
+
+	value=(double*)xmalloc(M*N*sizeof(double));
+	memcpy(value,in_value,M*N*sizeof(double));
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::~DoubleMatParam(){{{1*/
+DoubleMatParam::~DoubleMatParam(){
+	xfree((void**)&value);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleMatParam::Echo {{{1*/
+void DoubleMatParam::Echo(void){
+
+	printf("DoubleMatParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   matrix size: %ix%i\n",this->M,this->N);
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::DeepEcho{{{1*/
+void DoubleMatParam::DeepEcho(void){
+
+	int i,j;
+	
+	printf("DoubleMatParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   matrix size: %ix%i\n",this->M,this->N);
+	for(i=0;i<this->M;i++){
+		for(i=0;i<this->N;i++){
+			printf("%i %i %g\n",i,j,*(this->value+N*i+j));
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::Id{{{1*/
+int    DoubleMatParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleMatParam::MyRank{{{1*/
+int    DoubleMatParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION DoubleMatParam::Marshall{{{1*/
+void  DoubleMatParam::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of DoubleMatParam: */
+	enum_value=DoubleMatParamEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall DoubleMatParam data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&M,sizeof(M));marshalled_dataset+=sizeof(M);
+	memcpy(marshalled_dataset,&N,sizeof(N));marshalled_dataset+=sizeof(N);
+	memcpy(marshalled_dataset,value,M*N*sizeof(double));marshalled_dataset+=M*N*sizeof(double);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::MarshallSize{{{1*/
+int   DoubleMatParam::MarshallSize(){
+	
+	return sizeof(M)
+		+sizeof(N)
+		+M*N*sizeof(double)
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::Demarshall{{{1*/
+void  DoubleMatParam::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*data: */
+	memcpy(&M,marshalled_dataset,sizeof(M));marshalled_dataset+=sizeof(M);
+	memcpy(&N,marshalled_dataset,sizeof(N));marshalled_dataset+=sizeof(N);
+	value=(double*)xmalloc(M*N*sizeof(double));
+	memcpy(value,marshalled_dataset,M*N*sizeof(double));marshalled_dataset+=M*N*sizeof(double);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION DoubleMatParam::ObjectEnum{{{1*/
+int DoubleMatParam::ObjectEnum(void){
+
+	return DoubleMatParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::copy{{{1*/
+Object* DoubleMatParam::copy() {
+	
+	return new DoubleMatParam(this->enum_type,this->value,this->M,this->N);
+
+}
+/*}}}*/
+
+/*DoubleMatParam virtual functions definitions: */
+/*FUNCTION DoubleMatParam::GetParameterValue(double** pdoublearray,int* pM,int* pN){{{1*/
+void  DoubleMatParam::GetParameterValue(double** pdoublearray,int* pM,int* pN){
+	double* output=NULL;
+
+	output=(double*)xmalloc((int)(M*N*sizeof(double)));
+	memcpy(output,value,M*N*sizeof(double));
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	if(pN) *pN=N;
+	*pdoublearray=output;
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){{{1*/
+void  DoubleMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){
+#ifdef _SERIAL_
+	int* output=NULL;
+	int  i;
+
+	output=(int*)xmalloc((int)(M*N*sizeof(int)));
+	for(i=0;i<M*N;i++) output[i]=(int)value[i];
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	if(pN) *pN=N;
+	*pintarray=output;
+#else
+	_error_("DoubleMat of enum %i (%s) cannot return an array of int",enum_type,EnumToStringx(enum_type));
+#endif
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::GetParameterName{{{1*/
+void DoubleMatParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  DoubleMatParam::SetMatlabField(mxArray* dataref){
+
+	mxArray* pfield=NULL;
+	mxArray* pfield2=NULL;
+	double* doublemat=NULL;
+	char* name=NULL;
+	
+	this->GetParameterName(&name);
+	this->GetParameterValue(&doublemat,NULL,NULL);
+				
+	pfield=mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pfield,N);
+	mxSetN(pfield,M);
+	mxSetPr(pfield,doublemat);
+	
+	//transpose the matrix, written directly to matlab! from C to matlab.
+	mexCallMATLAB(1,&pfield2, 1, &pfield, "transpose");
+	mxSetField( dataref, 0, name,pfield2);
+}
+#endif
+/*}}}*/
+/*FUNCTION DoubleMatParam::SetValue{{{1*/
+void  DoubleMatParam::SetValue(double* doublearray,int in_M,int in_N){
+
+	/*avoid leak: */
+	xfree((void**)&this->value);
+
+	this->value=(double*)xmalloc(in_M*in_N*sizeof(double));
+	memcpy(this->value,doublearray,in_M*in_N*sizeof(double));
+
+	this->M=in_M;
+	this->N=in_N;
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::UnitConversion{{{1*/
+void  DoubleMatParam::UnitConversion(int direction_enum){
+	::UnitConversion(this->value,this->M*this->N,direction_enum,this->enum_type);
+}
+/*}}}*/
+		
+/*diverse: */
+/*FUNCTION DoubleMatParam::GetPointer{{{1*/
+double* DoubleMatParam::GetPointer(void){
+	return this->value;
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/DoubleMatParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/DoubleMatParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/DoubleMatParam.h	(revision 11330)
@@ -0,0 +1,92 @@
+/*! \file DoubleMatParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _DOUBLEMATPARAM_H_
+#define _DOUBLEMATPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleMatParam: public Param{
+
+	protected: 
+		int enum_type;
+		double* value;
+		int M;
+		int N;
+
+	public:
+		/*DoubleMatParam constructors, destructors: {{{1*/
+		DoubleMatParam();
+		DoubleMatParam(int enum_type,IssmDouble* value,int M,int N);
+		~DoubleMatParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("DoubleMat param of enum %i (%s) cannot return a bool",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int* pinteger){_error_("DoubleMat param of enum %i (%s) cannot return an integer",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("DoubleMat param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN);
+		void  GetParameterValue(double* pdouble){_error_("DoubleMat param of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char** pstring){_error_("DoubleMat param of enum %i (%s) cannot return a string",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("DoubleMat param of enum %i (%s) cannot return a string arrayl",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM){_error_("DoubleMat param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM,int* pN);
+		void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims){_error_("DoubleMat param of enum %i (%s) cannot return a matrix array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Vec* pvec){_error_("DoubleMat param of enum %i (%s) cannot return a Vec",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Mat* pmat){_error_("DoubleMat param of enum %i (%s) cannot return a Mat",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(FILE** pfid){_error_("DoubleMat param of enum %i (%s) cannot return a FILE",enum_type,EnumToStringx(enum_type));}
+
+		void  SetValue(bool boolean){_error_("DoubleMat param of enum %i (%s) cannot hold a boolean",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int integer){_error_("DoubleMat param of enum %i (%s) cannot hold an integer",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double scalar){_error_("DoubleMat param of enum %i (%s) cannot hold a scalar",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char* string){_error_("DoubleMat param of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char** stringarray,int M){_error_("DoubleMat param of enum %i (%s) cannot hold a string array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M){_error_("DoubleMat param of enum %i (%s) cannot hold a double vec array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M,int N);
+		void  SetValue(int* intarray,int M){_error_("DoubleMat param of enum %i (%s) cannot hold a int vec array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* intarray,int M,int N){_error_("DoubleMat param of enum %i (%s) cannot hold a int mat array",enum_type,EnumToStringx(enum_type));};
+		void  SetValue(Vec vec){_error_("DoubleMat param of enum %i (%s) cannot hold a Vec",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Mat mat){_error_("DoubleMat param of enum %i (%s) cannot hold a Mat",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(FILE* fid){_error_("DoubleMat param of enum %i (%s) cannot hold a FILE",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double** array, int M, int* mdim_array, int* ndim_array){_error_("DoubleMat param of enum %i (%s) cannot hold an array of matrices",enum_type,EnumToStringx(enum_type));}
+		void  UnitConversion(int direction_enum);
+		double* GetPointer(void);
+
+		void GetParameterName(char**pname);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+
+		/*}}}*/
+};
+#endif  /* _DOUBLEMATPARAM_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Params/DoubleParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/DoubleParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/DoubleParam.cpp	(revision 11330)
@@ -0,0 +1,235 @@
+/*!\file DoubleParam.c
+ * \brief: implementation of the DoubleParam object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+/*DoubleParam constructors and destructor*/
+/*FUNCTION DoubleParam::DoubleParam(){{{1*/
+DoubleParam::DoubleParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleParam::DoubleParam(int enum_type,IssmDouble value){{{1*/
+DoubleParam::DoubleParam(int in_enum_type,IssmDouble in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION DoubleParam::~DoubleParam(){{{1*/
+DoubleParam::~DoubleParam(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleParam::Echo {{{1*/
+void DoubleParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION DoubleParam::DeepEcho{{{1*/
+void DoubleParam::DeepEcho(void){
+
+	printf("DoubleParam:\n");
+	printf("   enum:  %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %g\n",this->value);
+}
+/*}}}*/
+/*FUNCTION DoubleParam::Id{{{1*/
+int    DoubleParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleParam::MyRank{{{1*/
+int    DoubleParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION DoubleParam::Marshall{{{1*/
+void  DoubleParam::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of DoubleParam: */
+	enum_value=DoubleParamEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall DoubleParam data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&value,sizeof(value));marshalled_dataset+=sizeof(value);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION DoubleParam::MarshallSize{{{1*/
+int   DoubleParam::MarshallSize(){
+	
+	return sizeof(value)+
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION DoubleParam::Demarshall{{{1*/
+void  DoubleParam::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&value,marshalled_dataset,sizeof(value));marshalled_dataset+=sizeof(value);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION DoubleParam::ObjectEnum{{{1*/
+int DoubleParam::ObjectEnum(void){
+
+	return DoubleParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleParam::copy{{{1*/
+Object* DoubleParam::copy() {
+	
+	return new DoubleParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*DoubleParam virtual functions definitions: */
+/*FUNCTION DoubleParam::GetParameterName{{{1*/
+void DoubleParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(int* pinteger){{{1*/
+void DoubleParam::GetParameterValue(int* pinteger){
+#ifdef _SERIAL_
+	*pinteger=(int)value;
+#else
+	_error_("Double param of enum %i (%s) cannot return an integer",enum_type,EnumToStringx(enum_type));
+#endif
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(bool* pbool){{{1*/
+void DoubleParam::GetParameterValue(bool* pbool){
+#ifdef _SERIAL_
+
+	/*If debugging mode, cheeck that the double is 0 or 1*/
+	_assert_(value==0 || value==1);
+	*pbool=(bool)value;
+
+#else
+	_error_("Double param of enum %i (%s) cannot return an bool",enum_type,EnumToStringx(enum_type));
+#endif
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(int** pintarray,int* pM){{{1*/
+void DoubleParam::GetParameterValue(int** pintarray,int* pM){
+#ifdef _SERIAL_
+	int* output=NULL;
+
+	output=(int*)xmalloc(1*sizeof(int));
+	*output=(int)value;
+
+	/*Assign output pointers:*/
+	if(pM) *pM=1;
+	*pintarray=output;
+#else
+	_error_("Double param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));
+#endif
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(int** pintarray,int* pM,int* pN){{{1*/
+void DoubleParam::GetParameterValue(int** pintarray,int* pM,int* pN){
+#ifdef _SERIAL_
+	int* output=NULL;
+
+	output=(int*)xmalloc(1*sizeof(int));
+	*output=(int)value;
+
+	/*Assign output pointers:*/
+	if(pM) *pM=1;
+	if(pN) *pN=1;
+	*pintarray=output;
+#else
+	_error_("Double param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));
+#endif
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(double** pdoublearray,int* pM){{{1*/
+void DoubleParam::GetParameterValue(double** pdoublearray,int* pM){
+#ifdef _SERIAL_
+	double* output=NULL;
+
+	output=(double*)xmalloc(1*sizeof(double));
+	*output=(double)value;
+
+	/*Assign output podoubleers:*/
+	if(pM) *pM=1;
+	*pdoublearray=output;
+#else
+	_error_("Double param of enum %i (%s) cannot return an array of double",enum_type,EnumToStringx(enum_type));
+#endif
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(double** pdoublearray,int* pM,int* pN){{{1*/
+void DoubleParam::GetParameterValue(double** pdoublearray,int* pM,int* pN){
+#ifdef _SERIAL_
+	double* output=NULL;
+
+	output=(double*)xmalloc(1*sizeof(double));
+	*output=(double)value;
+
+	/*Assign output podoubleers:*/
+	if(pM) *pM=1;
+	if(pN) *pN=1;
+	*pdoublearray=output;
+#else
+	_error_("Double param of enum %i (%s) cannot return an array of double",enum_type,EnumToStringx(enum_type));
+#endif
+}
+/*}}}*/
+/*FUNCTION DoubleParam::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  DoubleParam::SetMatlabField(mxArray* dataref){
+
+	char* name=NULL;
+	this->GetParameterName(&name);
+	mxSetField( dataref, 0, name,mxCreateDoubleScalar(value));
+}
+#endif
+/*}}}*/
+/*FUNCTION DoubleParam::UnitConversion{{{1*/
+void  DoubleParam::UnitConversion(int direction_enum){
+	::UnitConversion(&this->value,1,direction_enum,this->enum_type);
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/DoubleParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/DoubleParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/DoubleParam.h	(revision 11330)
@@ -0,0 +1,90 @@
+/*! \file DoubleParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _DOUBLEPARAM_H_
+#define _DOUBLEPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		IssmDouble value;
+
+	public:
+		/*DoubleParam constructors, destructors: {{{1*/
+		DoubleParam();
+		DoubleParam(int enum_type,IssmDouble value);
+		~DoubleParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{1*/
+		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(double* pdouble){*pdouble=value;}
+		void  GetParameterValue(char** pstring){_error_("Double param of enum %i (%s) cannot return a string",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Double param of enum %i (%s) cannot return a string arrayl",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM);
+		void  GetParameterValue(double** pdoublearray,int* pM, int* pN);
+		void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims){_error_("Double param of enum %i (%s) cannot return a matrix array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Vec* pvec){_error_("Double param of enum %i (%s) cannot return a Vec",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Mat* pmat){_error_("Double param of enum %i (%s) cannot return a Mat",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(FILE** pfid){_error_("Double param of enum %i (%s) cannot return a FILE",enum_type,EnumToStringx(enum_type));}
+
+		void  SetValue(bool boolean){this->value=(double)boolean;}
+		void  SetValue(int integer){this->value=(double)integer;}
+		void  SetValue(double scalar){this->value=(double)scalar;}
+		void  SetValue(char* string){_error_("Double param of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char** stringarray,int M){_error_("Double param of enum %i (%s) cannot hold a string array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M){_error_("Double param of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* pdoublearray,int M,int N){_error_("Double param of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* intarray,int M){_error_("Double param of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* pintarray,int M,int N){_error_("Double param of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Vec vec){_error_("Double param of enum %i (%s) cannot hold a Vec",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Mat mat){_error_("Double param of enum %i (%s) cannot hold a Mat",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(FILE* fid){_error_("Double param of enum %i (%s) cannot hold a FILE",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double** array, int M, int* mdim_array, int* ndim_array){_error_("Double param of enum %i (%s) cannot hold an array of matrices",enum_type,EnumToStringx(enum_type));}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+
+		/*}}}*/
+};
+#endif  /* _DOUBLEPARAM_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Params/DoubleTransientMatParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/DoubleTransientMatParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/DoubleTransientMatParam.cpp	(revision 11330)
@@ -0,0 +1,31 @@
+/*!\file DoubleTransientMatParam.c
+ * \brief: implementation of the DoubleTransientMatParam object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*FUNCTION DoubleTransientMatParam::DoubleTransientMatParam(int enum_type,IssmDoubleMat value){{{1*/
+DoubleTransientMatParam::DoubleTransientMatParam(int in_enum_type,double* in_value, int in_M,int in_N):DoubleMatParam(in_enum_type,in_value,in_M,in_N){
+}
+/*}}}*/
+
+/*FUNCTION DoubleTransientMatParam::UnitConversion{{{1*/
+void  DoubleTransientMatParam::UnitConversion(int direction_enum){
+	::UnitConversion(this->value,(this->M-1)*this->N,direction_enum,this->enum_type);
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/DoubleTransientMatParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/DoubleTransientMatParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/DoubleTransientMatParam.h	(revision 11330)
@@ -0,0 +1,36 @@
+/*! \file DoubleTransientMatParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _DOUBLETRANSIENTMATPARAM_H_
+#define _DOUBLETRANSIENTMATPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleTransientMatParam: public DoubleMatParam{
+
+	public:
+		/*DoubleTransientMatParam constructors, destructors: {{{1*/
+		DoubleTransientMatParam(int enum_type,IssmDouble* value,int M,int N);
+		/*}}}*/
+		/*Param vritual function definitions: {{{1*/
+		void  UnitConversion(int direction_enum);
+		/*}}}*/
+};
+#endif  /* _DOUBLETRANSIENTMATPARAM_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Params/DoubleVecParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/DoubleVecParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/DoubleVecParam.cpp	(revision 11330)
@@ -0,0 +1,240 @@
+/*!\file DoubleVecParam.c
+ * \brief: implementation of the DoubleVecParam object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*DoubleVecParam constructors and destructor*/
+/*FUNCTION DoubleVecParam::DoubleVecParam(){{{1*/
+DoubleVecParam::DoubleVecParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::DoubleVecParam(int enum_type,IssmDoubleVec values,int M){{{1*/
+DoubleVecParam::DoubleVecParam(int in_enum_type,double* in_values, int in_M){
+
+	enum_type=in_enum_type;
+	M=in_M;
+
+	values=(double*)xmalloc(M*sizeof(double));
+	memcpy(values,in_values,M*sizeof(double));
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::~DoubleVecParam(){{{1*/
+DoubleVecParam::~DoubleVecParam(){
+	xfree((void**)&values);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleVecParam::Echo {{{1*/
+void DoubleVecParam::Echo(void){
+
+	printf("DoubleVecParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   vector size: %i\n",this->M);
+
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::DeepEcho{{{1*/
+void DoubleVecParam::DeepEcho(void){
+
+	int i;
+	
+	printf("DoubleVecParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   vector size: %i\n",this->M);
+	for(i=0;i<this->M;i++){
+		printf("%i %g\n",i,this->values[i]);
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::Id{{{1*/
+int    DoubleVecParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleVecParam::MyRank{{{1*/
+int    DoubleVecParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION DoubleVecParam::Marshall{{{1*/
+void  DoubleVecParam::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of DoubleVecParam: */
+	enum_value=DoubleVecParamEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall DoubleVecParam data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&M,sizeof(M));marshalled_dataset+=sizeof(M);
+	memcpy(marshalled_dataset,values,M*sizeof(double));marshalled_dataset+=M*sizeof(double);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::MarshallSize{{{1*/
+int   DoubleVecParam::MarshallSize(){
+	
+	return sizeof(M)
+		+M*sizeof(double)
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::Demarshall{{{1*/
+void  DoubleVecParam::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*data: */
+	memcpy(&M,marshalled_dataset,sizeof(M));marshalled_dataset+=sizeof(M);
+	values=(double*)xmalloc(M*sizeof(double));
+	memcpy(values,marshalled_dataset,M*sizeof(double));marshalled_dataset+=M*sizeof(double);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION DoubleVecParam::ObjectEnum{{{1*/
+int DoubleVecParam::ObjectEnum(void){
+
+	return DoubleVecParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::copy{{{1*/
+Object* DoubleVecParam::copy() {
+	
+	return new DoubleVecParam(this->enum_type,this->values,this->M);
+
+}
+/*}}}*/
+
+/*DoubleVecParam virtual functions definitions: */
+/*FUNCTION DoubleVecParam::GetParameterValue(double** pdoublearray,int* pM){{{1*/
+void  DoubleVecParam::GetParameterValue(double** pdoublearray,int* pM){
+	double* output=NULL;
+	int M;
+
+	M=this->M;
+	output=(double*)xmalloc(M*sizeof(double));
+	memcpy(output,values,M*sizeof(double));
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	*pdoublearray=output;
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::GetParameterValue(double** pdoublearray,int* pM){{{1*/
+void  DoubleVecParam::GetParameterValue(double** pdoublearray,int* pM,int* pN){
+	double* output=NULL;
+	int M;
+	int N;
+
+	N=1;
+	M=this->M;
+	output=(double*)xmalloc(M*sizeof(double));
+	memcpy(output,values,M*sizeof(double));
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	if(pN) *pN=N;
+	*pdoublearray=output;
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::GetParameterValue(int** pintarray,int* pM){{{1*/
+void  DoubleVecParam::GetParameterValue(int** pintarray,int* pM){
+#ifdef _SERIAL_
+	int* output=NULL;
+	int i;
+
+	/*Cast values into integers*/
+	output=(int*)xmalloc(M*sizeof(int));
+	for(i=0;i<M;i++) output[i]=(int)values[i];
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	*pintarray=output;
+#else
+	_error_("DoubleVec param of enum %i (%s) cannot return an array of int",enum_type,EnumToStringx(enum_type));
+#endif
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::GetParameterName{{{1*/
+void DoubleVecParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  DoubleVecParam::SetMatlabField(mxArray* dataref){
+
+	char* name=NULL;
+	double* doublevec=NULL;
+	mxArray* pfield=NULL;
+
+	this->GetParameterValue(&doublevec,NULL);
+	this->GetParameterName(&name);
+				
+	pfield=mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pfield,M);
+	mxSetN(pfield,1);
+	mxSetPr(pfield,doublevec);
+	
+	mxSetField( dataref, 0, name, pfield);
+}
+#endif
+/*}}}*/
+/*FUNCTION DoubleVecParam::SetValue{{{1*/
+void  DoubleVecParam::SetValue(double* doublearray,int in_M){
+
+	/*avoid leak: */
+	xfree((void**)&this->values);
+
+	this->values=(double*)xmalloc(in_M*sizeof(double));
+	memcpy(this->values,doublearray,in_M*sizeof(double));
+
+	this->M=in_M;
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::UnitConversion{{{1*/
+void  DoubleVecParam::UnitConversion(int direction_enum){
+	::UnitConversion(this->values,this->M,direction_enum,this->enum_type);
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/DoubleVecParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/DoubleVecParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/DoubleVecParam.h	(revision 11330)
@@ -0,0 +1,89 @@
+/*! \file DoubleVecParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _DOUBLEVECPARAM_H_
+#define _DOUBLEVECPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DoubleVecParam: public Param{
+
+	private: 
+		int enum_type;
+		IssmDouble* values;
+		int M;
+
+	public:
+		/*DoubleVecParam constructors, destructors: {{{1*/
+		DoubleVecParam();
+		DoubleVecParam(int enum_type,IssmDouble* values,int M);
+		~DoubleVecParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param virtual functions definitions: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("DoubleVec param of enum %i (%s) cannot return a bool",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int* pinteger){_error_("DoubleVec param of enum %i (%s) cannot return an integer",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM);
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("DoubleVec param of enum %i (%s) cannot return a string",enum_type,EnumToStringx(enum_type));};
+		void  GetParameterValue(double* pdouble){_error_("DoubleVec param of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char** pstring){_error_("DoubleVec param of enum %i (%s) cannot return a string",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("DoubleVec param of enum %i (%s) cannot return a string arrayl",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM);
+		void  GetParameterValue(double** pdoublearray,int* pM, int* pN);
+		void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims){_error_("DoubleVec param of enum %i (%s) cannot return a matrix array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Vec* pvec){_error_("DoubleVec param of enum %i (%s) cannot return a Vec",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Mat* pmat){_error_("DoubleVec param of enum %i (%s) cannot return a Mat",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(FILE** pfid){_error_("DoubleVec param of enum %i (%s) cannot return a FILE",enum_type,EnumToStringx(enum_type));}
+
+		void  SetValue(bool boolean){_error_("DoubleVec param of enum %i (%s) cannot hold a boolean",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int integer){_error_("DoubleVec param of enum %i (%s) cannot hold an integer",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double scalar){_error_("DoubleVec param of enum %i (%s) cannot hold a scalar",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char* string){_error_("DoubleVec param of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char** stringarray,int M){_error_("DoubleVec param of enum %i (%s) cannot hold a string array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M);
+		void  SetValue(double* pdoublearray,int M,int N){_error_("DoubleVec param of enum %i (%s) cannot hold a double mat array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* intarray,int M){_error_("DoubleVec param of enum %i (%s) cannot hold a int mat array",enum_type,EnumToStringx(enum_type));};
+		void  SetValue(int* pintarray,int M,int N){_error_("DoubleVec param of enum %i (%s) cannot hold a int mat array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Vec vec){_error_("DoubleVec param of enum %i (%s) cannot hold a Vec",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Mat mat){_error_("DoubleVec param of enum %i (%s) cannot hold a Mat",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(FILE* fid){_error_("DoubleVec param of enum %i (%s) cannot hold a FILE",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double** array, int M, int* mdim_array, int* ndim_array){_error_("DoubleVec param of enum %i (%s) cannot hold an array of matrices",enum_type,EnumToStringx(enum_type));}
+		void  UnitConversion(int direction_enum);
+		
+		void GetParameterName(char**pname);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+		/*}}}*/
+};
+#endif  /* _DOUBLEVECPARAM_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Params/FileParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/FileParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/FileParam.cpp	(revision 11330)
@@ -0,0 +1,115 @@
+/*!\file FileParam.c
+ * \brief: implementation of the FileParam object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*FileParam constructors and destructor*/
+/*FUNCTION FileParam::FileParam(){{{1*/
+FileParam::FileParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION FileParam::FileParam(int enum_type,FILE *value){{{1*/
+FileParam::FileParam(int in_enum_type,FILE* in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION FileParam::~FileParam(){{{1*/
+FileParam::~FileParam(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION FileParam::Echo {{{1*/
+void FileParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION FileParam::DeepEcho{{{1*/
+void FileParam::DeepEcho(void){
+
+	printf("FileParam:\n");
+	printf("   enum:  %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %p\n",this->value);
+}
+/*}}}*/
+/*FUNCTION FileParam::Id{{{1*/
+int    FileParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION FileParam::MyRank{{{1*/
+int    FileParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION FileParam::Marshall{{{1*/
+void  FileParam::Marshall(char** pmarshalled_dataset){
+
+	_error_("FileParam is a pointer and cannot be marshalled");
+}
+/*}}}*/
+/*FUNCTION FileParam::MarshallSize{{{1*/
+int   FileParam::MarshallSize(){
+	_error_("FileParam is a pointer and cannot be marshalled");
+}
+/*}}}*/
+/*FUNCTION FileParam::Demarshall{{{1*/
+void  FileParam::Demarshall(char** pmarshalled_dataset){
+	_error_("FileParam is a pointer and cannot be marshalled");
+}
+/*}}}*/
+#endif
+/*FUNCTION FileParam::ObjectEnum{{{1*/
+int FileParam::ObjectEnum(void){
+
+	return FileParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION FileParam::copy{{{1*/
+Object* FileParam::copy() {
+	
+	return new FileParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*FileParam virtual functions definitions: */
+/*FUNCTION FileParam::GetParameterName{{{1*/
+void FileParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION FileParam::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  FileParam::SetMatlabField(mxArray* dataref){
+	
+	_error_("FileParam is a pointer and cannot be converted into a matlab object");
+}
+#endif
+/*}}}*/
+/*FUNCTION FileParam::UnitConversion{{{1*/
+void  FileParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/FileParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/FileParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/FileParam.h	(revision 11330)
@@ -0,0 +1,89 @@
+/*! \file FileParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _FILEPARAM_H_
+#define _FILEPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class FileParam: public Param{
+
+	private: 
+		int   enum_type;
+		FILE* value;
+
+	public:
+		/*FileParam constructors, destructors: {{{1*/
+		FileParam();
+		FileParam(int enum_type,FILE* fid);
+		~FileParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){  _error_("FileParam of enum %i (%s) cannot return a bool",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int* pinteger){_error_("FileParam of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("FileParam of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("FileParam of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double* pdouble){_error_("FileParam of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char** pstring){_error_("FileParam of enum %i (%s) cannot return a string",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("FileParam of enum %i (%s) cannot return a string arrayl",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM){_error_("FileParam of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM, int* pN){_error_("FileParam of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims){_error_("File param of enum %i (%s) cannot return a matrix array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Vec* pvec){_error_("FileParam of enum %i (%s) cannot return a Vec",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Mat* pmat){_error_("FileParam of enum %i (%s) cannot return a Mat",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(FILE** pfid){*pfid=value;};
+
+		void  SetValue(bool boolean){_error_("FileParam of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int integer){_error_("FileParam of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double scalar){_error_("FileParam of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char* string){_error_("FileParam of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char** stringarray,int M){_error_("FileParam of enum %i (%s) cannot hold a string array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M){_error_("FileParam of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* pdoublearray,int M,int N){_error_("FileParam of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* intarray,int M){_error_("FileParam of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* pintarray,int M,int N){_error_("FileParam of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Vec vec){_error_("FileParam of enum %i (%s) cannot hold a Vec",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Mat mat){_error_("FileParam of enum %i (%s) cannot hold a Mat",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(FILE* fid){_error_("File param of enum %i (%s) cannot hold a FILE",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double** array, int M, int* mdim_array, int* ndim_array){_error_("File param of enum %i (%s) cannot hold an array of matrices",enum_type,EnumToStringx(enum_type));}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+
+		/*}}}*/
+};
+#endif  /* _INTPARAM_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Params/IntMatParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/IntMatParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/IntMatParam.cpp	(revision 11330)
@@ -0,0 +1,220 @@
+/*!\file IntMatParam.c
+ * \brief: implementation of the IntMatParam object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*IntMatParam constructors and destructor*/
+/*FUNCTION IntMatParam::IntMatParam(){{{1*/
+IntMatParam::IntMatParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION IntMatParam::IntMatParam(int enum_type,IssmIntMat value){{{1*/
+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=(int*)xmalloc(M*N*sizeof(int));
+	memcpy(value,in_value,M*N*sizeof(int));
+}
+/*}}}*/
+/*FUNCTION IntMatParam::~IntMatParam(){{{1*/
+IntMatParam::~IntMatParam(){
+	xfree((void**)&value);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION IntMatParam::Echo {{{1*/
+void IntMatParam::Echo(void){
+
+	printf("IntMatParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   matrix size: %ix%i\n",this->M,this->N);
+
+}
+/*}}}*/
+/*FUNCTION IntMatParam::DeepEcho{{{1*/
+void IntMatParam::DeepEcho(void){
+
+	int i,j;
+	
+	printf("IntMatParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   matrix size: %ix%i\n",this->M,this->N);
+	for(i=0;i<this->M;i++){
+		for(i=0;i<this->N;i++){
+			printf("(%i,%i) %i\n",i,j,*(this->value+N*i+j));
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION IntMatParam::Id{{{1*/
+int    IntMatParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntMatParam::MyRank{{{1*/
+int    IntMatParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION IntMatParam::Marshall{{{1*/
+void  IntMatParam::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of IntMatParam: */
+	enum_value=IntMatParamEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall IntMatParam data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&M,sizeof(M));marshalled_dataset+=sizeof(M);
+	memcpy(marshalled_dataset,&N,sizeof(N));marshalled_dataset+=sizeof(N);
+	memcpy(marshalled_dataset,value,M*N*sizeof(int));marshalled_dataset+=M*N*sizeof(int);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION IntMatParam::MarshallSize{{{1*/
+int   IntMatParam::MarshallSize(){
+	
+	return sizeof(M)
+		+sizeof(N)
+		+M*N*sizeof(int)
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION IntMatParam::Demarshall{{{1*/
+void  IntMatParam::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*data: */
+	memcpy(&M,marshalled_dataset,sizeof(M));marshalled_dataset+=sizeof(M);
+	memcpy(&N,marshalled_dataset,sizeof(N));marshalled_dataset+=sizeof(N);
+	value=(int*)xmalloc(M*N*sizeof(int));
+	memcpy(value,marshalled_dataset,M*N*sizeof(int));marshalled_dataset+=M*N*sizeof(int);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION IntMatParam::ObjectEnum{{{1*/
+int IntMatParam::ObjectEnum(void){
+
+	return IntMatParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION IntMatParam::copy{{{1*/
+Object* IntMatParam::copy() {
+	
+	return new IntMatParam(this->enum_type,this->value,this->M,this->N);
+
+}
+/*}}}*/
+
+/*IntMatParam virtual functions definitions: */
+/*FUNCTION IntMatParam::GetParameterValue{{{1*/
+void  IntMatParam::GetParameterValue(int** pintarray,int* pM,int* pN){
+	int* output=NULL;
+
+	output=(int*)xmalloc((int)(M*N*sizeof(int)));
+	memcpy(output,value,M*N*sizeof(int));
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	if(pN) *pN=N;
+	*pintarray=output;
+}
+/*}}}*/
+/*FUNCTION IntMatParam::GetParameterName{{{1*/
+void IntMatParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION IntMatParam::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  IntMatParam::SetMatlabField(mxArray* dataref){
+
+	char    *name        = NULL;
+	double  *doublearray = NULL;
+	int     *intarray    = NULL;
+	mxArray *pfield      = NULL;
+	mxArray *pfield2     = NULL;
+
+	this->GetParameterValue(&intarray,NULL,NULL);
+	this->GetParameterName(&name);
+
+	/*cast intarray into doublearray for Matlab*/
+	doublearray=(double*)xmalloc(M*N*sizeof(double));
+	for(int i=0;i<M*N;i++)doublearray[i]=(double)intarray[i];
+	xfree((void**)&intarray);
+
+	pfield=mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pfield,M);
+	mxSetN(pfield,N);
+	mxSetPr(pfield,doublearray);
+
+	//transpose the matrix, written directly to matlab! from C to matlab.
+	mexCallMATLAB(1,&pfield2, 1, &pfield, "transpose");
+	mxSetField( dataref, 0, name,pfield2);
+}
+#endif
+/*}}}*/
+/*FUNCTION IntMatParam::SetValue{{{1*/
+void  IntMatParam::SetValue(int* intarray,int in_M,int in_N){
+
+	/*avoid leak: */
+	xfree((void**)&this->value);
+
+	this->value=(int*)xmalloc(in_M*in_N*sizeof(int));
+	memcpy(this->value,intarray,in_M*in_N*sizeof(int));
+
+	this->M=in_M;
+	this->N=in_N;
+}
+/*}}}*/
+/*FUNCTION IntMatParam::UnitConversion{{{1*/
+void  IntMatParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/IntMatParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/IntMatParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/IntMatParam.h	(revision 11330)
@@ -0,0 +1,91 @@
+/*! \file IntMatParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _INTMATPARAM_H_
+#define _INTMATPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class IntMatParam: public Param{
+
+	private: 
+		int enum_type;
+		int* value;
+		int M;
+		int N;
+
+	public:
+		/*IntMatParam constructors, destructors: {{{1*/
+		IntMatParam();
+		IntMatParam(int enum_type,int* value,int M,int N);
+		~IntMatParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("IntMat param of enum %i (%s) cannot return a bool",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int* pinteger){_error_("IntMat param of enum %i (%s) cannot return an integer",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("IntMat param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN);
+		void  GetParameterValue(double* pdouble){_error_("IntMat param of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char** pstring){_error_("IntMat param of enum %i (%s) cannot return a string",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("IntMat param of enum %i (%s) cannot return a string arrayl",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM){_error_("IntMat param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM,int* pN){_error_("IntMat param of enum %i (%s) cannot return a matrix array",enum_type,EnumToStringx(enum_type));};
+		void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims){_error_("IntMat param of enum %i (%s) cannot return a matrix array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Vec* pvec){_error_("IntMat param of enum %i (%s) cannot return a Vec",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Mat* pmat){_error_("IntMat param of enum %i (%s) cannot return a Mat",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(FILE** pfid){_error_("IntMat param of enum %i (%s) cannot return a FILE",enum_type,EnumToStringx(enum_type));}
+
+		void  SetValue(bool boolean){_error_("IntMat param of enum %i (%s) cannot hold a boolean",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int integer){_error_("IntMat param of enum %i (%s) cannot hold an integer",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double scalar){_error_("IntMat param of enum %i (%s) cannot hold a scalar",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char* string){_error_("IntMat param of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char** stringarray,int M){_error_("IntMat param of enum %i (%s) cannot hold a string array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M){_error_("IntMat param of enum %i (%s) cannot hold a double vec array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M,int N){_error_("IntMat param of enum %i (%s) cannot hold a double vec array",enum_type,EnumToStringx(enum_type));};
+		void  SetValue(int* intarray,int M){_error_("IntMat param of enum %i (%s) cannot hold a int vec array",enum_type,EnumToStringx(enum_type));};
+		void  SetValue(int* intarray,int M,int N);
+		void  SetValue(Vec vec){_error_("IntMat param of enum %i (%s) cannot hold a Vec",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Mat mat){_error_("IntMat param of enum %i (%s) cannot hold a Mat",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(FILE* fid){_error_("IntMat param of enum %i (%s) cannot hold a FILE",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double** array, int M, int* mdim_array, int* ndim_array){_error_("IntMat param of enum %i (%s) cannot hold an array of matrices",enum_type,EnumToStringx(enum_type));}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+
+		/*}}}*/
+};
+#endif  /* _INTMATPARAM_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Params/IntParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/IntParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/IntParam.cpp	(revision 11330)
@@ -0,0 +1,150 @@
+/*!\file IntParam.c
+ * \brief: implementation of the IntParam object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*IntParam constructors and destructor*/
+/*FUNCTION IntParam::IntParam(){{{1*/
+IntParam::IntParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION IntParam::IntParam(int enum_type,IssmInt value){{{1*/
+IntParam::IntParam(int in_enum_type,IssmInt in_value){
+
+	enum_type=in_enum_type;
+	value=in_value;
+}
+/*}}}*/
+/*FUNCTION IntParam::~IntParam(){{{1*/
+IntParam::~IntParam(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION IntParam::Echo {{{1*/
+void IntParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION IntParam::DeepEcho{{{1*/
+void IntParam::DeepEcho(void){
+
+	printf("IntParam:\n");
+	printf("   enum:  %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %i\n",this->value);
+}
+/*}}}*/
+/*FUNCTION IntParam::Id{{{1*/
+int    IntParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntParam::MyRank{{{1*/
+int    IntParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION IntParam::Marshall{{{1*/
+void  IntParam::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of IntParam: */
+	enum_value=IntParamEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall IntParam data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&value,sizeof(value));marshalled_dataset+=sizeof(value);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION IntParam::MarshallSize{{{1*/
+int   IntParam::MarshallSize(){
+	
+	return sizeof(value)+
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION IntParam::Demarshall{{{1*/
+void  IntParam::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(&value,marshalled_dataset,sizeof(value));marshalled_dataset+=sizeof(value);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION IntParam::ObjectEnum{{{1*/
+int IntParam::ObjectEnum(void){
+
+	return IntParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION IntParam::copy{{{1*/
+Object* IntParam::copy() {
+	
+	return new IntParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*IntParam virtual functions definitions: */
+/*FUNCTION IntParam::GetParameterName{{{1*/
+void IntParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION IntParam::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  IntParam::SetMatlabField(mxArray* dataref){
+	
+	char* name=NULL;
+	this->GetParameterName(&name);
+	mxSetField( dataref, 0, name,mxCreateDoubleScalar((double)value));
+}
+#endif
+/*}}}*/
+/*FUNCTION IntParam::UnitConversion{{{1*/
+void  IntParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/IntParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/IntParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/IntParam.h	(revision 11330)
@@ -0,0 +1,90 @@
+/*! \file IntParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _INTPARAM_H_
+#define _INTPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class IntParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		IssmInt value;
+
+	public:
+		/*IntParam constructors, destructors: {{{1*/
+		IntParam();
+		IntParam(int enum_type,IssmInt value);
+		~IntParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Int param of enum %i (%s) cannot return a bool",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int* pinteger){*pinteger=value;}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Int param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Int param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double* pdouble){_error_("Int param of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char** pstring){_error_("Int param of enum %i (%s) cannot return a string",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Int param of enum %i (%s) cannot return a string arrayl",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM){_error_("Int param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM, int* pN){_error_("Int param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims){_error_("Int param of enum %i (%s) cannot return a matrix array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Vec* pvec){_error_("Int param of enum %i (%s) cannot return a Vec",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Mat* pmat){_error_("Int param of enum %i (%s) cannot return a Mat",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(FILE** pfid){_error_("Int param of enum %i (%s) cannot return a FILE",enum_type,EnumToStringx(enum_type));}
+
+		void  SetValue(bool boolean){this->value=(int)boolean;}
+		void  SetValue(int integer){this->value=integer;}
+		void  SetValue(int* intarray,int M){_error_("Int param of enum %i (%s) cannot hold an int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* intarray,int M,int N){_error_("Int param of enum %i (%s) cannot hold an int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double scalar){this->value=(int)scalar;}
+		void  SetValue(char* string){_error_("Int param of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char** stringarray,int M){_error_("Int param of enum %i (%s) cannot hold a string array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M){_error_("Int param of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* pdoublearray,int M,int N){_error_("Int param of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Vec vec){_error_("Int param of enum %i (%s) cannot hold a Vec",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Mat mat){_error_("Int param of enum %i (%s) cannot hold a Mat",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(FILE* fid){_error_("Int param of enum %i (%s) cannot hold a FILE",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double** array, int M, int* mdim_array, int* ndim_array){_error_("Int param of enum %i (%s) cannot hold an array of matrices",enum_type,EnumToStringx(enum_type));}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+
+		/*}}}*/
+};
+#endif  /* _INTPARAM_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Params/IntVecParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/IntVecParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/IntVecParam.cpp	(revision 11330)
@@ -0,0 +1,235 @@
+/*!\file IntVecParam.c
+ * \brief: implementation of the IntVecParam object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*IntVecParam constructors and destructor*/
+/*FUNCTION IntVecParam::IntVecParam(){{{1*/
+IntVecParam::IntVecParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION IntVecParam::IntVecParam(int enum_type,int* values,int M){{{1*/
+IntVecParam::IntVecParam(int in_enum_type,int* in_values, int in_M){
+
+	enum_type=in_enum_type;
+	M=in_M;
+
+	if(M){
+		values=(int*)xmalloc(M*sizeof(int));
+		memcpy(values,in_values,M*sizeof(int));
+	}
+	else values=NULL;
+}
+/*}}}*/
+/*FUNCTION IntVecParam::IntVecParam(int enum_type,double* values,int M){{{1*/
+IntVecParam::IntVecParam(int in_enum_type,double* in_values, int in_M){
+
+	enum_type=in_enum_type;
+	M=in_M;
+
+	if(M){
+		values=(int*)xmalloc(M*sizeof(int));
+		for(int i=0;i<in_M;i++) values[i]=(int)in_values[i];
+	}
+	else values=NULL;
+}
+/*}}}*/
+/*FUNCTION IntVecParam::~IntVecParam(){{{1*/
+IntVecParam::~IntVecParam(){
+	xfree((void**)&values);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION IntVecParam::Echo {{{1*/
+void IntVecParam::Echo(void){
+
+	printf("IntVecParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   vector size: %i\n",this->M);
+
+}
+/*}}}*/
+/*FUNCTION IntVecParam::DeepEcho{{{1*/
+void IntVecParam::DeepEcho(void){
+
+	int i;
+	
+	printf("IntVecParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   vector size: %i\n",this->M);
+	for(i=0;i<this->M;i++){
+		printf("%i %i\n",i,this->values[i]);
+	}
+}
+/*}}}*/
+/*FUNCTION IntVecParam::Id{{{1*/
+int    IntVecParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntVecParam::MyRank{{{1*/
+int    IntVecParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION IntVecParam::Marshall{{{1*/
+void  IntVecParam::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of IntVecParam: */
+	enum_value=IntVecParamEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall IntVecParam data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&M,sizeof(M));marshalled_dataset+=sizeof(M);
+	if(M)memcpy(marshalled_dataset,values,M*sizeof(int));marshalled_dataset+=M*sizeof(int);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION IntVecParam::MarshallSize{{{1*/
+int   IntVecParam::MarshallSize(){
+	
+	return sizeof(M)+
+		+M*sizeof(int)
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION IntVecParam::Demarshall{{{1*/
+void  IntVecParam::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*data: */
+	memcpy(&M,marshalled_dataset,sizeof(M));marshalled_dataset+=sizeof(M);
+	if(M) {
+		values=(int*)xmalloc(M*sizeof(int));
+		memcpy(values,marshalled_dataset,M*sizeof(int));marshalled_dataset+=M*sizeof(int);
+	}
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION IntVecParam::ObjectEnum{{{1*/
+int IntVecParam::ObjectEnum(void){
+
+	return IntVecParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION IntVecParam::copy{{{1*/
+Object* IntVecParam::copy() {
+	
+	return new IntVecParam(this->enum_type,this->values,this->M);
+
+}
+/*}}}*/
+
+/*IntVecParam virtual functions definitions: */
+/*FUNCTION IntVecParam::GetParameterValue{{{1*/
+void  IntVecParam::GetParameterValue(int** pintarray,int* pM){
+	int* output=NULL;
+
+	if(M){
+		output=(int*)xmalloc(M*sizeof(int));
+		memcpy(output,values,M*sizeof(int));
+	}
+
+	/*Assign output pointers:*/
+	if(pM) *pM=M;
+	*pintarray=output;
+}
+/*}}}*/
+/*FUNCTION IntVecParam::GetParameterName{{{1*/
+void IntVecParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION IntVecParam::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  IntVecParam::SetMatlabField(mxArray* dataref){
+
+	char    *name      = NULL;
+	double  *doublevec = NULL;
+	int     *intvec    = NULL;
+	mxArray *pfield    = NULL;
+
+	this->GetParameterValue(&intvec,NULL);
+	this->GetParameterName(&name);
+
+	/*cast intvec into doublevec for Matlab*/
+	if(M){
+		doublevec=(double*)xmalloc(M*sizeof(double));
+		for(int i=0;i<M;i++)doublevec[i]=(double)intvec[i];
+	}
+	else doublevec=NULL;
+	xfree((void**)&intvec);
+				
+	pfield=mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pfield,M);
+	mxSetN(pfield,1);
+	mxSetPr(pfield,doublevec);
+	
+	mxSetField(dataref, 0, name, pfield);
+}
+#endif
+/*}}}*/
+/*FUNCTION IntVecParam::SetValue{{{1*/
+void  IntVecParam::SetValue(int* intarray,int in_M){
+
+	/*avoid leak: */
+	xfree((void**)&this->values);
+
+	if(in_M){
+		this->values=(int*)xmalloc(in_M*sizeof(int));
+		memcpy(this->values,intarray,in_M*sizeof(int));
+	}
+	else this->values=NULL;
+
+	this->M=in_M;
+}
+/*}}}*/
+/*FUNCTION IntVecParam::UnitConversion{{{1*/
+void  IntVecParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/IntVecParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/IntVecParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/IntVecParam.h	(revision 11330)
@@ -0,0 +1,90 @@
+/*! \file IntVecParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _INTVECPARAM_H_
+#define _INTVECPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class IntVecParam: public Param{
+
+	private: 
+		int enum_type;
+		int* values;
+		int M;
+
+	public:
+		/*IntVecParam constructors, destructors: {{{1*/
+		IntVecParam();
+		IntVecParam(int enum_type,int* values,int M);
+		IntVecParam(int enum_type,double* values,int M);
+		~IntVecParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param virtual functions definitions: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("IntVec param of enum %i (%s) cannot return a bool",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int* pinteger){_error_("IntVec param of enum %i (%s) cannot return an integer",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM);
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("IntVec param of enum %i (%s) cannot return a matrix",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double* pdouble){_error_("IntVec param of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char** pstring){_error_("IntVec param of enum %i (%s) cannot return a string",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("IntVec param of enum %i (%s) cannot return a string array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM){_error_("IntVec param of enum %i (%s) cannot return a double array (maybe in serial?)",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM, int* pN){_error_("IntVec param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims){_error_("IntVec param of enum %i (%s) cannot return a matrix array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Vec* pvec){_error_("IntVec param of enum %i (%s) cannot return a Vec",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Mat* pmat){_error_("IntVec param of enum %i (%s) cannot return a Mat",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(FILE** pfid){_error_("IntVec param of enum %i (%s) cannot return a FILE",enum_type,EnumToStringx(enum_type));}
+
+		void  SetValue(bool boolean){_error_("IntVec param of enum %i (%s) cannot hold a boolean",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int integer){_error_("IntVec param of enum %i (%s) cannot hold an integer",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double scalar){_error_("IntVec param of enum %i (%s) cannot hold a scalar",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char* string){_error_("IntVec param of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char** stringarray,int M){_error_("IntVec param of enum %i (%s) cannot hold a string array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M){_error_("IntVec param of enum %i (%s) cannot hold a double mat array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* pdoublearray,int M,int N){_error_("IntVec param of enum %i (%s) cannot hold a double mat array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* intarray,int M);
+		void  SetValue(int* pintarray,int M,int N){_error_("IntVec param of enum %i (%s) cannot hold a int mat array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Vec vec){_error_("IntVec param of enum %i (%s) cannot hold a Vec",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Mat mat){_error_("IntVec param of enum %i (%s) cannot hold a Mat",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(FILE* fid){_error_("IntVec param of enum %i (%s) cannot hold a FILE",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double** array, int M, int* mdim_array, int* ndim_array){_error_("IntVec param of enum %i (%s) cannot hold an array of matrices",enum_type,EnumToStringx(enum_type));}
+		void  UnitConversion(int direction_enum);
+		
+		void GetParameterName(char**pname);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+		/*}}}*/
+};
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Params/Param.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/Param.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/Param.h	(revision 11330)
@@ -0,0 +1,66 @@
+/*!\file:  Param.h
+ * \brief abstract class for Param object
+ */ 
+
+
+#ifndef _PARAM_H_
+#define _PARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "../Object.h"
+#include "../Node.h"
+/*}}}*/
+
+class Param: public Object{
+
+	public: 
+		virtual        ~Param(){};
+
+		/*Virtual functions:*/
+		virtual int   InstanceEnum()=0;
+		virtual void  GetParameterValue(bool* pbool)=0;
+		virtual void  GetParameterValue(int* pinteger)=0;
+		virtual void  GetParameterValue(int** pintarray,int* pM)=0;
+		virtual void  GetParameterValue(int** pintarray,int* pM,int* pN)=0;
+		virtual void  GetParameterValue(double* pdouble)=0;
+		virtual void  GetParameterValue(char** pstring)=0;
+		virtual void  GetParameterValue(char*** pstringarray,int* pM)=0;
+		virtual void  GetParameterValue(double** pdoublearray,int* pM)=0;
+		virtual void  GetParameterValue(double** pdoublearray,int* pM,int* pN)=0;
+		virtual void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims)=0;
+		virtual void  GetParameterValue(Vec* pvec)=0;
+		virtual void  GetParameterValue(Mat* pmat)=0;
+		virtual void  GetParameterValue(FILE** pfid)=0;
+		
+		virtual void  SetValue(bool boolean)=0;
+		virtual void  SetValue(int integer)=0;
+		virtual void  SetValue(double scalar)=0;
+		virtual void  SetValue(char* string)=0;
+		virtual void  SetValue(char** stringarray,int M)=0;
+		virtual void  SetValue(double* doublearray,int M)=0;
+		virtual void  SetValue(double* pdoublearray,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(Vec vec)=0;
+		virtual void  SetValue(Mat mat)=0;
+		virtual void  SetValue(FILE* fid)=0;
+		virtual void  SetValue(double** array, int M, int* mdim_array, int* ndim_array)=0;
+		virtual void  UnitConversion(int direction_enum)=0;
+		virtual void  GetParameterName(char**pname)=0;
+		#ifdef _SERIAL_
+		virtual void  SetMatlabField(mxArray* dataref)=0;
+		#endif
+};
+#endif
Index: /issm/trunk-jpl-damage/src/c/objects/Params/PetscMatParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/PetscMatParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/PetscMatParam.cpp	(revision 11330)
@@ -0,0 +1,242 @@
+/*!\file PetscMatParam.c
+ * \brief: implementation of the PetscMatParam object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*PetscMatParam constructors and destructor*/
+/*FUNCTION PetscMatParam::PetscMatParam(){{{1*/
+PetscMatParam::PetscMatParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION PetscMatParam::PetscMatParam(int enum_type,IssmPetscMat value){{{1*/
+PetscMatParam::PetscMatParam(int in_enum_type,Mat in_value){
+
+	enum_type=in_enum_type;
+
+	value=NULL;
+
+	if(in_value){
+		MatDuplicate(in_value,MAT_COPY_VALUES,&value);
+	}
+}
+/*}}}*/
+/*FUNCTION PetscMatParam::~PetscMatParam(){{{1*/
+PetscMatParam::~PetscMatParam(){
+	MatFree(&value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION PetscMatParam::Echo {{{1*/
+void PetscMatParam::Echo(void){
+
+	printf("PetscMatParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+
+}
+/*}}}*/
+/*FUNCTION PetscMatParam::DeepEcho{{{1*/
+void PetscMatParam::DeepEcho(void){
+
+	int i;
+	printf("PetscMatParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	MatView(value,PETSC_VIEWER_STDOUT_WORLD);
+}
+/*}}}*/
+/*FUNCTION PetscMatParam::Id{{{1*/
+int    PetscMatParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION PetscMatParam::MyRank{{{1*/
+int    PetscMatParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION PetscMatParam::Marshall{{{1*/
+void  PetscMatParam::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+	int   M,N;
+	double* serial_mat=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of PetscMatParam: */
+	enum_value=PetscMatParamEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall PetscMatParam data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	if(value){
+		MatGetSize(value,&M,&N);
+		MatToSerial(&serial_mat,value);
+		memcpy(marshalled_dataset,&M,sizeof(M));marshalled_dataset+=sizeof(M);
+		memcpy(marshalled_dataset,&N,sizeof(N));marshalled_dataset+=sizeof(N);
+		memcpy(marshalled_dataset,serial_mat,M*N*sizeof(double));marshalled_dataset+=(M*N*sizeof(double));
+	}
+	else{
+		M=0;
+		N=0;
+		memcpy(marshalled_dataset,&M,sizeof(M));marshalled_dataset+=sizeof(M);
+		memcpy(marshalled_dataset,&N,sizeof(N));marshalled_dataset+=sizeof(N);
+	}
+	
+	/*Free ressources:*/
+	xfree((void**)&serial_mat);
+
+	/*return:*/
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION PetscMatParam::MarshallSize{{{1*/
+int   PetscMatParam::MarshallSize(){
+
+	int M=0;
+	int N=0;
+	if(value)MatGetSize(value,&M,&N);
+			
+	return sizeof(M)+
+		sizeof(N)+
+		M*N*sizeof(double)+
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION PetscMatParam::Demarshall{{{1*/
+void  PetscMatParam::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i,j;
+	int   M,N;
+	double* serial_mat=NULL;
+	int*    idxm=NULL;
+	int*    idxn=NULL;
+	double sparsity=.001;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*data: */
+	memcpy(&M,marshalled_dataset,sizeof(M));marshalled_dataset+=sizeof(M);
+	memcpy(&N,marshalled_dataset,sizeof(N));marshalled_dataset+=sizeof(N);
+	if(M!=0 && N!=0){
+		serial_mat=(double*)xmalloc(M*N*sizeof(double));
+		memcpy(serial_mat,marshalled_dataset,M*N*sizeof(double));marshalled_dataset+=(M*N*sizeof(double));
+		value=NewMat(M,N,sparsity);
+		idxm=(int*)xmalloc(M*sizeof(int));
+		idxn=(int*)xmalloc(N*sizeof(int));
+		for(i=0;i<M;i++)idxm[i]=i;
+		for(i=0;i<N;i++)idxn[i]=i;
+		MatSetValues(value,M,idxm,N,idxn,serial_mat,INSERT_VALUES); 
+		MatAssemblyBegin(value,MAT_FINAL_ASSEMBLY); 
+		MatAssemblyEnd(value,MAT_FINAL_ASSEMBLY);
+
+			}
+	else{
+		value=NULL;
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&serial_mat);
+	xfree((void**)&idxm);
+	xfree((void**)&idxn);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+#endif
+/*FUNCTION PetscMatParam::ObjectEnum{{{1*/
+int PetscMatParam::ObjectEnum(void){
+
+	return PetscMatParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION PetscMatParam::copy{{{1*/
+Object* PetscMatParam::copy() {
+	
+	return new PetscMatParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*PetscMatParam virtual functions definitions: */
+/*FUNCTION PetscMatParam::GetParameterValue{{{1*/
+void  PetscMatParam::GetParameterValue(Mat* poutput){
+	Mat output=NULL;
+
+	if(value){
+		MatDuplicate(value,MAT_COPY_VALUES,&output);
+	}
+	*poutput=output;
+}
+/*}}}*/
+/*FUNCTION PetscMatParam::GetParameterName{{{1*/
+void PetscMatParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION PetscMatParam::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  PetscMatParam::SetMatlabField(mxArray* dataref){
+	
+	char* name=NULL;
+	int   M,N;
+	double* doublemat=NULL;
+	mxArray* pfield=NULL;
+
+	MatToSerial(&doublemat,value);
+	MatGetSize(value,&M,&N);
+	this->GetParameterName(&name);
+				
+	pfield=mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pfield,M);
+	mxSetN(pfield,N);
+	mxSetPr(pfield,doublemat);
+	mxSetField( dataref, 0, name, pfield);
+}
+#endif
+/*}}}*/
+/*FUNCTION PetscMatParam::SetValue{{{1*/
+void  PetscMatParam::SetValue(Mat matrix){
+	
+	/*avoid leak: */
+	MatFree(&value);
+	
+	/*copy: */
+	MatDuplicate(matrix,MAT_COPY_VALUES,&value);
+}
+/*}}}*/
+/*FUNCTION PetscMatParam::UnitConversion{{{1*/
+void  PetscMatParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/PetscMatParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/PetscMatParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/PetscMatParam.h	(revision 11330)
@@ -0,0 +1,90 @@
+/*! \file PetscMatParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _PETSCMATPARAM_H_
+#define _PETSCMATPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class PetscMatParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		Mat value;
+
+	public:
+		/*PetscMatParam constructors, destructors: {{{1*/
+		PetscMatParam();
+		PetscMatParam(int enum_type,Mat value);
+		~PetscMatParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("PetscMat param of enum %i (%s) cannot return a bool",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int* pinteger){_error_("PetscMat param of enum %i (%s) cannot return an integer",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("PetscMat param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("PetscMat param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double* pdouble){_error_("PetscMat param of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char** pstring){_error_("PetscMat param of enum %i (%s) cannot return a string",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("PetscMat param of enum %i (%s) cannot return a string arrayl",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM){_error_("PetscMat param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM, int* pN){_error_("PetscMat param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims){_error_("PetscMat param of enum %i (%s) cannot return a matrix array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Vec* pvec){_error_("PetscMat param of enum %i (%s) cannot return a vec",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Mat* poutput);
+		void  GetParameterValue(FILE** pfid){_error_("PetscMat param of enum %i (%s) cannot return a FILE",enum_type,EnumToStringx(enum_type));}
+
+		void  SetValue(bool boolean){_error_("PetscMat param of enum %i (%s) cannot hold a boolean",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int integer){_error_("PetscMat param of enum %i (%s) cannot hold an integer",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double scalar){_error_("PetscMat param of enum %i (%s) cannot hold a scalar",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char* string){_error_("PetscMat param of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char** stringarray,int M){_error_("PetscMat param of enum %i (%s) cannot hold a string array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M){_error_("PetscMat param of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* pdoublearray,int M,int N){_error_("PetscMat param of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* intarray,int M){_error_("PetscMat param of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* pintarray,int M,int N){_error_("PetscMat param of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Vec vec){_error_("PetscMat param of enum %i (%s) cannot hold a Vec",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Mat mat);
+		void  SetValue(FILE* fid){_error_("PetscMat param of enum %i (%s) cannot hold a FILE",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double** array, int M, int* mdim_array, int* ndim_array){_error_("PetscMat param of enum %i (%s) cannot hold an array of matrices",enum_type,EnumToStringx(enum_type));}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+
+		/*}}}*/
+};
+#endif  /* _PETSCMATPARAM_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Params/PetscVecParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/PetscVecParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/PetscVecParam.cpp	(revision 11330)
@@ -0,0 +1,237 @@
+/*!\file PetscVecParam.c
+ * \brief: implementation of the PetscVecParam object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*PetscVecParam constructors and destructor*/
+/*FUNCTION PetscVecParam::PetscVecParam(){{{1*/
+PetscVecParam::PetscVecParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION PetscVecParam::PetscVecParam(int enum_type,IssmPetscVec value){{{1*/
+PetscVecParam::PetscVecParam(int in_enum_type,Vec in_value){
+
+	enum_type=in_enum_type;
+
+	value=NULL;
+
+	if(in_value){
+		VecDuplicate(in_value,&value);
+		VecCopy(in_value,value);
+	}
+}
+/*}}}*/
+/*FUNCTION PetscVecParam::~PetscVecParam(){{{1*/
+PetscVecParam::~PetscVecParam(){
+	VecFree(&value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION PetscVecParam::Echo {{{1*/
+void PetscVecParam::Echo(void){
+
+	printf("PetscVecParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+
+}
+/*}}}*/
+/*FUNCTION PetscVecParam::DeepEcho{{{1*/
+void PetscVecParam::DeepEcho(void){
+
+	int i;
+	printf("PetscVecParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	VecView(value,PETSC_VIEWER_STDOUT_WORLD);
+}
+/*}}}*/
+/*FUNCTION PetscVecParam::Id{{{1*/
+int    PetscVecParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION PetscVecParam::MyRank{{{1*/
+int    PetscVecParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION PetscVecParam::Marshall{{{1*/
+void  PetscVecParam::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+	int   M;
+	double* serial_value=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of PetscVecParam: */
+	enum_value=PetscVecParamEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall PetscVecParam data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	if(value){
+		VecGetSize(value,&M);
+		VecToMPISerial(&serial_value,value);
+		memcpy(marshalled_dataset,&M,sizeof(M));marshalled_dataset+=sizeof(M);
+		memcpy(marshalled_dataset,serial_value,M*sizeof(double));marshalled_dataset+=(M*sizeof(double));
+	}
+	else{
+		M=0;
+		memcpy(marshalled_dataset,&M,sizeof(M));marshalled_dataset+=sizeof(M);
+	}
+	/*Free ressources:*/
+	xfree((void**)&serial_value);
+
+	/*return:*/
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION PetscVecParam::MarshallSize{{{1*/
+int   PetscVecParam::MarshallSize(){
+
+	int M=0;
+	if(value)VecGetSize(value,&M);
+
+	return sizeof(M)+M*sizeof(double)
+		+sizeof(enum_type)+
+		+sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION PetscVecParam::Demarshall{{{1*/
+void  PetscVecParam::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+	int   M;
+	double* serial_vec=NULL;
+	int*    idxm=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	
+	/*data: */
+	
+	memcpy(&M,marshalled_dataset,sizeof(M));marshalled_dataset+=sizeof(M);
+	if(M){
+		serial_vec=(double*)xmalloc(M*sizeof(double));
+		memcpy(serial_vec,marshalled_dataset,M*sizeof(double));marshalled_dataset+=(M*sizeof(double));
+
+		value=NewVec(M);
+		idxm=(int*)xmalloc(M*sizeof(int));
+		for(i=0;i<M;i++)idxm[i]=i;
+		VecSetValues(value,M,idxm,serial_vec,INSERT_VALUES);
+
+		VecAssemblyBegin(value);
+		VecAssemblyEnd(value);
+
+		
+	}
+	else{
+		value=NULL;
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&serial_vec);
+	xfree((void**)&idxm);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+#endif
+/*FUNCTION PetscVecParam::ObjectEnum{{{1*/
+int PetscVecParam::ObjectEnum(void){
+
+	return PetscVecParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION PetscVecParam::copy{{{1*/
+Object* PetscVecParam::copy() {
+	
+	return new PetscVecParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*PetscVecParam virtual functions definitions: */
+/*FUNCTION PetscVecParam::GetParameterValue{{{1*/
+void  PetscVecParam::GetParameterValue(Vec* poutput){
+	Vec output=NULL;
+
+	if(value){
+		VecDuplicate(value,&output);
+		VecCopy(value,output);
+	}
+	*poutput=output;
+}
+/*}}}*/
+/*FUNCTION PetscVecParam::GetParameterName{{{1*/
+void PetscVecParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION PetscVecParam::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  PetscVecParam::SetMatlabField(mxArray* dataref){
+
+	mxArray* pfield=NULL;
+	char* name=NULL;
+	double* doublevec=NULL;
+	int M;
+	
+	VecToMPISerial(&doublevec,value);
+	VecGetSize(value,&M);
+	this->GetParameterName(&name);
+	
+	pfield=mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pfield,M);
+	mxSetN(pfield,1);
+	mxSetPr(pfield,doublevec);
+	
+	mxSetField( dataref, 0, name, pfield);
+}
+#endif
+/*}}}*/
+/*FUNCTION PetscVecParam::SetValue{{{1*/
+void  PetscVecParam::SetValue(Vec vector){
+
+	/*avoid leak: */
+	VecFree(&value);
+	
+	/*copy: */
+	VecDuplicate(vector,&value);
+	VecCopy(vector,value);
+}
+/*}}}*/
+/*FUNCTION PetscVecParam::UnitConversion{{{1*/
+void  PetscVecParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/PetscVecParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/PetscVecParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/PetscVecParam.h	(revision 11330)
@@ -0,0 +1,90 @@
+/*! \file PetscVecParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _PETSCVECPARAM_H_
+#define _PETSCVECPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class PetscVecParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		Vec value;
+
+	public:
+		/*PetscVecParam constructors, destructors: {{{1*/
+		PetscVecParam();
+		PetscVecParam(int enum_type,Vec value);
+		~PetscVecParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("PetscVec param of enum %i (%s) cannot return a bool",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int* pinteger){_error_("PetscVec param of enum %i (%s) cannot return an integer",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("PetscVec param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("PetscVec param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double* pdouble){_error_("PetscVec param of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char** pstring){_error_("PetscVec param of enum %i (%s) cannot return a string",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("PetscVec param of enum %i (%s) cannot return a string arrayl",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM){_error_("PetscVec param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM, int* pN){_error_("PetscVec param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims){_error_("PetscVec param of enum %i (%s) cannot return a matrix array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Mat* pmat){_error_("PetscVec param of enum %i (%s) cannot return a Mat",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Vec* poutput);
+		void  GetParameterValue(FILE** pfid){_error_("PetscVec of enum %i (%s) cannot return a FILE",enum_type,EnumToStringx(enum_type));}
+
+		void  SetValue(bool boolean){_error_("PetscVec of enum %i (%s) cannot hold a boolean",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int integer){_error_("PetscVec of enum %i (%s) cannot hold an integer",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double scalar){_error_("PetscVec of enum %i (%s) cannot hold a scalar",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char* string){_error_("PetscVec of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char** stringarray,int M){_error_("PetscVec of enum %i (%s) cannot hold a string array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M){_error_("PetscVec of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* pdoublearray,int M,int N){_error_("PetscVec of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* intarray,int M){_error_("PetscVec of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* pintarray,int M,int N){_error_("PetscVec of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Vec vec);
+		void  SetValue(Mat mat){_error_("PetscVec of enum %i (%s) cannot hold a Mat",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(FILE* fid){_error_("PetscVec of enum %i (%s) cannot hold a FILE",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double** array, int M, int* mdim_array, int* ndim_array){_error_("PetscVec param of enum %i (%s) cannot hold an array of matrices",enum_type,EnumToStringx(enum_type));}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+
+		/*}}}*/
+};
+#endif  /* _PETSCVECPARAM_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Params/StringArrayParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/StringArrayParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/StringArrayParam.cpp	(revision 11330)
@@ -0,0 +1,293 @@
+/*!\file StringArrayParam.c
+ * \brief: implementation of the StringArrayParam object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*StringArrayParam constructors and destructor*/
+/*FUNCTION StringArrayParam::StringArrayParam(){{{1*/
+StringArrayParam::StringArrayParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::StringArrayParam(int enum_type,char** in_values,int in_numstrings){{{1*/
+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=(char**)xmalloc(numstrings*sizeof(char*));
+		for(i=0;i<numstrings;i++){
+			char* string=NULL;
+			size=strlen(in_values[i])+1;
+			string=(char*)xmalloc(size*sizeof(char));
+			memcpy(string,in_values[i],size*sizeof(char));
+			value[i]=string;
+		}
+	}
+	else value=NULL;
+	
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::~StringArrayParam(){{{1*/
+StringArrayParam::~StringArrayParam(){
+		
+	int i;
+	
+	char* string=NULL;
+	for(i=0;i<this->numstrings;i++){
+		string=value[i];
+		xfree((void**)&string);
+	}
+	xfree((void**)&value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION StringArrayParam::Echo {{{1*/
+void StringArrayParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::DeepEcho{{{1*/
+void StringArrayParam::DeepEcho(void){
+
+	int i;
+	char* string=NULL;
+
+	printf("StringArrayParam:\n");
+	printf("   enum: %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	for(i=0;i<this->numstrings;i++){
+		string=this->value[i];
+		printf("   %i: %s\n",i,string);
+	}
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::Id{{{1*/
+int    StringArrayParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION StringArrayParam::MyRank{{{1*/
+int    StringArrayParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION StringArrayParam::Marshall{{{1*/
+void  StringArrayParam::Marshall(char** pmarshalled_dataset){
+
+	int   i;
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+	int   stringsize;
+	char* string=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of StringArrayParam: */
+	enum_value=StringArrayParamEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+	
+	/*marshall data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	memcpy(marshalled_dataset,&numstrings,sizeof(numstrings));marshalled_dataset+=sizeof(numstrings);
+	for(i=0;i<numstrings;i++){
+		string=this->value[i];
+		stringsize=strlen(string)+1;
+		
+		memcpy(marshalled_dataset,&stringsize,sizeof(stringsize));marshalled_dataset+=sizeof(stringsize);
+		memcpy(marshalled_dataset,string,stringsize*sizeof(char));marshalled_dataset+=stringsize*sizeof(char);
+	}
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::MarshallSize{{{1*/
+int   StringArrayParam::MarshallSize(){
+
+	int i;
+	int marshallsize=0;
+	int stringsize;
+	char* string=NULL;
+
+	marshallsize+=sizeof(numstrings);
+
+	for(i=0;i<numstrings;i++){
+		string=this->value[i];
+		stringsize=strlen(string)+1;
+		marshallsize+=sizeof(stringsize);
+		marshallsize+=stringsize*sizeof(char);
+	}
+	
+	marshallsize+=sizeof(enum_type);
+	marshallsize+=sizeof(int); //sizeof(int) for enum value
+
+	return marshallsize;
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::Demarshall{{{1*/
+void  StringArrayParam::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+	int   stringsize;
+	char* string=NULL;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+
+	memcpy(&numstrings,marshalled_dataset,sizeof(int));marshalled_dataset+=sizeof(int);
+	if(numstrings){
+		this->value=(char**)xmalloc(numstrings*sizeof(char*));
+
+		for(i=0;i<numstrings;i++){
+			memcpy(&stringsize,marshalled_dataset,sizeof(int));marshalled_dataset+=sizeof(int);
+
+			string=(char*)xmalloc(stringsize*sizeof(char));
+			memcpy(string,marshalled_dataset,stringsize*sizeof(char));marshalled_dataset+=stringsize*sizeof(char);
+
+			this->value[i]=string;
+		}
+	}
+	else this->value=NULL;
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION StringArrayParam::ObjectEnum{{{1*/
+int StringArrayParam::ObjectEnum(void){
+
+	return StringArrayParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::copy{{{1*/
+Object* StringArrayParam::copy() {
+	
+	return new StringArrayParam(this->enum_type,this->value,this->numstrings);
+
+}
+/*}}}*/
+
+/*StringArrayParam virtual functions definitions: */
+/*FUNCTION StringArrayParam::GetParameterValue{{{1*/
+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=(char**)xmalloc(this->numstrings*sizeof(char*));
+
+		for(i=0;i<this->numstrings;i++){
+			string=this->value[i];
+			stringsize=strlen(string)+1;
+
+			string2=(char*)xmalloc(stringsize*sizeof(char));
+			memcpy(string2,string,stringsize*sizeof(char));
+
+			outstrings[i]=string2;
+		}
+	}
+	else outstrings=NULL;
+
+	/*Assign output pointers:*/
+	*pM=M;
+	*pstringarray=outstrings;
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::GetParameterName{{{1*/
+void StringArrayParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  StringArrayParam::SetMatlabField(mxArray* dataref){
+	
+	int      i;
+	char*    name=NULL;
+	mwSize   dims[2]={0};
+	mxArray* pfield=NULL;
+	
+	this->GetParameterName(&name);
+
+	dims[0]=this->numstrings;
+	dims[1]=1;
+	pfield=mxCreateCellArray(2,dims);
+	for(i=0;i<this->numstrings;i++){
+		char* string=value[i];
+		mxSetCell(pfield,i,mxCreateString(string));
+	}
+	mxSetField( dataref, 0, name,pfield);
+}
+#endif
+/*}}}*/
+/*FUNCTION StringArrayParam::SetValue{{{1*/
+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];
+		xfree((void**)&string);
+	}
+	xfree((void**)&this->value);
+
+	/*copy: */
+	this->numstrings=M;
+	this->value=(char**)xmalloc(this->numstrings*sizeof(char*));
+	for(i=0;i<this->numstrings;i++){
+		string=stringarray[i];
+		stringsize=strlen(string)+1;
+
+		string2=(char*)xmalloc(stringsize*sizeof(char));
+		memcpy(string2,string,stringsize*sizeof(char));
+
+		this->value[i]=string2;
+	}
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::UnitConversion{{{1*/
+void  StringArrayParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/StringArrayParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/StringArrayParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/StringArrayParam.h	(revision 11330)
@@ -0,0 +1,91 @@
+/*! \file StringArrayParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _STRINGARRAYPARAM_H_
+#define _STRINGARRAYPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class StringArrayParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int      enum_type;
+		char**   value;
+		int      numstrings;
+
+
+	public:
+		/*StringArrayParam constructors, destructors: {{{1*/
+		StringArrayParam();
+		StringArrayParam(int enum_type,char** values, int numstrings);
+		~StringArrayParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("StringArray param of enum %i (%s) cannot return a bool",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int* pinteger){_error_("StringArray param of enum %i (%s) cannot return an integer",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("StringArray param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("StringArray param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double* pdouble){_error_("StringArray param of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char** pstring){_error_("StringArray param of enum %i (%s) cannot return a string",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char*** pstringarray,int* pM);
+		void  GetParameterValue(double** pdoublearray,int* pM){_error_("StringArray param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM, int* pN){_error_("StringArray param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims){_error_("Vec param of enum %i (%s) cannot return a matrix array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Vec* pvec){_error_("StringArray param of enum %i (%s) cannot return a Vec",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Mat* pmat){_error_("StringArray param of enum %i (%s) cannot return a Mat",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(FILE** pfid){_error_("StringArray param of enum %i (%s) cannot return a FILE",enum_type,EnumToStringx(enum_type));}
+
+		void  SetValue(bool boolean){_error_("StringArray param of enum %i (%s) cannot hold a boolean",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int integer){_error_("StringArray param of enum %i (%s) cannot hold an integer",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double scalar){_error_("StringArray param of enum %i (%s) cannot hold a scalar",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char* string){_error_("StringArray param of enum %i (%s) cannot hold a string",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char** stringarray,int M);
+		void  SetValue(double* doublearray,int M){_error_("StringArray param of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* pdoublearray,int M,int N){_error_("StringArray param of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* intarray,int M){_error_("StringArray param of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* pintarray,int M,int N){_error_("StringArray param of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Vec vec){_error_("StringArray param of enum %i (%s) cannot hold a Vec",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Mat mat){_error_("StringArray param of enum %i (%s) cannot hold a Mat",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(FILE* fid){_error_("StringArray param of enum %i (%s) cannot hold a FILE",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double** array, int M, int* mdim_array, int* ndim_array){_error_("StringArray param of enum %i (%s) cannot hold an array of matrices",enum_type,EnumToStringx(enum_type));}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+		/*}}}*/
+};
+#endif  /* _STRINGARRAYPARAM_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Params/StringParam.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/StringParam.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/StringParam.cpp	(revision 11330)
@@ -0,0 +1,196 @@
+/*!\file StringParam.c
+ * \brief: implementation of the StringParam object
+ */
+
+/*header files: */
+/*{{{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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*StringParam constructors and destructor*/
+/*FUNCTION StringParam::StringParam(){{{1*/
+StringParam::StringParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION StringParam::StringParam(int enum_type,IssmString value){{{1*/
+StringParam::StringParam(int in_enum_type,char* in_value){
+
+	enum_type=in_enum_type;
+	value=(char*)xmalloc((strlen(in_value)+1)*sizeof(char));
+	memcpy(value,in_value,(strlen(in_value)+1)*sizeof(char));
+
+	
+}
+/*}}}*/
+/*FUNCTION StringParam::~StringParam(){{{1*/
+StringParam::~StringParam(){
+	xfree((void**)&value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION StringParam::Echo {{{1*/
+void StringParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION StringParam::DeepEcho{{{1*/
+void StringParam::DeepEcho(void){
+	printf("StringParam:\n");
+	printf("   enum:  %i (%s)\n",this->enum_type,EnumToStringx(this->enum_type));
+	printf("   value: %s\n",this->value);
+}
+/*}}}*/
+/*FUNCTION StringParam::Id{{{1*/
+int    StringParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION StringParam::MyRank{{{1*/
+int    StringParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION StringParam::Marshall{{{1*/
+void  StringParam::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_value=0;
+	int   stringsize;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum value of StringParam: */
+	enum_value=StringParamEnum;
+	
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_value,sizeof(enum_value));marshalled_dataset+=sizeof(enum_value);
+
+	/*marshall data: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+	stringsize=strlen(this->value)+1;
+	
+	memcpy(marshalled_dataset,&stringsize,sizeof(stringsize));marshalled_dataset+=sizeof(stringsize);
+	memcpy(marshalled_dataset,this->value,stringsize*sizeof(char));marshalled_dataset+=stringsize*sizeof(char);
+
+	*pmarshalled_dataset=marshalled_dataset;
+}
+/*}}}*/
+/*FUNCTION StringParam::MarshallSize{{{1*/
+int   StringParam::MarshallSize(){
+
+	int stringsize;
+	stringsize=strlen(this->value)+1;
+	
+	return sizeof(int)+
+		stringsize*sizeof(char)+
+		sizeof(enum_type)+
+		sizeof(int); //sizeof(int) for enum value
+}
+/*}}}*/
+/*FUNCTION StringParam::Demarshall{{{1*/
+void  StringParam::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+	int   stringsize;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+	memcpy(&enum_type,marshalled_dataset,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+
+	memcpy(&stringsize,marshalled_dataset,sizeof(int));marshalled_dataset+=sizeof(int);
+	
+	this->value=(char*)xmalloc(stringsize*sizeof(char));
+	memcpy(this->value,marshalled_dataset,stringsize*sizeof(char));marshalled_dataset+=stringsize*sizeof(char);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION StringParam::ObjectEnum{{{1*/
+int StringParam::ObjectEnum(void){
+
+	return StringParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION StringParam::copy{{{1*/
+Object* StringParam::copy() {
+	
+	return new StringParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*StringParam virtual functions definitions: */
+/*FUNCTION StringParam::GetParameterValue{{{1*/
+void  StringParam::GetParameterValue(char** pstring){
+	
+	char* outstring=NULL;
+	int   stringsize;
+
+	stringsize=strlen(this->value)+1;
+
+	outstring=(char*)xmalloc(stringsize*sizeof(char));
+	memcpy(outstring,this->value,stringsize*sizeof(char));
+
+	*pstring=outstring;
+
+}
+/*}}}*/
+/*FUNCTION StringParam::GetParameterName{{{1*/
+void StringParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION StringParam::SetMatlabField{{{1*/
+#ifdef _SERIAL_
+void  StringParam::SetMatlabField(mxArray* dataref){
+	
+	char* name=NULL;
+
+	this->GetParameterName(&name);
+	mxSetField( dataref, 0, name, mxCreateString(value));
+}
+#endif
+/*}}}*/
+/*FUNCTION StringParam::SetValue{{{1*/
+void  StringParam::SetValue(char* string){
+	
+	int   stringsize;
+	
+	/*avoid leak: */
+	xfree((void**)&this->value);
+
+	/*copy: */
+	stringsize=strlen(string)+1;
+	this->value=(char*)xmalloc(stringsize*sizeof(char));
+	memcpy(this->value,string,stringsize*sizeof(char));
+
+}
+/*}}}*/
+/*FUNCTION StringParam::UnitConversion{{{1*/
+void  StringParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Params/StringParam.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Params/StringParam.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Params/StringParam.h	(revision 11330)
@@ -0,0 +1,90 @@
+/*! \file StringParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _STRINGPARAM_H_
+#define _STRINGPARAM_H_
+
+/*Headers:*/
+/*{{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+
+#include "./Param.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class StringParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		char* value;
+
+	public:
+		/*StringParam constructors, destructors: {{{1*/
+		StringParam();
+		StringParam(int enum_type,char* value);
+		~StringParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{1*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("String param of enum %i (%s) cannot return a bool",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int* pinteger){_error_("String param of enum %i (%s) cannot return an integer",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("String param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("String param of enum %i (%s) cannot return an array of integers",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double* pdouble){_error_("String param of enum %i (%s) cannot return a double",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(char** pstring);
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("String param of enum %i (%s) cannot return a string arrayl",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM){_error_("String param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double** pdoublearray,int* pM, int* pN){_error_("String param of enum %i (%s) cannot return a double array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(double*** parray, int* pM,int** pmdims, int** pndims){_error_("String param of enum %i (%s) cannot return a matrix array",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Vec* pvec){_error_("String param of enum %i (%s) cannot return a Vec",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(Mat* pmat){_error_("String param of enum %i (%s) cannot return a Mat",enum_type,EnumToStringx(enum_type));}
+		void  GetParameterValue(FILE** pfid){_error_("Bool param of enum %i (%s) cannot return a FILE",enum_type,EnumToStringx(enum_type));}
+
+		void  SetValue(bool boolean){_error_("String param of enum %i (%s) cannot hold a boolean",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int integer){_error_("String param of enum %i (%s) cannot hold an integer",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double scalar){_error_("String param of enum %i (%s) cannot hold a scalar",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(char* string);
+		void  SetValue(char** stringarray,int M){_error_("String param of enum %i (%s) cannot hold a string array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* doublearray,int M){_error_("String param of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double* pdoublearray,int M,int N){_error_("String param of enum %i (%s) cannot hold a double array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* intarray,int M){_error_("String param of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(int* pintarray,int M,int N){_error_("String param of enum %i (%s) cannot hold a int array",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Vec vec){_error_("String param of enum %i (%s) cannot hold a Vec",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(Mat mat){_error_("String param of enum %i (%s) cannot hold a Mat",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(FILE* fid){_error_("String param of enum %i (%s) cannot hold a FILE",enum_type,EnumToStringx(enum_type));}
+		void  SetValue(double** array, int M, int* mdim_array, int* ndim_array){_error_("String param of enum %i (%s) cannot hold an array of matrices",enum_type,EnumToStringx(enum_type));}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+		#ifdef _SERIAL_
+		void  SetMatlabField(mxArray* dataref);
+		#endif
+
+		/*}}}*/
+};
+#endif  /* _STRINGPARAM_H */
Index: /issm/trunk-jpl-damage/src/c/objects/Patch.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Patch.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Patch.cpp	(revision 11330)
@@ -0,0 +1,168 @@
+/*!\file Patch.c
+ * \brief: implementation of the Patch object
+ */
+
+/*Include files: {{{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 "./objects.h"
+#include "../Container/Container.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+/*}}}*/
+
+/*Object constructors and destructors:*/
+/*FUNCTION Patch::Patch() default constructor {{{1*/
+Patch::Patch(){
+	this->numrows=0;
+	this->numcols=0;
+	this->maxvertices=0;
+	this->maxnodes=0;
+	this->values=NULL;
+}
+/*}}}*/
+/*FUNCTION Patch::Patch(int numrows, int maxvertices, int maxnodes){{{1*/
+Patch::Patch(int in_numrows, int in_maxvertices, int in_maxnodes){
+
+	int i,j;
+	this->numrows=in_numrows;
+	this->maxvertices=in_maxvertices;
+	this->maxnodes=in_maxnodes;
+    
+	this->numcols=1  //enum_type
+		+1           //step
+		+1           //time 
+		+1           //element id
+		+1           //interpolation type
+		+maxvertices //vertices
+		+maxnodes;   //nodes
+
+	//Allocate values and fill with NaN:
+	if (this->numcols*this->numrows==0){
+		this->values=NULL;
+	}
+	else{
+		this->values=(double*)xmalloc(this->numcols*this->numrows*sizeof(double));
+		for(i=0;i<this->numrows;i++){
+			for(j=0;j<this->numcols;j++){
+				this->values[i*this->numcols+j]=NAN;
+			}
+		}
+	}
+
+}
+/*}}}*/
+/*FUNCTION Patch::~Patch(){{{1*/
+Patch::~Patch(){
+	xfree((void**)&values);
+}
+/*}}}*/
+
+/*Object methods*/
+/*FUNCTION Patch::fillelementinfo{{{1*/
+void Patch::fillelementinfo(int count, int element_id, int* vertices_ids, int num_vertices){
+
+	int i;
+	double* row=NULL;
+
+	/*point to the start of the row: */
+	row=this->values+count*this->numcols;
+
+	/*Let's remember what is on a row: 
+	 enum_type step time element_id interpolation vertices_ids nodal_values
+	 */
+	row[3]=element_id;
+	for(i=0;i<num_vertices;i++){
+		row[5+i]=vertices_ids[i];
+	}
+
+}
+/*}}}*/
+/*FUNCTION Patch::fillresultinfo{{{1*/
+void Patch::fillresultinfo(int count,int enum_type,int step, double time, int interpolation, double* nodal_values, int num_nodes){
+
+	int i;
+	double* row=NULL;
+
+	/*point to the start of the row: */
+	row=this->values+count*this->numcols;
+
+	/*Let's remember what is on a row: 
+	 enum_type step time element_id interpolation vertices_ids nodal_values
+	 */
+	row[0]=enum_type;
+	row[1]=(double)step;
+	row[2]=time;
+	row[4]=interpolation;
+	for(i=0;i<num_nodes;i++){
+		row[5+this->maxvertices+i]=nodal_values[i];
+	}
+
+}
+/*}}}*/
+/*FUNCTION Patch::Gather{{{1*/
+void Patch::Gather(void){
+
+	int         i;
+	int         count;
+	extern int  my_rank;
+	extern int  num_procs;
+	int         total_numrows;
+	int         node_numrows;
+	double     *total_values  = NULL;
+	MPI_Status  status;
+
+	#ifdef _SERIAL_
+	return; //nothing to be done
+	#endif
+	
+	/*First, figure out total number of rows combining all the cpus: */
+	MPI_Reduce(&this->numrows,&total_numrows,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&total_numrows,1,MPI_INT,0,MPI_COMM_WORLD);
+
+	/*return if patch empty*/
+	if(total_numrows==0) return;
+
+	/*Now, allocate buffer to holds all the values, on node 0: */
+	if(my_rank==0)total_values=(double*)xmalloc(this->numcols*total_numrows*sizeof(double));
+
+	/*Start by copying node 0 values onto total_values: */
+	if(my_rank==0){
+		count=0;
+		memcpy(total_values+count,this->values,this->numcols*this->numrows*sizeof(double));
+		count+=this->numrows*this->numcols;
+	}
+
+	/*Now, ask other nodes to send their values: */
+	for (i=1;i<num_procs;i++){
+		if (my_rank==i){ 
+			MPI_Send(&this->numrows,1,MPI_INT,0,1,MPI_COMM_WORLD);   
+			if (this->numrows)MPI_Send(this->values,this->numrows*this->numcols,MPI_DOUBLE,0,1,MPI_COMM_WORLD); 
+		}
+		if (my_rank==0){
+			MPI_Recv(&node_numrows,1,MPI_INT,i,1,MPI_COMM_WORLD,&status); 
+			if (node_numrows)MPI_Recv(total_values+count,node_numrows*this->numcols,MPI_DOUBLE,i,1,MPI_COMM_WORLD,&status);
+			count+=node_numrows*this->numcols;
+		}
+	}	
+
+	/*Now, node 0 has total_values, of size total_numrows*this->numcols. Update the fields in the patch, to reflect this new 
+	 * reality. For other cpus, no point in keeping their data anymore: */
+	if(my_rank==0){
+		this->numrows=total_numrows;
+		xfree((void**)&this->values);
+		this->values=total_values;
+	}
+	else{
+		this->numrows=0;
+		xfree((void**)&this->values);
+	}
+}/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Patch.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Patch.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Patch.h	(revision 11330)
@@ -0,0 +1,46 @@
+/*!\file: Patch.h
+ * \brief prototypes for Patch.h
+ */ 
+
+/*A Patch object is used to store all results held in elements, in a serial way, and to dump them to disk. 
+	
+	Each row of the Patch object is made of the following information: 
+	- the result enum_type, 
+	- the step and time, 
+	- the id of the element, 
+	- the interpolation type, 
+	- the vertices ids, 
+	- and the values at the nodes (could be different from the vertices).
+	
+	For ex: 
+	1. on a Beam element, Vx, at step 1, time .5, element id 1, interpolation type P0 (constant), vertices ids 1 and 2, one constant value 4.5
+	   VxEnum 1  .5  1 P0  1 2       4.5 NaN  NaN
+	2. on a Tria element, Vz, at step 2, time .8, element id 2, interpolation type P1 (linear), vertices ids 1 3 and 4, with values at 3 nodes 4.5, 3.2, 2.5
+	   VzEnum 2  .8  2 P1  1 3 4     4.5 3.2  2.5
+*/
+
+
+#ifndef _PATCH_H_
+#define  _PATCH_H_
+
+/*Headers:*/
+class Patch{
+
+	public:
+
+		int     numrows; //number of results held in Patch object
+		int     numcols; //number of columns
+		int     maxvertices; //maxvertices corresponds to largest amount of vertices on a given element, determined by the geometry.
+		int     maxnodes;    // maxnodes corresponds to the largest amout of nodes on a given element, determined by the interpolation type.
+		
+		double* values;  //result values
+
+		Patch();
+		Patch(int numrows, int maxvertices, int maxnodes);
+		~Patch();
+		void fillelementinfo(int row, int element_id, int* vertices_ids, int num_vertices);
+		void fillresultinfo(int row,int enum_type,int step, double time, int interpolation, double* nodal_values, int num_nodes);
+		void Gather(void);
+
+};
+#endif //ifndef _PATCH_H_
Index: /issm/trunk-jpl-damage/src/c/objects/Segment.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Segment.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Segment.cpp	(revision 11330)
@@ -0,0 +1,104 @@
+/*!\file Segment.c
+ * \brief: implementation of the Segment object
+ */
+
+/*Include files: {{{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 "./objects.h"
+#include "../Container/Container.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+/*}}}*/
+
+/*Segment constructors and destructors:*/
+/*FUNCTION Segment::Segment() default constructor {{{1*/
+Segment::Segment(){
+	this->eid=UNDEF;
+	this->x1=UNDEF;
+	this->y1=UNDEF;
+	this->x2=UNDEF;
+	this->y2=UNDEF;
+}
+/*}}}*/
+/*FUNCTION Segment::Segment(int eid, double x1,double y1,double x2, double y2){{{1*/
+Segment::Segment(int segment_eid, double segment_x1,double segment_y1,double segment_x2, double segment_y2){
+
+	this->eid=segment_eid;
+	this->x1=segment_x1;
+	this->y1=segment_y1;
+	this->x2=segment_x2;
+	this->y2=segment_y2;
+
+}
+/*}}}*/
+/*FUNCTION Segment::~Segment(){{{1*/
+Segment::~Segment(){
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Segment::Echo{{{1*/
+void Segment::Echo(void){
+
+	printf("Segment:\n");
+	printf("   eid: %i\n",eid);
+	printf("   node 1: %g|%g\n",this->x1,this->y1);
+	printf("   node 2: %g|%g\n",this->x2,this->y2);
+
+}
+/*}}}*/
+/*FUNCTION Segment::DeepEcho{{{1*/
+void Segment::DeepEcho(void){
+	this->Echo();
+}
+/*}}}*/
+/*FUNCTION Segment::Id{{{1*/
+int    Segment::Id(void){ return eid; }
+/*}}}*/
+/*FUNCTION Segment::MyRank{{{1*/
+int    Segment::MyRank(void){ 
+	extern int my_rank;
+
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION Segment::Marshall{{{1*/
+void  Segment::Marshall(char** pmarshalled_dataset){
+
+	_error_(" not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Segment::MarshallSize{{{1*/
+int   Segment::MarshallSize(){
+	_error_(" not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Segment::Demarshall{{{1*/
+void  Segment::Demarshall(char** pmarshalled_dataset){
+	_error_(" not supported yet!");
+}
+/*}}}*/
+#endif
+/*FUNCTION Segment::ObjectEnum{{{1*/
+int Segment::ObjectEnum(void){
+
+	return SegmentEnum;
+
+}
+/*}}}*/
+/*FUNCTION Segment::copy {{{1*/
+Object* Segment::copy() {
+	return new Segment(this->eid,this->x1,this->y1,this->x2,this->y2);
+
+}
+
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Segment.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Segment.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Segment.h	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file Segment.h
+ * \brief: header file for node object
+ */
+
+#ifndef _SEGMENT_H_
+#define _SEGMENT_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Object.h"
+/*}}}*/
+
+class Segment: public Object{
+
+	public:
+		int eid;
+		double x1;
+		double y1;
+		double x2;
+		double y2;
+
+		/*Segment constructors, destructors {{{1*/
+		Segment();
+		Segment(int eid,double x1,double y1, double x2, double y2);
+		~Segment();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+};
+
+#endif  /* _SEGMENT_H_ */
Index: /issm/trunk-jpl-damage/src/c/objects/Update.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Update.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Update.h	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file: Update.h: abstract class used by some objects to update their properties
+ * \brief prototypes for Update.h
+ */ 
+
+#ifndef _UPDATE_H_
+#define  _UPDATE_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "../shared/shared.h"
+/*}}}*/
+
+class Update{
+
+	public:
+
+		virtual void  InputUpdateFromVector(double* vector, int name, int type)=0;
+		virtual void  InputUpdateFromVector(int* vector, int name, int type)=0;
+		virtual void  InputUpdateFromVector(bool* vector, int name, int type)=0; 
+		#ifdef _HAVE_DAKOTA_
+		virtual void  InputUpdateFromMatrixDakota(double* matrix, int rows, int ncols, int name, int type)=0;
+		virtual void  InputUpdateFromVectorDakota(double* vector, int name, int type)=0;
+		virtual void  InputUpdateFromVectorDakota(int* vector, int name, int type)=0;
+		virtual void  InputUpdateFromVectorDakota(bool* vector, int name, int type)=0;
+		#endif
+		virtual void  InputUpdateFromConstant(double constant, int name)=0;
+		virtual void  InputUpdateFromConstant(int constant, int name)=0;
+		virtual void  InputUpdateFromConstant(bool constant, int name)=0;
+		virtual void  InputUpdateFromSolution(double* solution)=0;
+		virtual void  InputUpdateFromIoModel(int index, IoModel* iomodel)=0;
+
+};
+
+#endif //ifndef _UPDATE_H_
+
Index: /issm/trunk-jpl-damage/src/c/objects/Vertex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Vertex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Vertex.cpp	(revision 11330)
@@ -0,0 +1,292 @@
+/*!\file Vertex.c
+ * \brief: implementation of the Vertex object
+ */
+
+/*Include files: {{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <string.h>
+#include "./objects.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+/*}}}*/
+
+/*Vertex constructors and destructor:*/
+/*FUNCTION Vertex::Vertex() {{{1*/
+Vertex::Vertex(){
+	return;
+}
+/*}}}*/
+/*FUNCTION Vertex::Vertex(int vertex_id, double vertex_x, double vertex_y, double vertex_z, double vertex_sigma){{{1*/
+Vertex::Vertex(int vertex_id, int vertex_sid,double vertex_x, double vertex_y, double vertex_z, double vertex_sigma,int vertex_connectivity){
+	this->Init(vertex_id, vertex_sid,vertex_x, vertex_y, vertex_z, vertex_sigma,vertex_connectivity);
+}
+/*}}}*/
+/*FUNCTION Vertex::Vertex(int vertex_id, int vertex_sid,int i, IoModel* iomodel) {{{1*/
+Vertex::Vertex(int vertex_id, int vertex_sid,int i, IoModel* iomodel){
+
+	_assert_(iomodel->Data(MeshXEnum) && iomodel->Data(MeshYEnum) && iomodel->Data(MeshZEnum));
+	_assert_(iomodel->Data(BedEnum) && iomodel->Data(ThicknessEnum) && iomodel->numbernodetoelementconnectivity);
+
+	this->Init(vertex_id, vertex_sid, iomodel->Data(MeshXEnum)[i],iomodel->Data(MeshYEnum)[i],iomodel->Data(MeshZEnum)[i],(iomodel->Data(MeshZEnum)[i]-iomodel->Data(BedEnum)[i])/(iomodel->Data(ThicknessEnum)[i]),iomodel->numbernodetoelementconnectivity[i]);
+
+}
+/*}}}*/
+/*FUNCTION Vertex::~Vertex() {{{1*/
+Vertex::~Vertex(){
+	return;
+}
+/*}}}*/
+/*FUNCTION Vertex::Init{{{1*/
+void Vertex::Init(int vertex_id, int vertex_sid,double vertex_x, double vertex_y, double vertex_z, double vertex_sigma,int vertex_connectivity){
+
+	/*all the initialization has been done by the initializer, just fill in the id: */
+	this->id=vertex_id;
+	this->sid=vertex_sid;
+	this->x=vertex_x;
+	this->y=vertex_y;
+	this->z=vertex_z;
+	this->sigma=vertex_sigma;
+	this->connectivity=vertex_connectivity;
+	this->dof=UNDEF;
+
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Vertex::Echo{{{1*/
+void Vertex::Echo(void){
+
+	printf("Vertex:\n");
+	printf("   id: %i\n",id);
+	printf("   sid: %i\n",sid);
+	printf("   x: %g\n",x);
+	printf("   y: %g\n",y);
+	printf("   z: %g\n",z);
+	printf("   sigma: %g\n",sigma);
+	printf("   connectivity: %i\n",connectivity);
+	printf("   dof: %i\n",dof);
+	printf("   clone: %i\n",clone);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Vertex::DeepEcho{{{1*/
+void Vertex::DeepEcho(void){
+	this->Echo();
+}
+/*}}}*/
+/*FUNCTION Vertex::Id{{{1*/
+int    Vertex::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Vertex::MyRank {{{1*/
+int    Vertex::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+#ifdef _SERIAL_
+/*FUNCTION Vertex::Marshall {{{1*/
+void  Vertex::Marshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   enum_type=0;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*get enum type of Vertex: */
+	enum_type=VertexEnum;
+
+	/*marshall enum: */
+	memcpy(marshalled_dataset,&enum_type,sizeof(enum_type));marshalled_dataset+=sizeof(enum_type);
+
+	/*marshall Vertex data: */
+	memcpy(marshalled_dataset,&id,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(marshalled_dataset,&sid,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(marshalled_dataset,&x,sizeof(x));marshalled_dataset+=sizeof(x);
+	memcpy(marshalled_dataset,&y,sizeof(y));marshalled_dataset+=sizeof(y);
+	memcpy(marshalled_dataset,&z,sizeof(z));marshalled_dataset+=sizeof(z);
+	memcpy(marshalled_dataset,&sigma,sizeof(sigma));marshalled_dataset+=sizeof(sigma);
+	memcpy(marshalled_dataset,&connectivity,sizeof(connectivity));marshalled_dataset+=sizeof(connectivity);
+	memcpy(marshalled_dataset,&dof,sizeof(dof));marshalled_dataset+=sizeof(dof);
+	memcpy(marshalled_dataset,&clone,sizeof(clone));marshalled_dataset+=sizeof(clone);
+
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+/*FUNCTION Vertex::MarshallSize {{{1*/
+int   Vertex::MarshallSize(){
+	
+	return sizeof(id)+
+		sizeof(sid)+
+		sizeof(x)+
+		sizeof(y)+
+		sizeof(z)+
+		sizeof(sigma)+
+		sizeof(connectivity)+
+		sizeof(dof)+
+		sizeof(clone)+
+		+sizeof(int); //sizeof(int) for enum type
+}
+/*}}}*/
+/*FUNCTION Vertex::Demarshall {{{1*/
+void  Vertex::Demarshall(char** pmarshalled_dataset){
+
+	char* marshalled_dataset=NULL;
+	int   i;
+
+	/*recover marshalled_dataset: */
+	marshalled_dataset=*pmarshalled_dataset;
+
+	/*this time, no need to get enum type, the pointer directly points to the beginning of the 
+	 *object data (thanks to DataSet::Demarshall):*/
+
+	memcpy(&id,marshalled_dataset,sizeof(id));marshalled_dataset+=sizeof(id);
+	memcpy(&sid,marshalled_dataset,sizeof(sid));marshalled_dataset+=sizeof(sid);
+	memcpy(&x,marshalled_dataset,sizeof(x));marshalled_dataset+=sizeof(x);
+	memcpy(&y,marshalled_dataset,sizeof(y));marshalled_dataset+=sizeof(y);
+	memcpy(&z,marshalled_dataset,sizeof(z));marshalled_dataset+=sizeof(z);
+	memcpy(&sigma,marshalled_dataset,sizeof(sigma));marshalled_dataset+=sizeof(sigma);
+	memcpy(&connectivity,marshalled_dataset,sizeof(connectivity));marshalled_dataset+=sizeof(connectivity);
+	memcpy(&dof,marshalled_dataset,sizeof(dof));marshalled_dataset+=sizeof(dof);
+	memcpy(&clone,marshalled_dataset,sizeof(clone));marshalled_dataset+=sizeof(clone);
+
+	/*return: */
+	*pmarshalled_dataset=marshalled_dataset;
+	return;
+}
+/*}}}*/
+#endif
+/*FUNCTION Vertex::ObjectEnum{{{1*/
+int Vertex::ObjectEnum(void){
+
+	return VertexEnum;
+
+}
+/*}}}*/
+/*FUNCTION Vertex::copy {{{1*/
+Object* Vertex::copy() {
+
+	return new Vertex(*this); 
+
+}
+/*}}}*/
+
+/* DofObject routines: */
+/*FUNCTION Vertex::DistributeDofs{{{1*/
+void  Vertex::DistributeDofs(int* pdofcount){
+
+	int i;
+	extern int my_rank;
+	int dofcount;
+
+	dofcount=*pdofcount;
+	
+	if(this->clone){
+		/*This vertex is a clone! Don't distribute dofs, it will get them from another cpu!*/
+		return;
+	}
+
+	/*This vertex should distribute his dof, go ahead: */
+	this->dof=dofcount;
+	dofcount++;
+
+	/*Assign output pointers: */
+	*pdofcount=dofcount;
+
+}
+/*}}}*/
+/*FUNCTION Vertex::OffsetDofs{{{1*/
+void  Vertex::OffsetDofs(int dofcount){
+	
+	int i;
+	extern int my_rank;
+	
+	if(this->clone){
+		/*This vertex is a clone, don't offset the dofs!: */
+		return;
+	}
+
+	/*This vertex should offset his dof, go ahead: */
+	this->dof+=dofcount;
+}
+/*}}}*/
+/*FUNCTION Vertex::ShowTrueDofs{{{1*/
+void  Vertex::ShowTrueDofs(int* truedofs){
+
+	int j;
+	extern int my_rank;
+	
+	/*Are we a clone? : */
+	if(this->clone)return;
+
+	/*Ok, we are not a clone, just plug our dof into truedofs: */
+	truedofs[this->id-1]=this->dof;
+
+}
+/*}}}*/
+/*FUNCTION Vertex::UpdateCloneDofs{{{1*/
+void  Vertex::UpdateCloneDofs(int* alltruedofs){
+
+	int j;
+	extern int my_rank;
+	
+	/*If we are not a clone, don't update, we already have dofs!: */
+	if(this->clone==0)return;
+
+	/*Ok, we are a clone node, but we did not create the dof for this vertex 
+	 * Therefore, our dof is garbage right now. Go pick it up in the alltruedofs: */
+	this->dof=alltruedofs[id-1];
+}
+/*}}}*/
+/*FUNCTION Vertex::SetClone {{{1*/
+void  Vertex::SetClone(int* minranks){
+
+	extern int my_rank;
+
+	if (minranks[id-1]==my_rank){
+		this->clone=0;
+	}
+	else{
+		/*!there is a cpu with lower rank that has the same vertex, 
+		therefore, I am a clone*/
+		this->clone=1; 	
+	}
+
+}
+/*}}}*/
+
+/*Vertex management: */
+/*FUNCTION Vertex::Connectivity{{{1*/
+int    Vertex::Connectivity(void){return connectivity;}
+/*}}}*/
+/*FUNCTION Vertex::Sid{{{1*/
+int    Vertex::Sid(void){ return sid; }
+/*}}}*/
+/*FUNCTION Vertex::UpdateVertexPosition {{{1*/
+void  Vertex::UpdatePosition(Vec vz,Parameters* parameters,double* thickness,double* bed){
+
+	double oldz,newz;
+	double dt,velz;
+
+	/*Get time stepping*/
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+
+	/*sigma remains constant. z=bed+sigma*thickness*/
+	oldz = this->z;
+	newz = bed[this->dof]+sigma*thickness[this->dof];
+	velz = (newz-oldz)/dt;
+	this->z = newz;
+
+	/*put vz in vector*/
+	VecSetValue(vz,this->dof,velz,INSERT_VALUES);
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/objects/Vertex.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/Vertex.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/Vertex.h	(revision 11330)
@@ -0,0 +1,68 @@
+/*! \file Vertex.h 
+ *  \brief: header file for vertex object
+ */
+
+#ifndef _VERTEX_H_
+#define _VERTEX_H_
+
+/*Headers:*/
+/*{{{1*/
+#include "./Object.h"
+class IoModel;
+#include "../shared/Exceptions/exceptions.h"
+#include "../toolkits/toolkits.h"
+#include "../include/include.h"
+
+/*}}}*/
+
+
+class Vertex: public Object{
+
+	public: 
+
+		int    id;
+		int    sid;            //sid for "serial" id, ie the rank of this vertex in the vertices dataset, if the dataset was serial on 1 cpu.
+		double x;
+		double y;
+		double z;
+		double sigma;          //sigma coordinate: (z-bed)/thickness
+		int    connectivity;   //number of vertices connected to this vertex
+
+		/*dof management: */
+		int    clone;
+		int    dof; //dof to recover values in a vertex indexed vector
+
+		/*Vertex constructors, destructors {{{1*/
+		Vertex();
+		Vertex(int id, int sid,double x, double y, double z, double sigma, int connectivity); 
+		void Init(int id, int sid, double x, double y, double z, double sigma,int connectivity);
+		Vertex(int id, int sid, int i, IoModel* iomodel);
+		~Vertex();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{1 */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		#ifdef _SERIAL_
+		void  Marshall(char** pmarshalled_dataset);
+		int   MarshallSize();
+		void  Demarshall(char** pmarshalled_dataset);
+		#endif
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*DofObject routines {{{1*/
+		void  DistributeDofs(int* pdofcount);
+		void  OffsetDofs(int dofcount);
+		void  ShowTrueDofs(int* borderdofs);
+		void  UpdateCloneDofs(int* allborderdofs);
+		void  SetClone(int* minranks);
+		/*}}}*/
+		/*Vertex management: {{{1*/
+		int   Sid(void); 
+		int   Connectivity(void); 
+		void  UpdatePosition(Vec vz,Parameters* parameters,double* thickness,double* bed);
+		/*}}}*/
+};
+#endif  /* _VERTEX_H */
Index: /issm/trunk-jpl-damage/src/c/objects/objects.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/objects/objects.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/objects/objects.h	(revision 11330)
@@ -0,0 +1,172 @@
+/* \file objects.h
+ * \brief: prototype header for all objects.
+ */
+
+#ifndef ALL_OBJECTS_H_
+#define ALL_OBJECTS_H_
+
+/*Abstract classes: */
+#include "./Object.h"
+
+/*Objects: */
+#include "./Hook.h"
+#include "./DofIndexing.h"
+#include "./Vertex.h"
+#include "./Node.h"
+#include "./Segment.h"
+#include "./IoModel.h"
+#include "./Patch.h"
+#include "./Update.h"
+
+/*Constraints: */
+#include "./Constraints/Constraint.h"
+#include "./Constraints/SpcStatic.h"
+#include "./Constraints/SpcTransient.h"
+#include "./Constraints/SpcDynamic.h"
+
+/*Gauss*/
+#include "./Gauss/GaussTria.h"
+#include "./Gauss/GaussPenta.h"
+
+/*Loads: */
+#include "./Loads/Friction.h"
+#include "./Loads/Icefront.h"
+#include "./Loads/Numericalflux.h"
+#include "./Loads/Riftfront.h"
+#include "./Loads/Penpair.h"
+#include "./Loads/Pengrid.h"
+
+/*Elements: */
+#include "./Elements/Element.h"
+#include "./Elements/Penta.h"
+#include "./Elements/PentaHook.h"
+#include "./Elements/PentaRef.h"
+#include "./Elements/Tria.h"
+#include "./Elements/TriaHook.h"
+#include "./Elements/TriaRef.h"
+
+/*KML parsing objects: */
+#include "./KML/KML_Attribute.h"
+#include "./KML/KML_Comment.h"
+#include "./KML/KML_ColorStyle.h"
+#include "./KML/KML_Container.h"
+#include "./KML/KML_Document.h"
+#include "./KML/KML_Feature.h"
+#include "./KML/KML_File.h"
+#include "./KML/KML_Folder.h"
+#include "./KML/KML_Geometry.h"
+#include "./KML/KML_GroundOverlay.h"
+#include "./KML/KML_Icon.h"
+#include "./KML/KML_LatLonBox.h"
+#include "./KML/KML_LinearRing.h"
+#include "./KML/KML_LineString.h"
+#include "./KML/KML_LineStyle.h"
+#include "./KML/KML_MultiGeometry.h"
+#include "./KML/KML_Object.h"
+#include "./KML/KML_Overlay.h"
+#include "./KML/KML_Point.h"
+#include "./KML/KML_Placemark.h"
+#include "./KML/KML_Polygon.h"
+#include "./KML/KML_PolyStyle.h"
+#include "./KML/KML_Style.h"
+#include "./KML/KML_StyleSelector.h"
+#include "./KML/KML_SubStyle.h"
+#include "./KML/KML_Unknown.h"
+#include "./KML/KMLFileReadUtils.h"
+
+/*Option parsing objects: */
+#include "./Options/Option.h"
+#include "./Options/OptionDouble.h"
+#include "./Options/OptionLogical.h"
+#include "./Options/OptionChar.h"
+#include "./Options/OptionStruct.h"
+#include "./Options/OptionCell.h"
+#include "./Options/OptionUtilities.h"
+
+/*Inputs: */
+#include "./Inputs/Input.h"
+#include "./Inputs/BoolInput.h"
+#include "./Inputs/DoubleInput.h"
+#include "./Inputs/IntInput.h"
+#include "./Inputs/PentaP1Input.h"
+#include "./Inputs/TriaP1Input.h"
+#include "./Inputs/ControlInput.h"
+#include "./Inputs/DatasetInput.h"
+#include "./Inputs/TransientInput.h"
+
+/*ElementResults: */
+#include "./ElementResults/ElementResult.h"
+#include "./ElementResults/DoubleElementResult.h"
+#include "./ElementResults/TriaP1ElementResult.h"
+#include "./ElementResults/PentaP1ElementResult.h" 
+#include "./ElementResults/BoolElementResult.h"
+
+/*ExternalResults: */
+#include "./ExternalResults/ExternalResult.h"
+#include "./ExternalResults/BoolExternalResult.h"
+#include "./ExternalResults/DoubleExternalResult.h"
+#include "./ExternalResults/DoubleVecExternalResult.h"
+#include "./ExternalResults/DoubleMatExternalResult.h"
+#include "./ExternalResults/IntExternalResult.h"
+#include "./ExternalResults/PetscVecExternalResult.h"
+#include "./ExternalResults/StringExternalResult.h"
+
+/*Materials: */
+#include "./Materials/Material.h"
+#include "./Materials/Matice.h"
+#include "./Materials/Matpar.h"
+
+/*Numerics:*/
+#include "./Numerics/ElementMatrix.h"
+#include "./Numerics/ElementVector.h"
+
+/*Params: */
+#include "./Params/BoolParam.h"
+#include "./Params/DoubleMatParam.h"
+#include "./Params/DoubleTransientMatParam.h"
+#include "./Params/DoubleMatArrayParam.h"
+#include "./Params/DoubleParam.h"
+#include "./Params/DoubleVecParam.h"
+#include "./Params/IntParam.h"
+#include "./Params/IntVecParam.h"
+#include "./Params/IntMatParam.h"
+#include "./Params/FileParam.h"
+#include "./Params/Param.h"
+#include "./Params/PetscMatParam.h"
+#include "./Params/PetscVecParam.h"
+#include "./Params/StringArrayParam.h"
+#include "./Params/StringParam.h"
+
+/*C objects: */
+#include "./Contour.h"
+#include "./FemModel.h"
+#include "./OptArgs.h"
+#include "./OptPars.h"
+
+/*Bamg: */
+#include "./Bamg/BamgOpts.h"
+#include "./Bamg/BamgGeom.h"
+#include "./Bamg/BamgMesh.h"
+#include "./Bamg/Metric.h"
+#include "./Bamg/DoubleAndInt.h"
+#include "./Bamg/Direction.h"
+#include "./Bamg/BamgVertex.h"
+#include "./Bamg/AdjacentTriangle.h"
+#include "./Bamg/Edge.h"
+#include "./Bamg/GeomVertex.h"
+#include "./Bamg/GeomEdge.h"
+#include "./Bamg/Curve.h"
+#include "./Bamg/Triangle.h"
+#include "./Bamg/ListofIntersectionTriangles.h"
+#include "./Bamg/GeomSubDomain.h"
+#include "./Bamg/SubDomain.h"
+#include "./Bamg/VertexOnGeom.h"
+#include "./Bamg/VertexOnVertex.h"
+#include "./Bamg/VertexOnEdge.h"
+#include "./Bamg/CrackedEdge.h"
+#include "./Bamg/Mesh.h"
+#include "./Bamg/Geometry.h"
+#include "./Bamg/QuadTree.h"
+#include "./Bamg/SetOfE4.h"
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Alloc/alloc.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Alloc/alloc.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Alloc/alloc.cpp	(revision 11330)
@@ -0,0 +1,98 @@
+/* \file alloc.h
+ * \brief: wrappers to "C" or "Matlab" memory allocators.
+ * These wrappers try to insulate ISSM from any library dependency.
+ * Ie: if we are running in matlab, matlab has to handle all memory allocations, 
+ * otherwise, we get big segfaults. If running in stand alone mode (pure C or C++ 
+ * application), we rely on the "C" library implementation of dynamic memory allocation.
+ * Why don't we use the "new" and "delete" c++ implementations? Because so far there 
+ * are no matlab wrappers to these, which implies having tons of segfaults when 
+ * running a mex module.
+ * Still, we try to throw memory allocation exceptions a la "C++" style when 
+ * the allocation routines described here do not work.
+ */
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile without HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#if defined(_SERIAL_) && defined(_HAVE_MATLAB_)
+#include "mex.h"
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include  "./alloc.h"
+#include "../Exceptions/exceptions.h"
+#include "../../include/include.h"
+
+void* xmalloc(int size){
+
+	void* memptr=NULL;
+
+	if(!size)_error_(" attempting to 0 size allocation!");
+
+	#if defined(_HAVE_MATLAB_) && defined(_SERIAL_)
+	/* Use the matlab api to do the allocation: */
+	memptr=mxMalloc(size);
+	#else
+	/* Use the c library to do the allocation: */
+	memptr=malloc(size);
+	#endif
+	if(!memptr) _error_("memory allocation failed!");
+
+	return memptr;
+}
+
+void* xcalloc(int n,int size){
+
+	void* memptr=NULL;
+	
+	if(!size)_error_("attempting to 0 size allocation!");
+
+	#if defined(_HAVE_MATLAB_) && defined(_SERIAL_)
+	/* Use the matlab api to do the allocation: */
+	memptr=mxCalloc(n,size);
+	#else
+	/* Use the c library to do the allocation: */
+	memptr=calloc(n,size);
+	#endif
+	if(!memptr) _error_("memory allocation failed!");
+
+	return memptr;
+}
+
+void xfree( void* *pv){
+
+	if (pv && *pv) {
+
+		#ifdef _SERIAL_
+		mxFree(*pv);
+		#else
+		free(*pv);
+		#endif
+
+		*pv=NULL;
+	}
+}
+
+void* xrealloc ( void* pv, int size){
+	
+	register void* value=NULL;
+	
+	if(!size)_error_("attempting to realloc to zero");
+
+	#ifndef MATLAB
+	value = (void*)realloc(pv,size);
+	#else
+	value = (void*)mxRealloc(pv,size);
+	#endif
+
+	if (value == NULL) {
+		_error_("virtual memory exhausted");
+	}
+	return value;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Alloc/alloc.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Alloc/alloc.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Alloc/alloc.h	(revision 11330)
@@ -0,0 +1,13 @@
+/* \file alloc.h
+ * \brief: header file for memory allocations.
+ */
+
+#ifndef _ALLOC_H_
+#define _ALLOC_H_
+
+void* xmalloc(int size);
+void* xcalloc(int n,int size);
+void  xfree(void** pvptr);
+void* xrealloc ( void* pv, int size);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Bamg/Abs.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Bamg/Abs.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Bamg/Abs.h	(revision 11330)
@@ -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/trunk-jpl-damage/src/c/shared/Bamg/BigPrimeNumber.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Bamg/BigPrimeNumber.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Bamg/BigPrimeNumber.cpp	(revision 11330)
@@ -0,0 +1,33 @@
+#include "./BigPrimeNumber.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, rest of the 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/trunk-jpl-damage/src/c/shared/Bamg/BigPrimeNumber.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Bamg/BigPrimeNumber.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Bamg/BigPrimeNumber.h	(revision 11330)
@@ -0,0 +1,12 @@
+#ifndef _BIGPRIMENUMBER_H_
+#define _BIGPRIMENUMBER_H_
+
+#include "./Abs.h"
+#include "./extrema.h"
+
+namespace bamg {
+
+	long BigPrimeNumber(long n);
+
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Bamg/BinaryRand.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Bamg/BinaryRand.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Bamg/BinaryRand.h	(revision 11330)
@@ -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/trunk-jpl-damage/src/c/shared/Bamg/Exchange.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Bamg/Exchange.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Bamg/Exchange.h	(revision 11330)
@@ -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/trunk-jpl-damage/src/c/shared/Bamg/HeapSort.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Bamg/HeapSort.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Bamg/HeapSort.h	(revision 11330)
@@ -0,0 +1,67 @@
+#ifndef _HEAPSORT_H_
+#define _HEAPSORT_H_
+
+/*Sort a list of size n*/
+template<class T> inline void  HeapSort(T *c,long n){
+	int l,j,r,i;
+	T   crit;
+	c--;                    //the array must starts at 1 and not 0 
+	if(n<=1) return;        //return if size <=1
+	l=n/2+1;                //initialize l and r
+	r=n;
+	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 -> stock this large value in i(<j)
+			else{c[i]=crit;break;}            //c[j]  < crit -> stock crit in i (<j)
+		}
+	}
+}
+
+/*Sort a list of size n and returns ordering*/
+template<class T> inline void  HeapSort(int** porder,T* c,int n){
+	int  l,j,r,i;
+	T    crit;
+	int  pos;
+	int* order = new int[n];
+	for(i=0;i<n;i++) order[i]=i+1;
+	c--;                    //the array must starts at 1 and not 0 
+	order--;
+	if(n<=1) return;        //return if size <=1
+	l=n/2+1;                //initialize l and r
+	r=n;
+	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;}
+		}
+	}
+}
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Bamg/OppositeAngle.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Bamg/OppositeAngle.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Bamg/OppositeAngle.h	(revision 11330)
@@ -0,0 +1,12 @@
+#ifndef _OPPOSITEANGLE_H_
+#define _OPPOSITEANGLE_H_
+
+#include "../../objects/Bamg/include.h"
+
+/*Return the opposite angle modulo 2 Pi*/
+namespace bamg {
+	inline float  OppositeAngle(float  a){return a<0 ? fPi+a:a-fPi;}
+	inline double OppositeAngle(double a){return a<0 ?  Pi+a:a- Pi;}
+}
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Bamg/det.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Bamg/det.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Bamg/det.h	(revision 11330)
@@ -0,0 +1,15 @@
+#ifndef _BAMGDET_H_
+#define _BAMGDET_H_
+
+#include "../../objects/Bamg/include.h"
+
+namespace bamg {
+
+	Icoor2 inline det(const I2 &a,const I2 & b,const I2 &c){
+		Icoor2 bax = b.x - a.x ,bay = b.y - a.y; 
+		Icoor2 cax = c.x - a.x ,cay = c.y - a.y; 
+		return  bax*cay - bay*cax;
+	}
+
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Bamg/extrema.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Bamg/extrema.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Bamg/extrema.h	(revision 11330)
@@ -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/trunk-jpl-damage/src/c/shared/Bamg/shared.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Bamg/shared.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Bamg/shared.h	(revision 11330)
@@ -0,0 +1,18 @@
+/* \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 "det.h"
+#include "Exchange.h"
+#include "extrema.h"
+#include "HeapSort.h"
+#include "OppositeAngle.h"
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Dofs/dofs.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Dofs/dofs.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Dofs/dofs.h	(revision 11330)
@@ -0,0 +1,12 @@
+/*!\file: dofs.h
+ * \brief prototypes for dofs.h
+ */ 
+
+#ifndef _DOFS_H_
+#define  _DOFS_H_
+
+double* dofsetgen(int numdofs,int* doflist,int dofspernode,int totaldofs);
+
+
+#endif //ifndef _DOFS_H_
+
Index: /issm/trunk-jpl-damage/src/c/shared/Dofs/dofsetgen.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Dofs/dofsetgen.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Dofs/dofsetgen.cpp	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file:  dofsetgen.cpp
+ * \brief  create list of dofs.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../Alloc/alloc.h"
+#include "../../include/include.h"
+#include <stdio.h>
+
+double* dofsetgen(int numdofs,int* doflist,int dofspernode,int totaldofs){
+
+	int i,j;
+	int count=0;
+
+	/*output: */
+	double* outdoflist=NULL;
+
+	/*number of nodes :*/
+	int numberofnodes;
+
+	/*allocate: */
+	numberofnodes=(int)totaldofs/dofspernode;
+	outdoflist=(double*)xmalloc(numberofnodes*numdofs*sizeof(double));
+
+	count=0;
+	for(i=0;i<numberofnodes;i++){
+		for(j=0;j<numdofs;j++){
+			outdoflist[numdofs*i+j]=count+doflist[j] + 1 ;//-1 because dofs vector comes from Matlab, where indices start at 1.
+		}
+		count+=dofspernode;
+	}
+
+	/*Assign output pointers:*/
+	return outdoflist;
+
+}
+
Index: /issm/trunk-jpl-damage/src/c/shared/Elements/Arrhenius.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Elements/Arrhenius.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Elements/Arrhenius.cpp	(revision 11330)
@@ -0,0 +1,50 @@
+/* \file Arrhenius.cpp
+ * \brief figure out B of ice for a certain temperature
+ */
+
+#include "./elements.h"
+#include <math.h>
+
+double Arrhenius(double temperature,double depth,double 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)*/
+	double beta=8.66*pow(10.,-4.);
+	double R=8.314;
+
+	/*Intermediaries*/
+	double A,B,Tstar;
+
+	/*convert temperature to absolute temperature*/
+	_assert_(depth);
+	Tstar=temperature-beta*depth;
+	_assert_(Tstar);
+
+	/*Get A*/
+	if(Tstar<263.15){
+		A=3.61*pow(10.,-13.) * exp(  -6.*pow(10.,4.)/(R*Tstar));
+	}
+	else{
+		A=1.73*pow(10.,  3.) * exp(-13.9*pow(10.,4.)/(R*Tstar));
+	}
+
+	/*Convert to B*/
+	B=pow(A,-1./n);
+
+	return B;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Elements/CoordinateSystemTransform.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Elements/CoordinateSystemTransform.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Elements/CoordinateSystemTransform.cpp	(revision 11330)
@@ -0,0 +1,75 @@
+/*!\file:  GetGlobalDofList.cpp
+ * \brief create transform matrix for different coordinate systems
+ */ 
+#include "./elements.h"
+#include <math.h>
+
+void CoordinateSystemTransform(double** ptransform,Node** nodes,int numnodes,int* cs_array){
+
+	int     i,counter;
+	int     numdofs           = 0;
+	double  norm;
+	double *transform         = NULL;
+	double *values            = NULL;
+	double  coord_system[3][3];
+
+	/*Some checks in debugging mode*/
+	_assert_(numnodes && nodes);
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case XYEnum:   numdofs+=2; break;
+			case XYZPEnum: numdofs+=4; break;
+			default: _error_("Coordinate system %s not supported yet",EnumToStringx(cs_array[i]));
+		}
+	}
+
+	/*Allocate and initialize transform matrix*/
+	transform=(double*)xmalloc(numdofs*numdofs*sizeof(double));
+	for(i=0;i<numdofs*numdofs;i++) transform[i]=0.0;
+
+	/*Create transform matrix for all nodes (x,y for 2d and x,y,z for 3d). It is a block matrix
+	 *for 3 nodes:
+
+	 *     | T1 0  0 |
+	 * Q = | 0  T2 0 |
+	 *     | 0  0  T3|
+	 *
+	 * Where T1 is the transform matrix for node 1. It is a simple copy of the coordinate system
+	 * associated to this node*/
+	counter=0;
+	for(i=0;i<numnodes;i++){
+		nodes[i]->GetCoordinateSystem(&coord_system[0][0]);
+		switch(cs_array[i]){
+			case XYEnum:
+				/*We remove the z component, we need to renormalize x and y: x=[x1 x2 0] y=[-x2 x1 0]*/
+				norm = sqrt( coord_system[0][0]*coord_system[0][0] + coord_system[1][0]*coord_system[1][0]); _assert_(norm>1.e-4);
+				transform[(numdofs)*(counter+0) + counter+0] =   coord_system[0][0]/norm;
+				transform[(numdofs)*(counter+0) + counter+1] = - coord_system[1][0]/norm;
+				transform[(numdofs)*(counter+1) + counter+0] =   coord_system[1][0]/norm;
+				transform[(numdofs)*(counter+1) + counter+1] =   coord_system[0][0]/norm;
+				counter+=2;
+				break;
+			case XYZPEnum:
+				/*Only the first 3 coordinates are changed (x,y,z), leave the others (P) unchanged*/
+				transform[(numdofs)*(counter+0) + counter+0] = coord_system[0][0];
+				transform[(numdofs)*(counter+0) + counter+1] = coord_system[0][1];
+				transform[(numdofs)*(counter+0) + counter+2] = coord_system[0][2];
+				transform[(numdofs)*(counter+1) + counter+0] = coord_system[1][0];
+				transform[(numdofs)*(counter+1) + counter+1] = coord_system[1][1];
+				transform[(numdofs)*(counter+1) + counter+2] = coord_system[1][2];
+				transform[(numdofs)*(counter+2) + counter+0] = coord_system[2][0];
+				transform[(numdofs)*(counter+2) + counter+1] = coord_system[2][1];
+				transform[(numdofs)*(counter+2) + counter+2] = coord_system[2][2];
+				transform[(numdofs)*(counter+3) + counter+3] = 1.0;
+				counter+=4;
+				break;
+			default:
+				_error_("Coordinate system %s not supported yet",EnumToStringx(cs_array[i]));
+		}
+	}
+
+	/*Assign output pointer*/
+	*ptransform=transform;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Elements/GetGlobalDofList.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Elements/GetGlobalDofList.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Elements/GetGlobalDofList.cpp	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file:  GetGlobalDofList.cpp
+ * \brief create new element matrix
+ */ 
+#include "./elements.h"
+
+int* GetGlobalDofList(Node** nodes,int numnodes,int setenum,int approximation){
+
+	int  i,numdof,count;
+	int* ndof_list=NULL;
+	int *doflist = NULL;
+
+
+	if(numnodes){
+
+		/*Allocate:*/
+		ndof_list=(int*)xmalloc(numnodes*sizeof(int));
+
+		/*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=(int*)xmalloc(numdof*sizeof(int));
+
+			/*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:*/
+	xfree((void**)&ndof_list);
+
+	return doflist;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Elements/GetLocalDofList.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Elements/GetLocalDofList.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Elements/GetLocalDofList.cpp	(revision 11330)
@@ -0,0 +1,62 @@
+/*!\file:  GetLocalDofList.cpp
+ * \brief create new element matrix
+ */ 
+#include "./elements.h"
+
+int* GetLocalDofList(Node** nodes,int numnodes,int setenum,int approximation){
+
+	int  i,j,count,numdof,numgdof;
+	int* ndof_list=NULL;
+	int* ngdof_list_cumulative=NULL;
+	int *doflist = NULL;
+
+	if(numnodes){
+		/*allocate: */
+		ndof_list=(int*)xmalloc(numnodes*sizeof(int));
+		ngdof_list_cumulative=(int*)xmalloc(numnodes*sizeof(int));
+
+
+		/*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=(int*)xmalloc(numdof*sizeof(int));
+
+			/*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:*/
+	xfree((void**)&ndof_list);
+	xfree((void**)&ngdof_list_cumulative);
+
+	/*CLean-up and return*/
+	return doflist;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Elements/GetNumberOfDofs.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Elements/GetNumberOfDofs.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Elements/GetNumberOfDofs.cpp	(revision 11330)
@@ -0,0 +1,16 @@
+/*!\file:  GetNumberOfDofs.cpp
+ * \brief create new element matrix
+ */ 
+#include "./elements.h"
+
+int GetNumberOfDofs(Node** nodes,int numnodes,int setenum,int approximation){
+
+	/*output: */
+	int numberofdofs=0;
+
+	for(int i=0;i<numnodes;i++){
+		numberofdofs+=nodes[i]->GetNumberOfDofs(approximation,setenum);
+	}
+
+	return numberofdofs;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Elements/GetVerticesCoordinates.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Elements/GetVerticesCoordinates.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Elements/GetVerticesCoordinates.cpp	(revision 11330)
@@ -0,0 +1,17 @@
+/*!\file:  GetVerticesCoordinates.cpp
+ * \brief get node coordinates
+ */ 
+
+#include "./elements.h"
+
+void GetVerticesCoordinates(double* xyz,  Node** nodes, int numvertices){
+
+	/*In debugging mode, check that nodes is not a NULL pointer*/
+	_assert_(nodes);
+
+	for(int i=0;i<numvertices;i++) {
+		xyz[i*3+0]=nodes[i]->GetX();
+		xyz[i*3+1]=nodes[i]->GetY();
+		xyz[i*3+2]=nodes[i]->GetZ();
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Elements/Paterson.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Elements/Paterson.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Elements/Paterson.cpp	(revision 11330)
@@ -0,0 +1,72 @@
+/* \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>
+
+double Paterson(double temperature){
+	
+	/*output: */
+	double B;
+	double T;
+
+	/*Switch to celsius from Kelvin: */
+	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 B 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');
+//	% B=fittedmodel(temperature);
+
+
+	if(T<=-45.0){
+		B=pow((double)10,(double)8)*(-0.000292866376675*pow(T+50,3)+ 0.011672640664130*pow(T+50,2)  -0.325004442485481*(T+50)+  6.524779401948101);
+	}
+	else if((T>=-45.0) && (T<=-40.0)){
+		B=pow((double)10,(double)8)*(-0.000292866376675*pow(T+45,3)+ 0.007279645014004*pow(T+45,2)  -0.230243014094813*(T+45)+  5.154964909039554);
+	}
+	else if((T>=-40.0) && (T<=-35.0)){
+		B=pow((double)10,(double)8)*(0.000072737147457*pow(T+40,3)+  0.002886649363879*pow(T+40,2)  -0.179411542205399*(T+40)+  4.149132666831214);
+	}
+	else if((T>=-35.0) && (T<=-30.0)){
+		B=pow((double)10,(double)8)*(-0.000086144770023*pow(T+35,3)+ 0.003977706575736*pow(T+35,2)  -0.145089762507325*(T+35)+  3.333333333333331);
+	}
+	else if((T>=-30.0) && (T<=-25.0)){
+		B=pow((double)10,(double)8)*(-0.000043984685769*pow(T+30,3)+ 0.002685535025386*pow(T+30,2)  -0.111773554501713*(T+30)+  2.696559088937191);
+	}
+	else if((T>=-25.0) && (T<=-20.0)){
+		B=pow((double)10,(double)8)*(-0.000029799523463*pow(T+25,3)+ 0.002025764738854*pow(T+25,2)  -0.088217055680511*(T+25)+  2.199331606342181);
+	}
+	else if((T>=-20.0) && (T<=-15.0)){
+		B=pow((double)10,(double)8)*(0.000136920904777*pow(T+20,3)+  0.001578771886910*pow(T+20,2)  -0.070194372551690*(T+20)+  1.805165505978111);
+	}
+	else if((T>=-15.0) && (T<=-10.0)){
+		B=pow((double)10,(double)8)*(-0.000899763781026*pow(T+15,3)+ 0.003632585458564*pow(T+15,2)  -0.044137585824322*(T+15)+  1.510778053489523);
+	}
+	else if((T>=-10.0) && (T<=-5.0)){
+		B=pow((double)10,(double)8)*(0.001676964325070*pow(T+10,3)-  0.009863871256831*pow(T+10,2)  -0.075294014815659*(T+10)+  1.268434288203714);
+	}
+	else if((T>=-5.0) && (T<=-2.0)){
+		B=pow((double)10,(double)8)*(-0.003748937622487*pow(T+5,3)+0.015290593619213*pow(T+5,2)  -0.048160403003748*(T+5)+  0.854987973338348);
+	}
+	else if(T>=-2.0){
+		B=pow((double)10,(double)8)*(-0.003748937622488*pow(T+2,3)-0.018449844983174*pow(T+2,2)  -0.057638157095631*(T+2)+  0.746900791092860);
+	}
+
+	/*B cannot be negative!*/
+	if(B<0) B=pow((double)10,(double)6);
+
+	return B;
+}
+
+
+
Index: /issm/trunk-jpl-damage/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp	(revision 11330)
@@ -0,0 +1,53 @@
+/*!\file:  TransformInvStiffnessMatrixCoord.cpp
+ * \brief transform stiffness matrix inverse coordinate system
+ */ 
+#include "./elements.h"
+
+void TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum){
+
+	int* cs_array=NULL;
+
+	/*All nodes have the same Coordinate System*/
+	cs_array=(int*)xmalloc(numnodes*sizeof(int));
+	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
+
+	/*Call core*/
+	TransformInvStiffnessMatrixCoord(Ke,nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xfree((void**)&cs_array);
+}
+
+void TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array){
+
+	int     i,j;
+	int     numdofs   = 0;
+	double *transform = NULL;
+	double *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case XYEnum:   numdofs+=2; break;
+			case XYZPEnum: numdofs+=4; break;
+			default: _error_("Coordinate system %s not supported yet",EnumToStringx(cs_array[i]));
+		}
+	}
+
+	/*Copy current stiffness matrix*/
+	values=(double*)xmalloc(Ke->nrows*Ke->ncols*sizeof(double));
+	for(i=0;i<Ke->nrows;i++) for(j=0;j<Ke->ncols;j++) values[i*Ke->ncols+j]=Ke->values[i*Ke->ncols+j];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes,numnodes,cs_array);
+
+	/*Transform matrix: R*Ke*R^T */
+	TripleMultiply(transform,numdofs,numdofs,0,
+				values,Ke->nrows,Ke->ncols,0,
+				transform,numdofs,numdofs,1,
+				&Ke->values[0],0);
+
+	/*Free Matrix*/
+	xfree((void**)&transform);
+	xfree((void**)&values);
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Elements/TransformLoadVectorCoord.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Elements/TransformLoadVectorCoord.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Elements/TransformLoadVectorCoord.cpp	(revision 11330)
@@ -0,0 +1,51 @@
+/*!\file:  TransformLoadVectorCoord.cpp
+ * \brief transform load vector coordinate system
+ */ 
+#include "./elements.h"
+
+void TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int cs_enum){
+	int* cs_array=NULL;
+
+	/*All nodes have the same Coordinate System*/
+	cs_array=(int*)xmalloc(numnodes*sizeof(int));
+	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
+
+	/*Call core*/
+	TransformLoadVectorCoord(pe,nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xfree((void**)&cs_array);
+}
+
+void TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int* cs_array){
+
+	int     i,j;
+	int     numdofs   = 0;
+	double *transform = NULL;
+	double *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case XYEnum:   numdofs+=2; break;
+			case XYZPEnum: numdofs+=4; break;
+			default: _error_("Coordinate system %s not supported yet",EnumToStringx(cs_array[i]));
+		}
+	}
+
+	/*Copy current load vector*/
+	values=(double*)xmalloc(pe->nrows*sizeof(double));
+	for(i=0;i<pe->nrows;i++) values[i]=pe->values[i];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes,numnodes,cs_array);
+
+	/*Transform matrix: R^T*pe */
+	MatrixMultiply(transform,numdofs,numdofs,1,
+				values,pe->nrows,1,0,
+				&pe->values[0],0);
+
+	/*Free Matrix*/
+	xfree((void**)&transform);
+	xfree((void**)&values);
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Elements/TransformSolutionCoord.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Elements/TransformSolutionCoord.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Elements/TransformSolutionCoord.cpp	(revision 11330)
@@ -0,0 +1,52 @@
+/*!\file:  TransformSolutionCoord.cpp
+ * \brief transform solution vector coordinate system
+ */ 
+#include "./elements.h"
+
+void TransformSolutionCoord(double* solution,Node** nodes,int numnodes,int cs_enum){
+
+	int* cs_array=NULL;
+
+	/*All nodes have the same Coordinate System*/
+	cs_array=(int*)xmalloc(numnodes*sizeof(int));
+	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
+
+	/*Call core*/
+	TransformSolutionCoord(solution,nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xfree((void**)&cs_array);
+}
+
+void TransformSolutionCoord(double* solution,Node** nodes,int numnodes,int* cs_array){
+
+	int     i,j;
+	int     numdofs   = 0;
+	double *transform = NULL;
+	double *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case XYEnum:   numdofs+=2; break;
+			case XYZPEnum: numdofs+=4; break;
+			default: _error_("Coordinate system %s not supported yet",EnumToStringx(cs_array[i]));
+		}
+	}
+
+	/*Copy current solution vector*/
+	values=(double*)xmalloc(numdofs*sizeof(double));
+	for(i=0;i<numdofs;i++) values[i]=solution[i];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes,numnodes,cs_array);
+
+	/*Transform matrix: R*U */
+	MatrixMultiply(transform,numdofs,numdofs,0,
+				values,numdofs,1,0,
+				&solution[0],0);
+
+	/*Free Matrix*/
+	xfree((void**)&transform);
+	xfree((void**)&values);
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp	(revision 11330)
@@ -0,0 +1,53 @@
+/*!\file:  TransformStiffnessMatrixCoord.cpp
+ * \brief transform stiffness matrix coordinate system
+ */ 
+#include "./elements.h"
+
+void TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum){
+
+	int* cs_array=NULL;
+
+	/*All nodes have the same Coordinate System*/
+	cs_array=(int*)xmalloc(numnodes*sizeof(int));
+	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
+
+	/*Call core*/
+	TransformStiffnessMatrixCoord(Ke,nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xfree((void**)&cs_array);
+}
+
+void TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array){
+
+	int     i,j;
+	int     numdofs   = 0;
+	double *transform = NULL;
+	double *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case XYEnum:   numdofs+=2; break;
+			case XYZPEnum: numdofs+=4; break;
+			default: _error_("Coordinate system %s not supported yet",EnumToStringx(cs_array[i]));
+		}
+	}
+
+	/*Copy current stiffness matrix*/
+	values=(double*)xmalloc(Ke->nrows*Ke->ncols*sizeof(double));
+	for(i=0;i<Ke->nrows;i++) for(j=0;j<Ke->ncols;j++) values[i*Ke->ncols+j]=Ke->values[i*Ke->ncols+j];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes,numnodes,cs_array);
+
+	/*Transform matrix: R^T*Ke*R */
+	TripleMultiply(transform,numdofs,numdofs,1,
+				values,Ke->nrows,Ke->ncols,0,
+				transform,numdofs,numdofs,0,
+				&Ke->values[0],0);
+
+	/*Free Matrix*/
+	xfree((void**)&transform);
+	xfree((void**)&values);
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Elements/elements.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Elements/elements.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Elements/elements.h	(revision 11330)
@@ -0,0 +1,50 @@
+/*!\file: elements.h
+ * \brief prototypes for elements.h
+ */ 
+
+#ifndef _SHARED_ELEMENTS_H_
+#define  _SHARED_ELEMENTS_H_
+
+#include "../../objects/objects.h"
+#include "../../Container/Container.h"
+class ElementMatrix;
+class ElementVector;
+
+double Paterson(double temperature);
+double Arrhenius(double temperature,double depth,double n);
+void   GetVerticesCoordinates(double* xyz,  Node** nodes, int numvertices);
+int    GetNumberOfDofs( Node** nodes,int numnodes,int setenum,int approximation_enum);
+int*   GetLocalDofList( Node** nodes,int numnodes,int setenum,int approximation_enum);
+int*   GetGlobalDofList(Node** nodes,int numnodes,int setenum,int approximation_enum);
+void   CoordinateSystemTransform(double** ptransform,Node** nodes,int numnodes,int* cs_array);
+#ifdef _HAVE_DIAGNOSTIC_
+void   TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
+void   TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array);
+void   TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
+void   TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array);
+void   TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int cs_enum);
+void   TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int* cs_array);
+void   TransformSolutionCoord(double* solution,Node** nodes,int numnodes,int cs_enum);
+void   TransformSolutionCoord(double* solution,Node** nodes,int numnodes,int* cs_array);
+#endif
+
+inline void printarray(double* array,int lines,int cols=1){
+	printf("\n");
+	for(int i=0;i<lines;i++){  
+		printf("   [ ");
+		for(int j=0;j<cols;j++) printf(" %12.7g ",array[i*cols+j]);
+		printf(" ]\n");
+	}  
+	printf("\n");
+}
+inline void printarray(int* array,int lines,int cols=1){
+	printf("\n");
+	for(int i=0;i<lines;i++){  
+		printf("   [ ");
+		for(int j=0;j<cols;j++) printf(" %6i",array[i*cols+j]);
+		printf(" ]\n");
+	}  
+	printf("\n");
+}
+
+#endif //ifndef _SHARED_ELEMENTS_H_
Index: /issm/trunk-jpl-damage/src/c/shared/Exceptions/Exceptions.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Exceptions/Exceptions.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Exceptions/Exceptions.cpp	(revision 11330)
@@ -0,0 +1,56 @@
+/* \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 "../shared.h"
+#include "../../include/include.h"
+#ifdef _SERIAL_
+#include "mex.h"
+#endif
+
+ErrorException::ErrorException(const string &what_arg){
+
+	what_str=what_arg;
+	file_name="";
+	function_name="";
+	file_line=0;
+}
+
+ErrorException::ErrorException(string what_file,string what_function,int what_line,string what_arg){
+
+	what_str=what_arg;
+	file_name=what_file;
+	function_name=what_function;
+	file_line=what_line;
+}
+
+ErrorException::~ErrorException() throw(){
+}
+
+const char* ErrorException::what() const throw(){
+	return what_str.c_str();
+}
+
+void ErrorException::Report(){
+	extern int my_rank;
+
+	if (function_name=="" || file_line==0){ //WINDOWS
+		printf("%s%s","Error message: ",what());
+	}
+	else{
+		#ifdef _PARALLEL_
+			printf("\n[%i] ??? Error using ==> %s:%i\n",my_rank,file_name.c_str(),file_line);
+			printf("[%i] %s error message: %s\n\n",my_rank,function_name.c_str(),what());
+		#else
+			mexErrMsgTxt(exprintf("\n??? Error using ==> %s at %i\n%s error message: %s\n",
+							file_name.c_str(),file_line,function_name.c_str(),what()));
+		#endif
+	}
+	return;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Exceptions/exceptions.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Exceptions/exceptions.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Exceptions/exceptions.h	(revision 11330)
@@ -0,0 +1,37 @@
+/*!\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>
+using namespace std;
+
+/*We derive our classes from the c++ exception class: */
+class ErrorException: public exception {
+	
+	string   what_str;
+	string   function_name;
+	string   file_name;
+	int      file_line;
+
+	public:
+
+	ErrorException(const string &what_arg); //for windows
+	ErrorException(string what_file,string what_function,int what_line,string what_arg);//UNIX
+	~ErrorException() throw();
+
+	virtual const char *what() const throw();
+
+	void Report();
+
+};
+
+char* exprintf(const char* format,...);
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Exceptions/exprintf.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Exceptions/exprintf.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Exceptions/exprintf.cpp	(revision 11330)
@@ -0,0 +1,30 @@
+/*!\file:  exprintf
+ * \brief this is a modification of the sprintf function. 
+ * Instead of returning an int, it will return the char* itself.
+ * The advantage is to be able to do things like: 
+ * ErrorException(exprintf("%s%i\n","test failed for id:",id));
+ */ 
+
+
+#include <stdarg.h>
+#include <stdio.h>
+#include "../Alloc/alloc.h"
+
+char* exprintf(const char* format,...){
+
+	/*returned string: */
+	char* string=NULL;
+
+	/*Assum nobody will print more that 1024 characters!*/
+	string=(char*)xmalloc(1024*sizeof(char));//assume that nobody will print more than 1024 characters at once.
+                                                                                                                                                                                                     
+	//variable list of arguments
+	va_list ap;
+
+	//First use vsprintf to get the whole input string.
+	va_start(ap,format);
+	vsprintf(string,format,ap); //printf style coding 
+	va_end(ap); 
+
+	return string;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineRead.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineRead.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineRead.cpp	(revision 11330)
@@ -0,0 +1,136 @@
+/*!\file:  DomainOutlineRead.cpp
+ * \brief DomainOutlineRead.c: read the vertex coordinates defined in a domain 
+ * outline from Argus (.exp file). The first contour in the file is for 
+ * the outside domain outline. The following contours represent holes in
+ * the domain.
+ */
+
+#include <stdio.h>
+#include "../Alloc/alloc.h"
+#include "../../include/include.h"
+#include "../Exceptions/exceptions.h"
+
+int DomainOutlineRead(int* pnprof,int** pprofnvertices,double*** ppprofx,double*** ppprofy,bool** pclosed,char* domainname,bool whole=true){
+
+	
+	/*Error management: */
+	int noerr=1;
+	int i,counter;
+
+	/*I/O: */
+	FILE* fid=NULL;
+	char chardummy[256];
+	double  ddummy;
+
+	/*output: */
+	int nprof; //number of profiles in the domainname file
+	int* profnvertices=NULL; //array holding the number of vertices for the nprof profiles
+	double** pprofx=NULL; //array of profiles x coordinates
+	double** pprofy=NULL; //array of profiles y coordinates
+	bool* closed=NULL; //array holding closed flags for the nprof profiles
+
+	/*For each profile: */
+	int n;
+	double* x=NULL;
+	double* y=NULL;
+	bool cl;
+
+	/*open domain outline file for reading: */
+	if ((fid=fopen(domainname,"r"))==NULL){
+		_error_("%s%s","could not find domain file ",domainname); 
+		noerr=0; goto cleanupandreturn;
+	}
+
+	/*Do a first pass through the domainname file, to figure out how many profiles 
+	 *we need to read: */
+	nprof=1;
+	for(;;){
+		fscanf(fid,"%256s %256s\n",chardummy,chardummy);
+		fscanf(fid,"%256s %256s\n",chardummy,chardummy);
+		fscanf(fid,"%256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy);
+		fscanf(fid,"%20u %256s\n",&n,chardummy);
+		fscanf(fid,"%256s %256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
+		for (i=0;i<n;i++){
+			fscanf(fid,"%20lf %20lf\n",&ddummy,&ddummy);
+		}
+		/*Ok, we have faked one profile reading, check whether we are at the end of the file, otherwise, keep fake reading next profile:*/
+		if (feof(fid)){
+			break;
+		}
+		nprof++;
+	}
+	
+	/*Allocate and initialize all the profiles: */
+	profnvertices=(int*)xmalloc(nprof*sizeof(int));
+	pprofx=(double**)xmalloc(nprof*sizeof(double*));
+	pprofy=(double**)xmalloc(nprof*sizeof(double*));
+	for (i=0;i<nprof;i++){
+		pprofx[i]=NULL;
+		pprofy[i]=NULL;
+	}
+	closed=(bool*)xmalloc(nprof*sizeof(bool));
+
+	/*Reaset file pointer to beginning of file: */
+	fseek(fid,0,SEEK_SET);
+
+	/*Start reading profiles: */
+	for(counter=0;counter<nprof;counter++){
+
+		/*Skip header: */
+		fscanf(fid,"%256s %256s\n",chardummy,chardummy);
+		fscanf(fid,"%256s %256s\n",chardummy,chardummy);
+		fscanf(fid,"%256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy);
+		
+		/*Get number of profile vertices: */
+		fscanf(fid,"%20u %256s\n",&n,chardummy);
+	
+		/*Skip next line: */
+		fscanf(fid,"%256s %256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
+
+		/*Allocate vertices: */
+		x=(double*)xmalloc(n*sizeof(double));
+		y=(double*)xmalloc(n*sizeof(double));
+		
+
+		/*Read vertices: */
+		for (i=0;i<n;i++){
+			fscanf(fid,"%20lf %20lf\n",x+i,y+i);
+		}
+
+		/*Now check that we are dealing with open contours: */
+		cl=false;
+		if((x[0]==x[n-1]) && (y[0]==y[n-1])){
+			cl=true;
+			if (!whole) {
+				n=n-1;
+			}
+		}
+
+		/*Assign pointers: */
+		profnvertices[counter]=n;
+		pprofx[counter]=x;
+		pprofy[counter]=y;
+		closed[counter]=cl;
+	}
+
+	/*close domain outline file: */
+	fclose(fid);
+
+	cleanupandreturn: 
+	/*Free ressources: */
+	if(!noerr){
+		xfree((void**)&x);
+		xfree((void**)&y);
+		n=-1;
+	}
+	
+	/*Assign output pointers: */
+	*pnprof=nprof;
+	*pprofnvertices=profnvertices;
+	*ppprofx=pprofx;
+	*ppprofy=pprofy;
+	if(pclosed)*pclosed=closed;
+	else       xfree((void**)&closed);
+	return noerr;
+}
+
Index: /issm/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineWrite.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineWrite.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineWrite.cpp	(revision 11330)
@@ -0,0 +1,72 @@
+/*!\file:  DomainOutlineWrite.cpp
+ * \brief DomainOutlineWrite.c: 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. The following contours represent holes in
+ * the domain.
+ */
+
+#include <stdio.h>
+#include "../Alloc/alloc.h"
+#include "../../include/include.h"
+#include "../Exceptions/exceptions.h"
+
+int DomainOutlineWrite(int nprof,int* profnvertices,double** pprofx,double** pprofy,bool* closed,char* domainname,bool whole=true){
+
+	
+	/*Error management: */
+	int noerr=1;
+	int i,counter;
+
+	/*I/O: */
+	FILE* fid=NULL;
+
+	/*input: */
+//	int nprof; //number of profiles in the domainname file
+//	int* profnvertices=NULL; //array holding the number of vertices for the nprof profiles
+//	double** pprofx=NULL; //array of profiles x coordinates
+//	double** pprofy=NULL; //array of profiles y coordinates
+//	bool* closed=NULL; //array holding closed flags for the nprof profiles
+
+	/*open domain outline file for writing: */
+	if ((fid=fopen(domainname,"w"))==NULL){
+		_error_("%s%s","could not open domain file ",domainname); 
+		noerr=0; goto cleanupandreturn;
+	}
+
+	/*Start writing profiles: */
+	for(counter=0;counter<nprof;counter++){
+
+		/*Write header: */
+		fprintf(fid,"%s %s\n","##","Name:");
+		fprintf(fid,"%s %s\n","##","Icon:0");
+		fprintf(fid,"%s %s %s %s\n","#","Points","Count","Value");
+		
+		/*Write number of profile vertices: */
+		if(closed[counter] && !whole)
+			fprintf(fid,"%u %s\n",profnvertices[counter]+1,"1.");
+		else
+			fprintf(fid,"%u %s\n",profnvertices[counter]  ,"1.");
+	
+		/*Write next line: */
+		fprintf(fid,"%s %s %s %s %s\n","#","X","pos","Y","pos");
+
+		/*Write vertices: */
+		for (i=0;i<profnvertices[counter];i++){
+			fprintf(fid,"%lf\t%lf\n",pprofx[counter][i],pprofy[counter][i]);
+		}
+
+		/*Now check that we are dealing with open contours: */
+		if(closed[counter] && !whole)
+			fprintf(fid,"%lf\t%lf\n",pprofx[counter][0],pprofy[counter][0]);
+
+		/*Write blank line: */
+		if(counter < nprof-1) fprintf(fid,"\n");
+	}
+
+	/*close domain outline file: */
+	fclose(fid);
+
+	cleanupandreturn: 
+	return noerr;
+}
+
Index: /issm/trunk-jpl-damage/src/c/shared/Exp/IsInPoly.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Exp/IsInPoly.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Exp/IsInPoly.cpp	(revision 11330)
@@ -0,0 +1,128 @@
+/*!\file IsInPoly.c
+ * \brief:  from a contour, determine which nodes are in  domain.
+ */
+
+#include <math.h>
+#include "../../toolkits/toolkits.h"
+#include "./exp.h"
+#include "../shared.h"
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*IsInPoly {{{1*/
+int IsInPoly(Vec in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue){
+
+	int i;
+	double x0,y0;
+	double value;
+	double xmin=xc[0];
+	double xmax=xc[0];
+	double ymin=yc[0];
+	double ymax=yc[0];
+
+	/*Get extrema*/
+	for (i=1;i<numvertices;i++){
+		if(xc[i]<xmin) xmin=xc[i];
+		if(xc[i]>xmax) xmax=xc[i];
+		if(yc[i]<ymin) ymin=yc[i];
+		if(yc[i]>ymax) ymax=yc[i];
+	}
+
+	/*Go through all vertices of the mesh:*/
+	for (i=i0;i<i1;i++){
+
+		//Get current value of value[i] -> do not change it if != 0
+		VecGetValues(in,1,&i,&value);
+		if (value){
+			/*this vertex already is inside one of the contours, continue*/
+			continue;
+		}
+
+		/*pick up vertex (x[i],y[i]) and figure out if located inside contour (xc,yc)*/
+		x0=x[i]; y0=y[i];
+		if(x0<xmin || x0>xmax || y0<ymin || y0>ymax){
+			value=0;
+		}
+		else{
+			value=pnpoly(numvertices,xc,yc,x0,y0,edgevalue);
+		}
+		VecSetValues(in,1,&i,&value,INSERT_VALUES);
+	}
+	 return 1;
+}/*}}}*/
+/*IsOutsidePoly {{{1*/
+int IsOutsidePoly(Vec in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue){
+
+	int i,j;
+	double x0,y0;
+	double value;
+	double xmin=xc[0];
+	double xmax=xc[0];
+	double ymin=yc[0];
+	double ymax=yc[0];
+
+	/*Get extrema*/
+	for (i=1;i<numvertices;i++){
+		if(xc[i]<xmin) xmin=xc[i];
+		if(xc[i]>xmax) xmax=xc[i];
+		if(yc[i]<ymin) ymin=yc[i];
+		if(yc[i]>ymax) ymax=yc[i];
+	}
+
+	/*Go through all vertices of the mesh:*/
+	for (i=i0;i<i1;i++){
+
+		//Get current value of value[i] -> do not change it if != 0
+		VecGetValues(in,1,&i,&value);
+		if (value){
+			/*this vertex already is inside one of the contours, continue*/
+			continue;
+		}
+
+		/*pick up vertex (x[i],y[i]) and figure out if located inside contour (xc,yc)*/
+		x0=x[i]; y0=y[i];
+		if(x0<xmin || x0>xmax || y0<ymin || y0>ymax){
+			value=1;
+		}
+		else{
+			value=1-pnpoly(numvertices,xc,yc,x0,y0,edgevalue);
+		}
+		VecSetValues(in,1,&i,&value,INSERT_VALUES);
+	}
+	return 1;
+}/*}}}*/
+/*pnpoly{{{1*/
+int pnpoly(int npol, double *xp, double *yp, double x, double y, int edgevalue) {
+	int i, j, c = 0;
+	double n1, n2, normp, scalar;
+	
+	/*first test, are they colinear? if yes, is the point in the middle of the segment*/
+	if (edgevalue != 2 ){
+		for (i = 0, j = npol-1; i < npol; j = i++) {
+			n1=pow(yp[i]-yp[j],2.0)+pow(xp[i]-xp[j],2.0);
+			n2=pow(y-yp[j],2.0)+pow(x-xp[j],2.0);
+			normp=pow(n1*n2,0.5);
+			scalar=(yp[i]-yp[j])*(y-yp[j])+(xp[i]-xp[j])*(x-xp[j]);
+
+			if (scalar == normp){
+				if (n2<=n1){
+					c = edgevalue;
+					return c;
+				}
+			}
+		}
+	}
+	/*second test : point is neither on a vertex, nor on a side, where is it ?*/
+	for (i = 0, j = npol-1; i < npol; j = i++) {
+		if ((((yp[i]<=y) && (y<yp[j])) ||
+					((yp[j]<=y) && (y<yp[i]))) &&
+				(x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i])){
+			c = !c;
+		}
+	}
+	return c;
+}/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/shared/Exp/IsInPolySerial.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Exp/IsInPolySerial.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Exp/IsInPolySerial.cpp	(revision 11330)
@@ -0,0 +1,34 @@
+/*
+ * IsInPolySerial.c:
+ */
+
+#include <math.h>
+
+
+#include "./exp.h"
+
+
+int IsInPolySerial(double* in,double* xc,double* yc,int numvertices,double* x,double* y,int nods, int edgevalue){
+
+	int i,j;
+	double x0,y0;
+
+	/*Go through all vertices of the mesh:*/
+	for (i=0;i<nods;i++){
+		if (in[i]){
+			/*this vertex already is inside one of the contours, continue*/
+			continue;
+		}
+		/*pick up vertex: */
+		x0=x[i];
+		y0=y[i];
+		if (pnpoly(numvertices,xc,yc,x0,y0,edgevalue)){
+			in[i]=1;
+		}
+		else{
+			in[i]=0;
+		}
+	}
+
+	return 1;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Exp/exp.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Exp/exp.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Exp/exp.h	(revision 11330)
@@ -0,0 +1,18 @@
+/* \file exp.h
+ * \brief: header file for contour (argus type, files in .exp extension) operations
+ */
+
+
+#ifndef _EXP_H_
+#define _EXP_H_
+
+#include "../../toolkits/toolkits.h"
+
+int IsInPoly(Vec in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue);
+int IsOutsidePoly(Vec in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue);
+int IsInPolySerial(double* in,double* xc,double* yc,int numvertices,double* x,double* y,int nods, int edgevalue);
+int DomainOutlineRead(int* pnprof,int** pprofnvertices,double*** ppprofx,double*** ppprofy,bool** pclosed,char* domainname,bool whole);
+int DomainOutlineWrite(int nprof,int* profnvertices,double** pprofx,double** pprofy,bool* closed,char* domainname,bool whole);
+int pnpoly(int npol, double *xp, double *yp, double x, double y, int edgevalue);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Matlab/CheckNumMatlabArguments.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Matlab/CheckNumMatlabArguments.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Matlab/CheckNumMatlabArguments.cpp	(revision 11330)
@@ -0,0 +1,28 @@
+/*!\file CheckNumMatlabArguments.cpp:
+ * \brief: check number of arguments and report an usage error message.
+ */
+
+#ifdef _SERIAL_
+
+#include "../Exceptions/exceptions.h"
+#include "../../include/include.h"
+#include "mex.h"
+
+int CheckNumMatlabArguments(int nlhs,int NLHS, int nrhs,int NRHS, const char* __FUNCT__, 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;
+}
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Matlab/ModuleBoot.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Matlab/ModuleBoot.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Matlab/ModuleBoot.cpp	(revision 11330)
@@ -0,0 +1,48 @@
+/* \file ModuleBoot.cpp
+ * \brief Carry out operations needed to boot, for example, petsc, MPI, plapack, etc ... 
+ * at the beginning of a module
+ */
+
+#include "../../toolkits/toolkits.h"
+
+int my_rank;
+int num_procs;
+
+int ModuleBoot(void){
+	
+	/*Declare my_rank and num_procs global variables!: */
+	my_rank=0;
+	num_procs=1;
+
+	/*Some test for MPI_Init crash with mpich2 1.4 on larsen, just ignore*/
+	#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 1
+	if(0){
+		int              mp_init = 0;
+		PetscErrorCode   ierr;
+		extern PetscBool PetscBeganMPI;
+		MPI_Initialized(&mp_init); 
+		if(mp_init!=1){
+			MPI_Init(NULL,NULL); 
+			PetscBeganMPI = PETSC_TRUE;
+			ierr=PetscInitializeNoArguments();CHKERRQ(ierr);
+		} 
+	}
+	else if (0){
+		PetscErrorCode   ierr;
+		PetscBool flg;
+		ierr=PetscInitialized(&flg);CHKERRQ(ierr);
+		if(flg){
+			extern PetscBool PetscBeganMPI;
+			PetscBeganMPI = PETSC_FALSE;
+			ierr=PetscFinalize();CHKERRQ(ierr);
+		}
+		ierr=PetscInitializeNoArguments();CHKERRQ(ierr);
+		ierr=PetscPopSignalHandler();CHKERRQ(ierr);
+	}
+	#endif
+
+	/*Initialize Petsc: */
+	PetscInitializeNoArguments();
+
+	return 1;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Matlab/ModuleEnd.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Matlab/ModuleEnd.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Matlab/ModuleEnd.cpp	(revision 11330)
@@ -0,0 +1,23 @@
+/* \file ModuleBoot.cpp
+ * \brief Carry out operations needed to boot, for example, petsc, MPI, plapack, etc ... 
+ * at the beginning of a module
+ */
+
+#include "../../toolkits/toolkits.h"
+
+int ModuleEnd(void){
+
+	#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 1
+	if(0){
+		PetscBool        flg;
+		PetscErrorCode   ierr;
+		extern PetscBool PetscBeganMPI;
+
+		/*Close PETSc but do not close MPI*/
+		PetscBeganMPI = PETSC_FALSE;
+		ierr=PetscFinalize();CHKERRQ(ierr);
+	}
+	#endif
+
+	return 1;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Matlab/PrintfFunction.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Matlab/PrintfFunction.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Matlab/PrintfFunction.cpp	(revision 11330)
@@ -0,0 +1,64 @@
+/*\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. 
+ */
+
+#include <stdarg.h>
+#include <stdio.h>
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+
+#ifdef _SERIAL_
+#include "mex.h"
+#endif
+
+int PrintfFunction(char* format,...){
+	/*http://linux.die.net/man/3/vsnprintf*/
+
+	/*string to be printed: */
+	char *buffer = NULL;
+	int   n,size = 100;
+	int         string_size;
+	extern int  my_rank;
+	extern int  num_procs;
+                                                                                                                                                                                                     
+	//variable list of arguments
+	va_list args;
+
+	while(true){
+
+		/*allocate buffer for given string size*/
+		buffer=(char*)xmalloc(size*sizeof(char));
+
+		/* Try to print in the allocated space. */
+		va_start(args, format);
+#ifndef WIN32
+		n=vsnprintf(buffer,size,format,args);
+#else
+		n=vsnprintf(buffer,size,format,args);
+#endif
+		va_end(args);
+
+		/* If that worked, return the string. */
+		if(n>-1 && n<size) break;
+
+		/* Else try again with more space. */
+		if(n>-1)   /* glibc 2.1 */
+		 size=n+1; /* precisely what is needed */
+		else       /* glibc 2.0 */
+		 size*=2;  /* twice the old size */
+
+		xfree((void**)&buffer);
+	}
+
+	/*Ok, if we are running in parallel, get node 0 to print*/
+#if defined(_PARALLEL_)
+	if(my_rank==0)printf(buffer);
+#else
+	mexPrintf(buffer);
+#endif
+
+	/*Clean up and return*/
+	xfree((void**)&buffer);
+	return 1;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Matlab/matlabshared.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Matlab/matlabshared.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Matlab/matlabshared.h	(revision 11330)
@@ -0,0 +1,19 @@
+/* \file Matlab.h
+ * \brief  header file for all routines related to matlab.
+ */
+
+#ifndef _MATLAB_SHARED_H_
+#define _MATLAB_SHARED_H_
+
+#include "../../objects/objects.h"
+
+
+#ifdef _SERIAL_
+#include "mex.h"
+	int ModuleBoot(void);
+	int ModuleEnd(void);
+	mxArray* mxGetAssignedField(const mxArray* pmxa_array,int number, const char* field);
+	int CheckNumMatlabArguments(int nlhs,int NLHS, int nrhs,int NRHS, const char* THISFUNCTION, void (*function)( void ));
+#endif
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Matlab/mxGetAssignedField.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Matlab/mxGetAssignedField.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Matlab/mxGetAssignedField.cpp	(revision 11330)
@@ -0,0 +1,43 @@
+/*!\file: mxGetAssignedField.c: 
+ * \brief: abstract interface on parallel side for i/o, so it ressembles the serial i/o.
+ *
+ * In serial mode, this routine takes care of returning the field coming 
+ * from the model. If largesize is 1, we are running out of core models in 
+ * matlab, and we need to call the subsref private method from the model object
+ * in order to correctly load the data from disk.
+ */
+
+
+#ifdef _SERIAL_
+
+#include "mex.h"
+
+mxArray* mxGetAssignedField(const mxArray* pmxa_array,int number,const char* field){
+
+	//output
+	mxArray* mxfield=NULL;
+	
+	//input
+	mxArray    *inputs[2];
+	mxArray    *pindex      = NULL;
+	const char *fnames[2];
+	mwSize      ndim        = 2;
+	mwSize      onebyone[2] = {1,1};
+
+	//We want to call the subsasgn method, and get the returned array.This ensures that if we are running 
+	//large sized problems, the data is truly loaded from disk by the model subsasgn class method.
+	inputs[0]=(mxArray*)pmxa_array; //this is the model
+
+	//create index structure used in the assignment (index.type='.' and index.subs='x' for field x for ex)
+	fnames[0] = "type";
+	fnames[1] = "subs";
+	pindex=mxCreateStructArray( ndim,onebyone,2,fnames);
+	mxSetField( pindex, 0, "type",mxCreateString("."));
+	mxSetField( pindex, 0, "subs",mxCreateString(field));
+	inputs[1]=pindex;
+
+	mexCallMATLAB( 1, &mxfield, 2, (mxArray**)inputs, "subsref");
+
+	return mxfield;
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Matlab/mxGetField.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Matlab/mxGetField.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Matlab/mxGetField.cpp	(revision 11330)
@@ -0,0 +1,12 @@
+/* \file mxGetField.c: 
+ * \brief: placeholder for parallel mxGetField dummy routine.
+ * This routine does nothing, just returns a NULL pointer, and is only present in the parallel compilation 
+ * to "mirror" the mxGetField matlab routine. This makes coding of parallel applications a lot easier. 
+ * It is  used in ModelProcessorx/Model.c for example.
+ */
+
+#include <stdio.h>
+
+#ifdef _PARALLEL_
+FILE* mxGetField(FILE* fid,int number, char* field){ return fid; }
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Matrix/MatrixUtils.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Matrix/MatrixUtils.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Matrix/MatrixUtils.cpp	(revision 11330)
@@ -0,0 +1,419 @@
+/*!\file: MatrixUtils
+ * \brief triple multiply
+ */ 
+
+/*Headers*/
+/*{{{1*/
+#include "./matrix.h"
+#include "../Exceptions/exceptions.h"
+#include "../Alloc/alloc.h"
+#include "../Matlab/matlabshared.h"
+#include <stdio.h>
+#include <sys/types.h>
+#include <math.h>
+#include <float.h>    /*  DBL_EPSILON  */
+#include "../../include/include.h"
+#include "../../io/io.h"
+/*}}}*/
+
+/*FUNCTION TripleMultiply {{{1*/
+int TripleMultiply( double* a, int nrowa, int ncola, int itrna, double* b, int nrowb, int ncolb, int itrnb, double* c, int nrowc, int ncolc, int itrnc, double* d, int iaddd){
+	/*TripleMultiply    Perform triple matrix product a*b*c+d.*/
+	
+	int idima,idimb,idimc,idimd;
+	double* dtemp;
+
+/*  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 doubles, and a*(b*c)
+	requires bd(a+c) multiplies and bd doubles (both are the same for
+	a symmetric triple product)  */
+
+/*  multiply (a*b)*c+d  */
+
+	if (idima*idimc*(idimb+idimd) <= idimb*idimd*(idima+idimc)) {
+		dtemp=(double *) xmalloc(idima*idimc*sizeof(double));
+
+		MatrixMultiply(a    ,nrowa,ncola,itrna,
+				   b    ,nrowb,ncolb,itrnb,
+				   dtemp,0);
+		MatrixMultiply(dtemp,idima,idimc,0    ,
+				   c    ,nrowc,ncolc,itrnc,
+				   d    ,iaddd);
+
+		xfree((void **)&dtemp);
+	}
+
+/*  multiply a*(b*c)+d  */
+
+	else {
+		dtemp=(double *) xmalloc(idimb*idimd*sizeof(double));
+
+		MatrixMultiply(b    ,nrowb,ncolb,itrnb,
+				   c    ,nrowc,ncolc,itrnc,
+				   dtemp,0);
+		MatrixMultiply(a    ,nrowa,ncola,itrna,
+				   dtemp,idimb,idimd,0    ,
+				   d    ,iaddd);
+
+		xfree((void **)&dtemp);
+	}
+
+	return 1;
+}/*}}}*/
+/*FUNCTION MatrixMuliply {{{1*/
+int MatrixMultiply( double* a, int nrowa, int ncola, int itrna, double* b, int nrowb, int ncolb, int itrnb, double* c, int iaddc ){
+	/*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;
+
+/*  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");
+	    noerr=0;	
+		return noerr;
+	}
+	else
+		nterm=ntrma;
+
+/*  zero matrix c, if not being added to product  */
+
+	if (!iaddc)
+		for (i=0; i<nrowc*ncolc; i++)
+			*(c+i)=0.;
+
+/*  perform the matrix multiplication  */
+
+	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;
+}/*}}}*/
+/*FUNCTION MatrixInverse {{{1*/
+int MatrixInverse( double* a, int ndim, int nrow, double* b, int nvec, double* 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 (*pivrc)[2],*pindx;
+	double pivot,det,dtemp;
+
+	if (!b && nvec) {
+		_error_("No right-hand side for nvec=%d.",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.;
+
+	pivrc = (int (*)[2]) xmalloc((nrow*2)*sizeof(int));
+	pindx = (int (*)   ) xcalloc( nrow   ,sizeof(int));
+
+/*  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) {
+			xfree((void **)&pivrc);
+			xfree((void **)&pindx);
+			_error_("Pivot %f less than machine epsilon",pivot);
+			noerr=0;
+			return noerr;
+		}
+
+		pivrc[i][0]=irow;
+		pivrc[i][1]=icol;
+
+		ipiv=icol;
+		pindx[ipiv]++;
+
+//		_printf_(true,"pivot for i=%d: irow=%d, icol=%d, pindx[%d]=%d\n",
+//				 i,irow,icol,ipiv,pindx[ipiv]);
+
+/*  switch rows to put pivot element on diagonal, noting that the
+	column stays the same and the determinant changes sign  */
+
+		if (irow != icol) {
+//			_printf_(true,"row switch for i=%d: irow=%d, icol=%d\n",
+//					 i,irow,icol);
+
+			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 (pivrc[j][0] != pivrc[j][1]) {
+			irow=pivrc[j][0];
+			icol=pivrc[j][1];
+
+//			_printf_(true,"column switch back for j=%d: irow=%d, icol=%d\n",
+//					 j,irow,icol);
+
+			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;
+
+	xfree((void **)&pivrc);
+	xfree((void **)&pindx);
+
+	return noerr;
+}/*}}}*/
+/*FUNCTION Matrix2x2Determinant(double* Adet,double* A) {{{1*/
+void Matrix2x2Determinant(double* Adet,double* A){
+	/*Compute determinant of a 2x2 matrix*/
+
+	/*det = a*d - c*b*/
+	*Adet= A[0]*A[3]-A[2]*A[1];
+}
+/*}}}*/
+/*FUNCTION Matrix2x2Invert(double* Ainv,double* A) {{{1*/
+void Matrix2x2Invert(double* Ainv,double* A){
+
+	/*Intermediaries*/
+	double det;
+
+	/*Compute determinant*/
+	Matrix2x2Determinant(&det,A);
+	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller that 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 */
+
+}/*}}}*/
+/*FUNCTION Matrix3x3Determinant(double* Adet,double* A) {{{1*/
+void Matrix3x3Determinant(double* Adet,double* 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];
+}
+/*}}}*/
+/*FUNCTION Matrix3x3Invert(double* Ainv,double* A) {{{1*/
+void Matrix3x3Invert(double* Ainv,double* A){
+
+	/*Intermediaries*/
+	double det;
+
+	/*Compute determinant*/
+	Matrix3x3Determinant(&det,A);
+	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller that 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 */
+
+}/*}}}*/
+/*FUNCTION MatrixTranspose(double* Adet,double* A) {{{1*/
+void MatrixTranspose(double* tA,double* A, int nrows, int ncols){
+	/*Transpose a n*m matrix*/
+
+	int i,j;
+
+	/*Check the the matrix has been allocated*/
+	_assert_(tA);
+
+	/*Transpose*/
+	for(i=0;i<ncols;i++){
+		for(j=0;j<nrows;j++){
+			tA[i*nrows+j]=A[j*ncols+i];
+		}
+	}
+
+}
+/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/shared/Matrix/matrix.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Matrix/matrix.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Matrix/matrix.h	(revision 11330)
@@ -0,0 +1,17 @@
+/*!\file: matrix.h
+ * \brief prototypes for matrix.h
+ */ 
+
+#ifndef _MATRIXUTILS_H_
+#define _MATRIXUTILS_H_
+
+int  TripleMultiply( double* a, int nrowa, int ncola, int itrna, double* b, int nrowb, int ncolb, int itrnb, double* c, int nrowc, int ncolc, int itrnc, double* d, int iaddd);
+int  MatrixMultiply( double* a, int nrowa, int ncola, int itrna, double* b, int nrowb, int ncolb, int itrnb, double* c, int iaddc );
+int  MatrixInverse( double* a, int ndim, int nrow, double* b, int nvec, double* pdet );
+void Matrix2x2Invert(double* Ainv, double* A);
+void Matrix2x2Determinant(double* Adet,double* A);
+void Matrix3x3Invert(double* Ainv, double* A);
+void Matrix3x3Determinant(double* Adet,double* A);
+void MatrixTranspose(double* tA,double* A,int nrows, int ncols);
+
+#endif //ifndef _MATRIXUTILS_H_
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/BrentSearch.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/BrentSearch.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/BrentSearch.cpp	(revision 11330)
@@ -0,0 +1,213 @@
+/*!\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 "./numerics.h"
+#include "../../objects/objects.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../../shared/shared.h"
+#include <float.h>
+
+void BrentSearch(double* psearch_scalar,double* pJ,OptPars* optpars,double (*f)(double,OptArgs*), OptArgs* optargs){
+
+	/* This routine is optimizing a given function using Brent's method
+	 * (Golden or parabolic procedure)*/
+
+	/*Intermediary*/
+	double si,gold,intervalgold,oldintervalgold;
+	double parab_num,parab_den;
+	double distance,cm_jump;
+	double fxmax,fxmin,fxbest;
+	double fx,fx1,fx2;
+	double xmax,xmin,xbest;
+	double x,x1,x2,xm;
+	double tol1,tol2,seps;
+	double tolerance=1.e-4;
+	int    maxiter,iter;
+	bool   loop=true,goldenflag;
+
+	/*Recover parameters:*/
+	xmin=optpars->xmin;
+	xmax=optpars->xmax;
+	maxiter=optpars->maxiter;
+	cm_jump=optpars->cm_jump;
+	
+	/*initialize counter and get response at the boundaries*/
+	iter=0;
+	fxmin = (*f)(xmin,optargs);
+	if (isnan(fxmin)) _error_("Function evaluation returned NaN");
+	_printf_(VerboseControl(),"\n        Iteration         x           f(x)       Tolerance         Procedure\n\n");
+	_printf_(VerboseControl(),"        %s    %12.6g  %12.6g  %s","   N/A",xmin,fxmin,"         N/A         boundary\n");
+	fxmax = (*f)(xmax,optargs);
+	if (isnan(fxmax)) _error_("Function evaluation returned NaN");
+	_printf_(VerboseControl(),"        %s    %12.6g  %12.6g  %s","   N/A",xmax,fxmax,"         N/A         boundary\n");
+
+	/*test if jump option activated and xmin==0*/
+	if (!isnan(cm_jump) && (xmin==0) && (fxmax/fxmin)<cm_jump){
+		*psearch_scalar=xmax;
+		*pJ=fxmax;
+		return;
+	}
+
+	/*initialize optimization variables*/
+	seps=sqrt(DBL_EPSILON);    //precision of a double
+	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*/
+	fxbest = (*f)(x,optargs);
+	if(isnan(fxbest)) _error_("Function evaluation returned NaN");
+	iter=iter+1;
+
+	/*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*/
+	_printf_(VerboseControl(),"         %5i    %12.6g  %12.6g  %12.6g  %s\n",iter,xbest,fxbest,pow(pow(xbest-xm,2),0.5),"       initial");
+	if (!isnan(cm_jump) && (xmin==0) && ((fxbest/fxmin)<cm_jump)){
+		_printf_(VerboseControl(),"      optimization terminated: current x satisfies criteria 'cm_jump'=%g\n",cm_jump);
+		loop=false;
+	}
+
+	while(loop){
+
+		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
+		fx = (*f)(x,optargs);
+		if(isnan(fx)) _error_("Function evaluation returned NaN");
+		iter=iter+1;
+
+		// 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;
+		_printf_(VerboseControl(),"         %5i    %12.6g  %12.6g  %12.6g  %s\n",iter,x,fx,pow(pow(xbest-xm,2),0.5),goldenflag?"       golden":"       parabolic");
+
+		/*Stop the optimization?*/
+		if (sqrt(pow(xbest-xm,2)) < (tol2-0.5*(xmax-xmin))){
+			_printf_(VerboseControl(),"      optimization terminated: current x satisfies criteria 'tolx'=%g\n",tolerance);
+			loop=false;
+		}
+		else if (iter>=maxiter){
+			_printf_(VerboseControl(),"      exiting: Maximum number of iterations has been exceeded  ('maxiter'=%i)\n",maxiter);
+			loop=false;
+		}
+		else if (!isnan(cm_jump) && (xmin==0) && ((fxbest/fxmin)<cm_jump)){
+			_printf_(VerboseControl(),"      optimization terminated: current x satisfies criteria 'cm_jump'=%g\n",cm_jump);
+			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: */
+	*psearch_scalar=xbest;
+	*pJ=fxbest;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.cpp	(revision 11330)
@@ -0,0 +1,1722 @@
+/*  Gauss point structures and prototypes  */
+
+#include "./GaussPoints.h"
+#include "../Matlab/matlabshared.h"
+#include "../Alloc/alloc.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+#include "../Exceptions/exceptions.h"
+#include <math.h>
+#include <float.h>
+
+/*General Gauss points*/
+/*FUNCTION GaussLegendreLinear {{{1*/
+void GaussLegendreLinear( double** pxgaus, double** 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;
+	double *alpha,*beta;
+
+	/*p= 1, npoint= 1*/
+	static double wgt1[]={2.000000000000000};
+	static double xi1[]={0.000000000000000};
+
+	/*p= 3, npoint= 2*/
+	static double wgt2[]={1.000000000000000, 1.000000000000000};
+	static double xi2[]={-0.577350269189626, 0.577350269189626};
+
+	/*p= 5, npoint= 3*/
+	static double wgt3[]={0.555555555555556, 0.888888888888889, 0.555555555555556};
+	static double xi3[]={-0.774596669241483, 0.000000000000000, 0.774596669241483};
+
+	/*p= 7, npoint= 4*/
+	static double wgt4[]={0.347854845137454, 0.652145154862546, 0.652145154862546, 0.347854845137454};
+	static double xi4[]={-0.861136311594053,-0.339981043584856, 0.339981043584856, 0.861136311594053};
+
+	static double* wgtp[MAX_LINE_GAUS_PTS]={wgt1 ,wgt2 ,wgt3 ,wgt4 };
+	static double* xip [MAX_LINE_GAUS_PTS]={xi1  ,xi2  ,xi3  ,xi4  };
+
+	static int np[MAX_LINE_GAUS_PTS]={sizeof(wgt1 )/sizeof(double),
+		sizeof(wgt2 )/sizeof(double),
+		sizeof(wgt3 )/sizeof(double),
+		sizeof(wgt4 )/sizeof(double)};
+
+	//	_printf_(true,"Gauss-Legendre recurrence coefficients ngaus=%d\n",ngaus);
+	*pxgaus = (double *) xmalloc(ngaus*sizeof(double));
+	*pxwgt  = (double *) xmalloc(ngaus*sizeof(double));
+
+	/*  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=(double *) xmalloc(ngaus*sizeof(double));
+		beta =(double *) xmalloc(ngaus*sizeof(double));
+
+		/*  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 );
+		xfree((void **)&beta );
+		xfree((void **)&alpha);
+	}
+}/*}}}1*/
+/*FUNCTION GaussLegendreTria{{{1*/
+void GaussLegendreTria( int* pngaus, double** pl1, double** pl2, double** pl3, double** 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;
+	double xi,eta;
+	double *xgaus=NULL,*xwgt=NULL,*egaus,*ewgt;
+
+	/*Hardcoded Gauss points declaration*/
+	/*p= 1, npoint= 1{{{2*/
+	static double wgt1[]={
+		1.732050807568877};
+	static double l11[]={
+		0.333333333333333};
+	static double l21[]={
+		0.333333333333333};
+	static double l31[]={
+		0.333333333333333};
+	/*}}}2*/
+	/*p= 2, npoint= 3  {{{2*/
+	static double wgt2[]={
+		0.577350269189625, 0.577350269189625, 0.577350269189625};
+	static double l12[]={
+		0.666666666666667, 0.166666666666667, 0.166666666666667};
+	static double l22[]={
+		0.166666666666667, 0.666666666666667, 0.166666666666667};
+	static double l32[]={
+		0.166666666666667, 0.166666666666667, 0.666666666666667};
+	/*}}}2*/
+	/*p= 3, npoint= 4  {{{2*/
+	static double wgt3[]={
+		-0.974278579257493, 0.902109795608790, 0.902109795608790, 
+		0.902109795608790};
+	static double l13[]={
+		0.333333333333333, 0.600000000000000, 0.200000000000000, 
+		0.200000000000000};
+	static double l23[]={
+		0.333333333333333, 0.200000000000000, 0.600000000000000, 
+		0.200000000000000};
+	static double l33[]={
+		0.333333333333333, 0.200000000000000, 0.200000000000000, 
+		0.600000000000000};
+	/*}}}2*/
+	/*p= 4, npoint= 6  {{{2*/
+	static double wgt4[]={
+		0.386908262797819, 0.386908262797819, 0.386908262797819, 
+		0.190442006391807, 0.190442006391807, 0.190442006391807};
+	static double l14[]={
+		0.108103018168070, 0.445948490915965, 0.445948490915965, 
+		0.816847572980459, 0.091576213509771, 0.091576213509771};
+	static double l24[]={
+		0.445948490915965, 0.108103018168070, 0.445948490915965, 
+		0.091576213509771, 0.816847572980459, 0.091576213509771};
+	static double l34[]={
+		0.445948490915965, 0.445948490915965, 0.108103018168070, 
+		0.091576213509771, 0.091576213509771, 0.816847572980459};
+	/*}}}2*/
+	/*p= 5, npoint= 7  {{{2*/
+	static double wgt5[]={
+		0.389711431702997, 0.229313399254729, 0.229313399254729, 
+		0.229313399254729, 0.218133059367230, 0.218133059367230, 
+		0.218133059367230};
+	static double l15[]={
+		0.333333333333333, 0.059715871789770, 0.470142064105115, 
+		0.470142064105115, 0.797426985353087, 0.101286507323456, 
+		0.101286507323456};
+	static double l25[]={
+		0.333333333333333, 0.470142064105115, 0.059715871789770, 
+		0.470142064105115, 0.101286507323456, 0.797426985353087, 
+		0.101286507323456};
+	static double l35[]={
+		0.333333333333333, 0.470142064105115, 0.470142064105115, 
+		0.059715871789770, 0.101286507323456, 0.101286507323456, 
+		0.797426985353087};
+	/*}}}2*/
+	/*p= 6, npoint=12  {{{2*/
+	static double wgt6[]={
+		0.202279763184836, 0.202279763184836, 0.202279763184836, 
+		0.088065961139281, 0.088065961139281, 0.088065961139281, 
+		0.143502272432755, 0.143502272432755, 0.143502272432755, 
+		0.143502272432755, 0.143502272432755, 0.143502272432755};
+	static double l16[]={
+		0.501426509658179, 0.249286745170910, 0.249286745170910, 
+		0.873821971016996, 0.063089014491502, 0.063089014491502, 
+		0.053145049844817, 0.053145049844817, 0.310352451033784, 
+		0.636502499121399, 0.310352451033784, 0.636502499121399};
+	static double l26[]={
+		0.249286745170910, 0.501426509658179, 0.249286745170910, 
+		0.063089014491502, 0.873821971016996, 0.063089014491502, 
+		0.310352451033784, 0.636502499121399, 0.053145049844817, 
+		0.053145049844817, 0.636502499121399, 0.310352451033784};
+	static double l36[]={
+		0.249286745170910, 0.249286745170910, 0.501426509658179, 
+		0.063089014491502, 0.063089014491502, 0.873821971016996, 
+		0.636502499121399, 0.310352451033784, 0.636502499121399, 
+		0.310352451033784, 0.053145049844817, 0.053145049844817};
+	/*}}}2*/
+	/*p= 7, npoint=13  {{{2*/
+	static double wgt7[]={
+		-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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*p= 8, npoint=16  {{{2*/
+	static double 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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*p= 9, npoint=19  {{{2*/
+	static double 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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*p=10, npoint=25  {{{2*/
+	static double 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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*p=11, npoint=27  {{{2*/
+	static double 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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*p=12, npoint=33  {{{2*/
+	static double 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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*  p=13, npoint=37  {{{2*/
+	static double 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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*p=14, npoint=42{{{2*/
+	static double 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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*p=15, npoint=48{{{2*/
+	static double 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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*p=16, npoint=52  {{{2*/
+	static double 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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*p=17, npoint=61{{{2*/
+	static double 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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*  p=18, npoint=70  {{{2*/
+
+	static double 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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*p=19, npoint=73  {{{2*/
+
+	static double 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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*p=20, npoint=79 {{{2*/
+	static double 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 double 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 double 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 double 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};
+	/*}}}2*/
+
+	static double* wgtp[MAX_TRIA_SYM_ORD]={
+		wgt1 ,wgt2 ,wgt3 ,wgt4 ,wgt5 ,
+		wgt6 ,wgt7 ,wgt8 ,wgt9 ,wgt10,
+		wgt11,wgt12,wgt13,wgt14,wgt15,
+		wgt16,wgt17,wgt18,wgt19,wgt20};
+	static double* l1p [MAX_TRIA_SYM_ORD]={
+		l11  ,l12  ,l13  ,l14  ,l15  ,
+		l16  ,l17  ,l18  ,l19  ,l110 ,
+		l111 ,l112 ,l113 ,l114 ,l115 ,
+		l116 ,l117 ,l118 ,l119 ,l120 };
+	static double* l2p [MAX_TRIA_SYM_ORD]={
+		l21  ,l22  ,l23  ,l24  ,l25  ,
+		l26  ,l27  ,l28  ,l29  ,l210 ,
+		l211 ,l212 ,l213 ,l214 ,l215 ,
+		l216 ,l217 ,l218 ,l219 ,l220 };
+	static double* l3p [MAX_TRIA_SYM_ORD]={
+		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(double),
+		sizeof(wgt2 )/sizeof(double),
+		sizeof(wgt3 )/sizeof(double),
+		sizeof(wgt4 )/sizeof(double),
+		sizeof(wgt5 )/sizeof(double),
+		sizeof(wgt6 )/sizeof(double),
+		sizeof(wgt7 )/sizeof(double),
+		sizeof(wgt8 )/sizeof(double),
+		sizeof(wgt9 )/sizeof(double),
+		sizeof(wgt10)/sizeof(double),
+		sizeof(wgt11)/sizeof(double),
+		sizeof(wgt12)/sizeof(double),
+		sizeof(wgt13)/sizeof(double),
+		sizeof(wgt14)/sizeof(double),
+		sizeof(wgt15)/sizeof(double),
+		sizeof(wgt16)/sizeof(double),
+		sizeof(wgt17)/sizeof(double),
+		sizeof(wgt18)/sizeof(double),
+		sizeof(wgt19)/sizeof(double),
+		sizeof(wgt20)/sizeof(double)};
+
+	//	_printf_(true,"GaussLegendreTria: iord=%d\n",iord);
+
+	/*  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  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl2  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl3  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pwgt = (double *) xmalloc(*pngaus*sizeof(double));
+
+		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  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl2  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl3  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pwgt = (double *) xmalloc(*pngaus*sizeof(double));
+
+		/*  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++;
+			}
+		}
+		xfree((void **)&xwgt );
+		xfree((void **)&xgaus);
+	}
+
+	//	_printf_(true,"GaussLegendreTria - ngaus=%d\n",*pngaus);
+	//	for (i=0; i<*pngaus; i++)
+	//		_printf_(true,"i=%d: l1gaus=%f,l2gaus=%f,l3gaus=%f,wgt=%f\n",
+	//				 i,(*pl1 )[i],(*pl2 )[i],(*pl3 )[i],(*pwgt)[i]);
+
+	return;
+}/*}}}1*/
+/*FUNCTION GaussLegendreTetra{{{1*/
+void GaussLegendreTetra( int* pngaus, double** pl1, double** pl2, double** pl3, double** pl4, double** 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;
+	double xi,eta,zeta;
+	double *xgaus=NULL,*xwgt=NULL,*egaus,*ewgt,*zgaus,*zwgt;
+
+	/*Hardcoded Gauss points definition*/
+	/*p= 1, npoint= 1  {{{2*/
+	static double wgt1[]={
+		1.000000000000000};
+	static double l11[]={
+		0.250000000000000};
+	static double l21[]={
+		0.250000000000000};
+	static double l31[]={
+		0.250000000000000};
+	static double l41[]={
+		0.250000000000000};
+	/*}}}2*/
+	/*p= 2, npoint= 4  {{{2*/
+
+	static double wgt2[]={
+		0.250000000000000, 0.250000000000000, 0.250000000000000,
+		0.250000000000000};
+	static double l12[]={
+		0.585410196624969, 0.138196601125011, 0.138196601125011,
+		0.138196601125011};
+	static double l22[]={
+		0.138196601125011, 0.585410196624969, 0.138196601125011,
+		0.138196601125011};
+	static double l32[]={
+		0.138196601125011, 0.138196601125011, 0.585410196624969,
+		0.138196601125011};
+	static double l42[]={
+		0.138196601125011, 0.138196601125011, 0.138196601125011,
+		0.585410196624969};
+	/*}}}2*/
+	/*p= 3, npoint= 5  {{{2*/
+	static double wgt3[]={
+		-0.800000000000000, 0.450000000000000, 0.450000000000000, 
+		0.450000000000000, 0.450000000000000};
+	static double l13[]={
+		0.250000000000000, 0.500000000000000, 0.166666666666667, 
+		0.166666666666667, 0.166666666666667};
+	static double l23[]={
+		0.250000000000000, 0.166666666666667, 0.500000000000000, 
+		0.166666666666667, 0.166666666666667};
+	static double l33[]={
+		0.250000000000000, 0.166666666666667, 0.166666666666667, 
+		0.500000000000000, 0.166666666666667};
+	static double l43[]={
+		0.250000000000000, 0.166666666666667, 0.166666666666667, 
+		0.166666666666667, 0.500000000000000};
+	/*}}}2*/
+	/*p= 4, npoint=11  {{{2*/
+
+	static double wgt4[]={
+		-0.013155555555556, 0.007622222222222, 0.007622222222222, 
+		0.007622222222222, 0.007622222222222, 0.024888888888889,
+		0.024888888888889, 0.024888888888889, 0.024888888888889, 
+		0.024888888888889, 0.024888888888889};
+	static double l14[]={
+		0.250000000000000, 0.785714285714286, 0.071428571428571, 
+		0.071428571428571, 0.071428571428571, 0.399403576166799,
+		0.399403576166799, 0.399403576166799, 0.100596423833201, 
+		0.100596423833201, 0.100596423833201};
+	static double l24[]={
+		0.250000000000000, 0.071428571428571, 0.785714285714286, 
+		0.071428571428571, 0.071428571428571, 0.399403576166799,
+		0.100596423833201, 0.100596423833201, 0.399403576166799, 
+		0.399403576166799, 0.100596423833201};
+	static double l34[]={
+		0.250000000000000, 0.071428571428571, 0.071428571428571, 
+		0.785714285714286, 0.071428571428571, 0.100596423833201, 
+		0.399403576166799, 0.100596423833201, 0.399403576166799,
+		0.100596423833201, 0.399403576166799};
+	static double l44[]={
+		0.250000000000000, 0.071428571428571, 0.071428571428571, 
+		0.071428571428571, 0.785714285714286, 0.100596423833201, 
+		0.100596423833201, 0.399403576166799, 0.100596423833201,
+		0.399403576166799, 0.399403576166799};
+	/*}}}2*/
+	/*p= 5, npoint=15  {{{2*/
+
+	static double wgt5[]={
+		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 double 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 double 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 double 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 double 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};
+	/*}}}2*/
+	/*p= 6, npoint=24  {{{2*/
+
+	static double 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 double 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 double 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 double 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 double 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};
+	/*}}}2*/
+
+	static double* wgtp[MAX_TETRA_SYM_ORD]={wgt1,wgt2,wgt3,wgt4,wgt5,wgt6};
+	static double* l1p [MAX_TETRA_SYM_ORD]={l11 ,l12 ,l13 ,l14 ,l15 ,l16 };
+	static double* l2p [MAX_TETRA_SYM_ORD]={l21 ,l22 ,l32 ,l24 ,l25 ,l26 };
+	static double* l3p [MAX_TETRA_SYM_ORD]={l31 ,l32 ,l33 ,l34 ,l35 ,l36 };
+	static double* l4p [MAX_TETRA_SYM_ORD]={l41 ,l42 ,l43 ,l44 ,l45 ,l46 };
+
+	static int np[MAX_TETRA_SYM_ORD]={sizeof(wgt1 )/sizeof(double),
+		sizeof(wgt2 )/sizeof(double),
+		sizeof(wgt3 )/sizeof(double),
+		sizeof(wgt4 )/sizeof(double),
+		sizeof(wgt5 )/sizeof(double),
+		sizeof(wgt6 )/sizeof(double)};
+
+	//	_printf_(true,"GaussLegendreTetra: iord=%d\n",iord);
+
+	/*  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  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl2  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl3  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl4  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pwgt = (double *) xmalloc(*pngaus*sizeof(double));
+
+		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]*2./3.*SQRT2;
+		}
+	}
+	else {
+
+		/*  calculate the Gauss points from the collapsed hexahedron  */
+		nigaus =iord/2+1;
+		*pngaus=nigaus*nigaus*nigaus;
+
+		*pl1  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl2  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl3  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl4  = (double *) xmalloc(*pngaus*sizeof(double));
+		*pwgt = (double *) xmalloc(*pngaus*sizeof(double));
+
+		/*  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++;
+				}
+			}
+		}
+		xfree((void **)&xwgt );
+		xfree((void **)&xgaus);
+	}
+}/*}}}1*/
+/*FUNCTION GaussLobatto{{{1*/
+void GaussLobatto( double** pxgaus, double** 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;
+	double *alpha,*beta;
+	double left=-1.,right= 1.;
+	double p0l=0.,p0r=0.,p1l=1.,p1r=1.,pm1l,pm1r,det;
+
+	/*p= 1, npoint= 1 (Gauss-Legendre)*/
+	static double wgt1[]={2.000000000000000};
+	static double xi1[]={0.000000000000000};
+
+	/*p= 1, npoint= 2*/
+	static double wgt2[]={1.000000000000000, 1.000000000000000};
+	static double xi2[]={-1.000000000000000, 1.000000000000000};
+
+	/*p= 3, npoint= 3*/
+	static double wgt3[]={0.333333333333333, 1.333333333333333, 0.333333333333333};
+	static double xi3[]={-1.000000000000000, 0.000000000000000, 1.000000000000000};
+
+	/*p= 5, npoint= 4*/
+	static double wgt4[]={0.166666666666667, 0.833333333333333, 0.833333333333333, 0.166666666666667};
+	static double xi4[]={-1.000000000000000,-0.447213595499958, 0.447213595499958, 1.000000000000000};
+
+	/*p= 7, npoint= 5*/
+	static double wgt5[]={0.100000000000000, 0.544444444444444, 0.711111111111111, 0.544444444444444, 0.100000000000000};
+	static double xi5[]={-1.000000000000000,-0.654653670707977, 0.000000000000000, 0.654653670707977, 1.000000000000000};
+
+	static double* wgtp[MAX_LINE_GLOB_PTS]={wgt1 ,wgt2 ,wgt3 ,wgt4 ,wgt5 };
+	static double* xip [MAX_LINE_GLOB_PTS]={xi1  ,xi2  ,xi3  ,xi4  ,xi5  };
+
+	static int np[MAX_LINE_GLOB_PTS]={sizeof(wgt1 )/sizeof(double),
+		sizeof(wgt2 )/sizeof(double),
+		sizeof(wgt3 )/sizeof(double),
+		sizeof(wgt4 )/sizeof(double),
+		sizeof(wgt5 )/sizeof(double)};
+
+	//	_printf_(true,"Gauss-Lobatto recurrence coefficients ngaus=%d\n",ngaus);
+	*pxgaus = (double *) xmalloc(ngaus*sizeof(double));
+	*pxwgt  = (double *) xmalloc(ngaus*sizeof(double));
+
+	/*  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=(double *) xmalloc(ngaus*sizeof(double));
+		beta =(double *) xmalloc(ngaus*sizeof(double));
+
+		/*  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 );
+		xfree((void **)&beta );
+		xfree((void **)&alpha);
+	}
+
+}/*}}}1*/
+/*FUNCTION GaussRecur{{{1*/
+void GaussRecur( double* zero, double* weight, int n, double* alpha, double* 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;
+	double p,g,r,s,c,f,b;
+	double* work;
+
+	if (n==1){
+		zero[0]  =alpha[0];
+		weight[0]=beta[0];
+		return;
+	}
+
+	work=(double*)xmalloc(n*sizeof(double));
+
+	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) {
+			xfree((void **)&work);
+			_error_("%s%i"," 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*/
+	xfree((void **)&work);
+
+}/*}}}1*/
+
+/*Element Gauss points TO BE REMOVED*/
+/*FUNCTION gaussQuad{{{1*/
+void gaussQuad( double** pxgaus, double** pxwgt, double** pegaus, double** 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);
+}/*}}}1*/
+/*FUNCTION gaussHexa{{{1*/
+void gaussHexa( double** pxgaus, double** pxwgt, double** pegaus, double** pewgt, double** pzgaus, double** 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);
+}/*}}}1*/
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.h	(revision 11330)
@@ -0,0 +1,22 @@
+/*!\file:  GaussPoints.h
+ * \brief
+ */ 
+
+#ifndef _GAUSSPOINTS_H
+#define _GAUSSPOINTS_H
+
+#define MAX_LINE_GAUS_PTS    4
+void GaussLegendreLinear( double** pxgaus, double** pxwgt, int ngaus ); 
+#define MAX_TRIA_SYM_ORD    20
+void GaussLegendreTria( int* pngaus, double** pl1, double** pl2, double** pl3, double** pwgt, int iord );
+#define MAX_TETRA_SYM_ORD    6
+void GaussLegendreTetra( int* pngaus, double** pl1, double** pl2, double** pl3, double** pl4, double** pwgt, int iord );
+#define MAX_LINE_GLOB_PTS    5
+void GaussLobatto( double** pxgaus, double** pxwgt, int ngaus ); 
+#define MAX_GAUS_ITER   30
+void GaussRecur( double* zero, double* weight, int n, double* alpha, double* beta );
+
+void gaussQuad( double** pxgaus, double** pxwgt, double** pegaus, double** pewgt, int nigaus, int njgaus );
+void gaussHexa( double** pxgaus, double** pxwgt, double** pegaus, double** pewgt, double** pzgaus, double** pzwgt, int nigaus, int njgaus, int nkgaus );
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/IsInputConverged.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/IsInputConverged.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/IsInputConverged.cpp	(revision 11330)
@@ -0,0 +1,59 @@
+/*!\file:  IsInputConverged.cpp
+ * \brief: figure out convergence at the input level. 
+ * We are given a list of inputs, new and old, and a criterion, and using the inputs, we 
+ * return the value of the criterion test, which will be used at the solution level 
+ * to determine convergence.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../objects/objects.h"
+
+void IsInputConverged(double* peps, Input** new_inputs,Input** old_inputs,int num_inputs,int criterion_enum){
+
+	int i,j;
+
+	/*output: */
+	double eps;
+	
+	/*intermediary: */
+	double *newvalues     = NULL;
+	double *oldvalues     = NULL;
+	int     num_values;
+	double  ndu        = 0;
+	double  nu         = 0;
+
+	if(criterion_enum==RelativeEnum){
+
+		/*conpute ndu/du (where u could be velocity, pressure, temperature, etc ...): */
+		for(i=0;i<num_inputs;i++){
+
+			/*in debugging mode, check that the inputs are of the same type*/
+			_assert_(new_inputs[i]->ObjectEnum()==old_inputs[i]->ObjectEnum());
+
+			/*Get pointers*/
+			new_inputs[i]->GetValuesPtr(&newvalues,&num_values);
+			old_inputs[i]->GetValuesPtr(&oldvalues,&num_values);
+			for(j=0;j<num_values;j++){
+				ndu+=pow(newvalues[j]-oldvalues[j],2);
+				nu+=pow(oldvalues[j],2);
+			}
+		}
+
+		/*take square root: */
+		ndu=sqrt(ndu);
+		nu=sqrt(nu);
+
+		/*now, compute eps: */
+		if(nu)eps=ndu/nu;
+		else eps=0;
+	}
+	else _error_("%s%s%s"," convergence criterion ",EnumToStringx(criterion_enum)," not supported yet!");
+
+	/*Assign output pointers:*/
+	*peps=eps;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/OptFunc.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/OptFunc.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/OptFunc.cpp	(revision 11330)
@@ -0,0 +1,41 @@
+/*!\file:  OptFunc.cpp
+ * \brief: "C" code wrapper to matlab objectivefunctionC call
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../objects/objects.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+
+#ifdef _SERIAL_
+#include "mex.h"
+double OptFunc(double scalar, OptArgs* optargs){
+	
+	/*output: */
+	double J;
+
+	mxArray*   inputs[2];
+	mxArray*   psearch_scalar=NULL;
+	mxArray*   mxJ=NULL;
+
+	psearch_scalar=mxCreateDoubleScalar(scalar);
+	inputs[0]=psearch_scalar;
+	inputs[1]=optargs->femmodel;
+
+	mexCallMATLAB(1,&mxJ,2,(mxArray**)inputs, optargs->function_name);
+
+	/*extract misfit from mxArray*/
+	J=mxGetScalar(mxJ);
+
+	return J;
+}
+#else
+double OptFunc(double scalar, OptArgs* optargs){
+	_error_(" not implemented yet");
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/OptimalSearch.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/OptimalSearch.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/OptimalSearch.cpp	(revision 11330)
@@ -0,0 +1,89 @@
+/*!\file:  OptimalSearch.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 "./numerics.h"
+#include "../../objects/objects.h"
+#include "../../io/io.h"
+#include "../../include/include.h"
+#include "../../shared/shared.h"
+#include <float.h>
+
+void OptimalSearch(double* psearch_scalar,double* pJ,OptPars* optpars,double (*f)(double,OptArgs*), OptArgs* optargs){
+
+	/* This routine is optimizing a given function*/
+
+	/*function values: */
+	double fx1,fx2,fxbest;
+	double x1,x2,xmin,xbest;
+
+	/*tolerances: */
+	double seps;
+	double tolerance=1.e-4;
+	int    maxiter;
+
+	/*counters: */
+	int  iter=0;
+	bool loop;
+
+	/*Recover parameters:*/
+	xmin     =optpars->xmin;
+	x1       =optpars->xmin;
+	x2       =optpars->xmax;
+	maxiter  =optpars->maxiter;
+	
+	//get the value of the function at the first boundary
+	fx1= (*f)(x1,optargs);
+	if (isnan(fx1)) _error_("Function evaluation returned NaN");
+	_printf_(VerboseControl(),"\n        Iteration         x           f(x)       Tolerance\n\n");
+	_printf_(VerboseControl(),"        %s    %12.6g  %12.6g  %s","   N/A",x1,fx1,"         N/A\n");
+
+	//update tolerances
+	seps=sqrt(DBL_EPSILON);
+
+	loop=true;
+	while(loop){
+
+		/*get f(x2)*/
+		iter++;
+		fx2 = (*f)(x2,optargs);
+		if (isnan(fx2)) _error_("Function evaluation returned NaN");
+		_printf_(VerboseControl(),"         %5i    %12.6g  %12.6g  %12.6g\n",iter,x2,fx2,fabs(x2-x1)>fabs(fx2-fx1)?fabs(fx2-fx1):fabs(x2-x1));
+
+		//Stop the optimization?
+		if ((fabs(x2-x1)+seps)<tolerance || (fabs(fx2-fx1)+seps)<tolerance){
+			_printf_(VerboseControl(),"      %s%g\n","optimization terminated: the current x satisfies the termination criteria using 'tolx' of " ,tolerance);
+			loop=false;
+		}
+		else if (iter>=maxiter){
+			_printf_(VerboseControl(),"      %s\n","exiting: Maximum number of iterations has been exceeded  - increase 'maxiter'\n");
+			loop=false;
+		}
+		else{
+			//continue
+			loop=true;
+		}
+
+		/*Compute x2*/
+		if(fx2<fx1){
+			xbest=x2; fxbest=fx2;
+			x1=x2;
+			x2=xmin+1.1*(x2-xmin); 
+			fx1=fx2;
+		}
+		else{
+			xbest=x1; fxbest=fx1;
+			x2=xmin+0.5*(x2-xmin);
+		}
+	}//end while
+
+	/*Assign output pointers: */
+	*psearch_scalar=xbest;
+	*pJ=fxbest;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/PetscOptionsFromAnalysis.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/PetscOptionsFromAnalysis.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/PetscOptionsFromAnalysis.cpp	(revision 11330)
@@ -0,0 +1,91 @@
+/*!\file:  PetscOptionsFromAnalysis.cpp
+ * \brief: change petsc options using analysis type and parameters
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../objects/objects.h"
+#include "../../Container/Parameters.h"
+#include "../../toolkits/toolkits.h"
+
+void PetscOptionsFromAnalysis(Parameters* parameters,int analysis_type){
+
+	int     dummy;
+	double* analyses=NULL;
+	char**  strings=NULL;
+	int     numanalyses;
+	char*   string=NULL;
+	int     found=-1;
+	int     i;
+
+	numanalyses=0;
+	parameters->FindParam(&strings,&numanalyses,PetscOptionsStringsEnum);
+
+	#ifdef _SERIAL_ //do not take this away, because ISSM loads analyses as a Double Param instead of a DoubleVec Param  when running with only 1 analysis
+	if(numanalyses==1){ analyses=(double*)xmalloc(1*sizeof(double)); parameters->FindParam(analyses,PetscOptionsAnalysesEnum);
+	}
+	else parameters->FindParam(&analyses,&dummy,PetscOptionsAnalysesEnum);
+	#else
+	parameters->FindParam(&analyses,&dummy,PetscOptionsAnalysesEnum);
+	#endif
+
+	if(numanalyses==0)return; //we did not find petsc options, don't bother.
+
+	/*ok, go through analyses and figure out if it corresponds to our analysis_type: */
+	found=-1;
+	for(i=0;i<numanalyses;i++){
+		if (analyses[i]==analysis_type){
+			/*found the analysis, get out of here: */
+			found=i;
+			break;
+		}
+	}
+	if(found==-1){
+		/*still haven't found a list of petsc options, go find the default one, for analysis type NoneAnalysisEnum: */
+		for(i=0;i<numanalyses;i++){
+			if (analyses[i]==NoneAnalysisEnum){
+				/*found the default analysis, get out of here: */
+				found=i;
+				break;
+			}
+		}
+	}
+	if (found==-1){
+		/*ok, we did not find anything, this is not good! error out: */
+		_error_("%s%s","could find neither a default analysis  nor analysis ",EnumToStringx(analysis_type));
+	}
+
+	/*ok, grab the petsc option string: */
+	string=strings[found];
+
+	/*now, reset the options database with this string. Taken from petsc/install/src/sys/objects/pinit.c. This 
+	 *capability is not covered by Petsc!: */
+
+	#if _PETSC_MAJOR_ == 2 
+	PetscOptionsDestroy();
+	PetscOptionsCreate();
+	//PetscOptionsCheckInitial_Private();
+	//PetscOptionsCheckInitial_Components();
+	PetscOptionsSetFromOptions();
+	PetscOptionsInsertMultipleString(string); //our patch
+	#else
+	PetscOptionsSetFromOptions();
+	PetscOptionsClear();
+	//PetscOptionsSetFromOptions();
+	PetscOptionsInsertMultipleString(string); //our patch
+	#endif
+
+
+	/*Free ressources*/
+	xfree((void**)&analyses);
+	for(i=0;i<numanalyses;i++){
+		string=strings[i];
+		xfree((void**)&string);
+	}
+	xfree((void**)&strings);
+
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/README
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/README	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/README	(revision 11330)
@@ -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/trunk-jpl-damage/src/c/shared/Numerics/Synchronize.sh
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/Synchronize.sh	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/Synchronize.sh	(revision 11330)
@@ -0,0 +1,202 @@
+#!/bin/bash
+#Synchronize Verbosity
+#first remove existing files
+rm $ISSM_TIER/src/m/shared/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 {{{1
+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 "../../include/macros.h"
+#include "../Exceptions/exceptions.h"
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+/*}}}*/
+
+/*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 Verbosity Matlab file{{{
+	cat <<END > $ISSM_TIER"/src/m/shared/"$(echo $FILENAME".m")
+function bool=$(echo $FILENAME)()
+%$(echo $FILENAME | awk {'print toupper($1)'}) - Return true if $(echo $LEVELNAME | awk {'print tolower($1)'}) level is activated
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Numerics/Synchronize.sh
+%            Please read src/c/shared/Numerics/README for more information
+%
+%   Usage:
+%      bool=$FILENAME()
+
+bool=logical(bitand(GetVerbosityLevel(),$BINARY));
+END
+	#}}}
+	#Add case to verbose.m FIELDS{{{
+	if [ $i -eq 1 ]; then cat <<END >> FIELDS
+		%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{{{1
+cat <<END >> Verbosity.cpp
+
+/*Verbosity Setup*/
+static int verbositylevel=-1;
+/*FUNCTION SetVerbosityLevel {{{*/
+void SetVerbosityLevel(int level){
+
+	if(level<0) _error_("vebosity level should be a positive integer (user provided %i)",level);
+
+#ifdef _SERIAL_
+
+	mxArray* output=NULL;
+	mxArray* input=NULL;
+	input=mxCreateDoubleScalar((double)level);
+
+	mexCallMATLAB(0,&output,1,&input,"SetVerbosityLevel");
+#else
+
+	verbositylevel = level;
+
+#endif
+}/*}}}*/
+/*FUNCTION GetVerbosityLevel {{{*/
+int  GetVerbosityLevel(void){
+#ifdef _SERIAL_
+
+	mxArray* output=NULL;
+	mxArray* input=NULL;
+	double   level;
+
+	mexCallMATLAB(1,&output,0,&input,"GetVerbosityLevel");
+	level=mxGetScalar(output);
+
+	verbositylevel = (int)level;
+
+#else
+
+	_assert_(verbositylevel>=0);
+	return verbositylevel;
+
+#endif
+}/*}}}*/
+END
+#}}}
+#Complete verbose.m {{{1
+VERBOSEPATH="$ISSM_TIER/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/trunk-jpl-damage/src/c/shared/Numerics/UnitConversion.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/UnitConversion.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/UnitConversion.cpp	(revision 11330)
@@ -0,0 +1,76 @@
+/*!\file:  UnitConversion.cpp
+ * \brief: convert units from the model to IU or from IU to the model.
+ */ 
+
+/*headers {{{1*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../Container/Container.h"
+#include "../../objects/objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+
+double UnitConversionScaleFactor(int type_enum);
+/*}}}*/
+
+void UnitConversion(double* values, int numvalues,int direction_enum, int type_enum){
+
+	double scale;
+	int i;
+
+	/*Get scaling factor: */
+	scale=UnitConversionScaleFactor(type_enum);
+
+	/*Now, which direction are we going? once determined, use scale factor: */
+	if(direction_enum==IuToExtEnum) for(i=0;i<numvalues;i++)values[i]=values[i]*scale; 
+	else if(direction_enum==ExtToIuEnum) for(i=0;i<numvalues;i++)values[i]=values[i]/scale; 
+	else _error_(" wrong direction for unit conversion, either IuToExtEnum or ExtToIuEnum. ");
+
+}
+
+double UnitConversion(double value, int direction_enum, int type_enum){
+
+	UnitConversion(&value,1,direction_enum,type_enum);
+
+	return value;
+}
+
+
+double UnitConversionScaleFactor(int type_enum){
+
+	double yts=365.0*24.0*3600.0;
+	
+	double scale;
+	switch(type_enum){
+		case TimesteppingTimeStepEnum: scale=1.0/yts;break; //yr
+		case TimesteppingFinalTimeEnum:    scale=1.0/yts;break; //yr
+		case TimeEnum:        scale=1.0/yts;break; //yr
+		case HydrologyWaterVxEnum: scale=yts;break; //m/yr
+		case HydrologyWaterVyEnum: scale=yts;break; //m/yr
+		case VxEnum:          scale=yts;break; //m/yr
+		case InversionVxObsEnum:       scale=yts;break; //m/yr
+		case VyEnum:          scale=yts;break; //m/yr
+		case InversionVyObsEnum:       scale=yts;break; //m/yr
+		case VzEnum:          scale=yts;break; //m/yr
+		case InversionVzObsEnum:       scale=yts;break; //m/yr
+		case VelEnum:         scale=yts;break; //m/yr
+		case InversionVelObsEnum:      scale=yts;break; //m/yr
+		case BalancethicknessThickeningRateEnum:  scale=yts;break; //m/yr
+		case BasalforcingsMeltingRateEnum:        scale=yts;break; //m/yr
+		case BasalforcingsMeltingRateCorrectionEnum: scale=yts;break; //m/yr
+		case SurfaceforcingsAccumulationRateEnum: scale=yts;break; //m/yr
+		case SurfaceforcingsAblationRateEnum:     scale=yts;break; //m/yr
+		case SurfaceforcingsMassBalanceEnum:      scale=yts;break; //m/yr
+		case MisfitEnum:      scale=pow(yts,2);break; //(m/yr)^2
+		case MassFluxEnum:    scale=pow((double)10,-12)*yts;break; // (GigaTon/year)
+		default: scale=1.0; break;
+	}
+	return scale;
+}
+
+
+
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/Verbosity.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/Verbosity.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/Verbosity.cpp	(revision 11330)
@@ -0,0 +1,73 @@
+/*
+* \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 "../../include/macros.h"
+#include "../Exceptions/exceptions.h"
+#ifdef _SERIAL_
+#include <mex.h>
+#endif
+/*}}}*/
+
+/*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*/
+
+/*Verbosity Setup*/
+static int verbositylevel=-1;
+/*FUNCTION SetVerbosityLevel {{{*/
+void SetVerbosityLevel(int level){
+
+	if(level<0) _error_("vebosity level should be a positive integer (user provided %i)",level);
+
+#ifdef _SERIAL_
+
+	mxArray* output=NULL;
+	mxArray* input=NULL;
+	input=mxCreateDoubleScalar((double)level);
+
+	mexCallMATLAB(0,&output,1,&input,"SetVerbosityLevel");
+#else
+
+	verbositylevel = level;
+
+#endif
+}/*}}}*/
+/*FUNCTION GetVerbosityLevel {{{*/
+int  GetVerbosityLevel(void){
+#ifdef _SERIAL_
+
+	mxArray* output=NULL;
+	mxArray* input=NULL;
+	double   level;
+
+	mexCallMATLAB(1,&output,0,&input,"GetVerbosityLevel");
+	level=mxGetScalar(output);
+
+	verbositylevel = (int)level;
+
+#else
+
+	_assert_(verbositylevel>=0);
+	return verbositylevel;
+
+#endif
+}/*}}}*/
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/Verbosity.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/Verbosity.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/Verbosity.h	(revision 11330)
@@ -0,0 +1,21 @@
+/*!\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);
+
+/*Setup Verbosity level*/
+void SetVerbosityLevel(int level);
+int  GetVerbosityLevel(void);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp	(revision 11330)
@@ -0,0 +1,53 @@
+#include "../Matlab/matlabshared.h"
+#include "../Alloc/alloc.h"
+#include "../../include/include.h"
+#include "../Exceptions/exceptions.h"
+#include <math.h>
+
+void XZvectorsToCoordinateSystem(double* T,double* xzvectors){
+
+	int		i,j;
+	double	x[3],y[3],z[3];
+	double	x_norm, y_norm, z_norm;
+
+	for(i=0;i<6;i++){
+		if(isnan(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/trunk-jpl-damage/src/c/shared/Numerics/cross.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/cross.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/cross.cpp	(revision 11330)
@@ -0,0 +1,20 @@
+/*!\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
+
+void cross(double* result,double* vector1,double* 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/trunk-jpl-damage/src/c/shared/Numerics/extrema.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/extrema.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/extrema.cpp	(revision 11330)
@@ -0,0 +1,27 @@
+/*!\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
+
+
+double min(double a,double b){
+	if (a<b)return a;
+	else return b;
+}
+int min(int a,int b){
+	if (a<b)return a;
+	else return b;
+}
+double max(double a,double b){
+	if (a>b)return a;
+	else return b;
+}
+int max(int a,int b){
+	if (a>b)return a;
+	else return b;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/isnan.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/isnan.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/isnan.cpp	(revision 11330)
@@ -0,0 +1,9 @@
+/*This routine only used by Intel compler: */
+#ifdef _INTEL_WIN_
+
+int isnan(double x){
+	if (x!=x)return 1;
+	else return 0;
+}
+#endif
+
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/isnan.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/isnan.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/isnan.h	(revision 11330)
@@ -0,0 +1,13 @@
+/*!\file:  isnan.h
+ * \brief: only used for intel compiler.
+ */ 
+
+#ifndef _ISNAN_INTEL_H_
+#define _ISNAN_INTEL_H_
+
+#ifdef _INTEL_WIN_
+int isnan(double X);
+#endif
+
+#endif
+
Index: /issm/trunk-jpl-damage/src/c/shared/Numerics/numerics.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Numerics/numerics.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Numerics/numerics.h	(revision 11330)
@@ -0,0 +1,32 @@
+/*!\file: numerics.h
+ * \brief prototypes for numerics.h
+ */ 
+
+#ifndef _NUMERICS_H_
+#define  _NUMERICS_H_
+
+#include "./Verbosity.h"
+#include "./GaussPoints.h"
+#include "./isnan.h"
+
+class Input;
+class Parameters;
+
+struct OptArgs;
+struct OptPars;
+
+double min(double a,double b);
+double max(double a,double b);
+int    min(int a,int b);
+int    max(int a,int b);
+double OptFunc(double scalar, OptArgs* optargs);
+void   BrentSearch(double* psearch_scalar,double* pJ,OptPars* optpars,double (*f)(double,OptArgs*), OptArgs* optargs);
+void   OptimalSearch(double* psearch_scalar,double* pJ,OptPars* optpars,double (*f)(double,OptArgs*), OptArgs* optargs);
+void   cross(double* result,double* vector1,double* vector2);
+void   IsInputConverged(double* peps, Input** new_inputs,Input** old_inputs,int num_inputs,int criterion_enum);
+void   UnitConversion(double* values, int numvalues,int direction_enum, int type_enum);
+double UnitConversion(double value, int direction_enum, int type_enum);
+void   PetscOptionsFromAnalysis(Parameters* parameters,int analysis_type);
+void   XZvectorsToCoordinateSystem(double* T,double* xzvectors);
+
+#endif //ifndef _NUMERICS_H_
Index: /issm/trunk-jpl-damage/src/c/shared/Sorting/Quicksort.c
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Sorting/Quicksort.c	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Sorting/Quicksort.c	(revision 11330)
@@ -0,0 +1,19 @@
+void swap(int *a, int *b) {
+	int t=*a; *a=*b; *b=t;
+}
+void sort(int arr[], int beg, int end) {
+	  
+	if (end > beg + 1) {
+		int piv = arr[beg], l = beg + 1, r = end;
+		while (l < r)
+		{
+			if (arr[l] <= piv)
+				l++;
+			else
+				swap(&arr[l], &arr[--r]);
+		}
+		swap(&arr[--l], &arr[beg]);
+		sort(arr, beg, l);
+		sort(arr, r, end);
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Sorting/binary_search.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Sorting/binary_search.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Sorting/binary_search.cpp	(revision 11330)
@@ -0,0 +1,66 @@
+/*!\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 <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;
+
+	// 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/trunk-jpl-damage/src/c/shared/Sorting/sorting.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Sorting/sorting.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Sorting/sorting.h	(revision 11330)
@@ -0,0 +1,12 @@
+/*!\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);
+
+
+#endif //ifndef _SORTING_H_
+
Index: /issm/trunk-jpl-damage/src/c/shared/String/DescriptorIndex.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/String/DescriptorIndex.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/String/DescriptorIndex.cpp	(revision 11330)
@@ -0,0 +1,71 @@
+/*!\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 "../shared.h"
+#include "../../EnumDefinitions/EnumDefinitions.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_("%s%s%s"," descriptor ",descriptor," is not correctly formatted!");
+
+	if (strncmp(pch,"scaled",6)==0){
+		/*we have a scaled variable. recover the root: */
+		pch = strtok (NULL, "_");
+		if(!pch)_error_("%s%s%s"," scaled descriptor ",descriptor," is not correctly formatted!");
+		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_("%s%s%s"," indexed descriptor ",descriptor," is not correctly formatted!");
+		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
+		/*now recover  the index: */
+		pch = strtok (NULL, "_");
+		if(!pch)_error_("%s%s%s"," indexed descriptor ",descriptor," is not correctly formatted!");
+		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_("%s%s%s"," nodal descriptor ",descriptor," is not correctly formatted!");
+		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
+		/*now recover  the index: */
+		pch = strtok (NULL, "_");
+		if(!pch)_error_("%s%s%s"," nodal descriptor ",descriptor," is not correctly formatted!");
+		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/trunk-jpl-damage/src/c/shared/String/sharedstring.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/String/sharedstring.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/String/sharedstring.h	(revision 11330)
@@ -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);
+
+#endif //ifndef _SHAREDSTRING_H_
+
Index: /issm/trunk-jpl-damage/src/c/shared/String/stricmp.c
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/String/stricmp.c	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/String/stricmp.c	(revision 11330)
@@ -0,0 +1,11 @@
+/* \file stricmp.cpp
+ * \brief bypass non-standard stricmp
+ */
+
+#ifndef WIN32
+
+#include <strings.h>
+int stricmp(const char* a,const char* b){
+	return  strcasecmp(a,b);
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/shared/Threads/LaunchThread.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Threads/LaunchThread.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Threads/LaunchThread.cpp	(revision 11330)
@@ -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 "../Alloc/alloc.h"
+#include "../Exceptions/exceptions.h"
+#include "../../include/include.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;
+	
+	/*dynamically allocate: */
+	threads=(pthread_t*)xmalloc(num_threads*sizeof(pthread_t));
+	handles=(pthread_handle*)xmalloc(num_threads*sizeof(pthread_handle));
+
+	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:*/
+	xfree((void**)&threads);
+	xfree((void**)&handles);
+
+	#else
+	pthread_handle handle;
+	handle.gate=gate;
+	handle.id=0;
+	handle.num=1;
+	
+	function((void*)&handle);
+	#endif
+
+}
Index: /issm/trunk-jpl-damage/src/c/shared/Threads/PartitionRange.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Threads/PartitionRange.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Threads/PartitionRange.cpp	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\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/trunk-jpl-damage/src/c/shared/Threads/issm_threads.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/Threads/issm_threads.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/Threads/issm_threads.h	(revision 11330)
@@ -0,0 +1,22 @@
+/*!\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/trunk-jpl-damage/src/c/shared/TriMesh/AssociateSegmentToElement.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/TriMesh/AssociateSegmentToElement.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/TriMesh/AssociateSegmentToElement.cpp	(revision 11330)
@@ -0,0 +1,33 @@
+/*!\file:  AssociateSegmentToElement.cpp
+ * \brief for each segment, look for the corresponding element.
+ */ 
+
+#include "./trimesh.h"
+
+int AssociateSegmentToElement(double** psegments,int nseg, double* index,int nel){
+	
+	/*Error management: */
+	int i;
+	int noerr=1;
+
+	/*Input: */
+	double* segments=NULL;
+
+	/*node indices: */
+	double A,B;
+
+	/*Recover segments: */
+	segments=*psegments;
+
+	for (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 noerr;
+}
+
+
Index: /issm/trunk-jpl-damage/src/c/shared/TriMesh/GridInsideHole.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/TriMesh/GridInsideHole.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/TriMesh/GridInsideHole.cpp	(revision 11330)
@@ -0,0 +1,53 @@
+/*
+ * 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;
+	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);
+	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/trunk-jpl-damage/src/c/shared/TriMesh/OrderSegments.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/TriMesh/OrderSegments.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/TriMesh/OrderSegments.cpp	(revision 11330)
@@ -0,0 +1,53 @@
+/*
+ * OrderSegments.c: 
+ * reorder segments so that their normals point outside the domain outline.
+ */
+#include "./trimesh.h"
+
+int OrderSegments(double** psegments,int nseg, double* index,int nel){
+	
+	/*Error management: */
+	int i;
+	int noerr=1;
+
+	/*Input: */
+	double* segments=NULL;
+
+	/*vertex indices: */
+	double A,B;
+	/*element indices: */
+	int el;
+
+
+	/*Recover segments: */
+	segments=*psegments;
+
+	for (i=0;i<nseg;i++){
+		A=segments[3*i+0];
+		B=segments[3*i+1];
+		el=(int)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 noerr;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/TriMesh/SplitMeshForRifts.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/TriMesh/SplitMeshForRifts.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/TriMesh/SplitMeshForRifts.cpp	(revision 11330)
@@ -0,0 +1,108 @@
+/*
+ * SplitMeshForRifts.c:
+ */
+#include "./trimesh.h"
+
+#include "../Alloc/alloc.h"
+
+int SplitMeshForRifts(int* pnel,double** pindex,int* pnods,double** px,double** py,int* pnsegs,double** psegments,double** psegmentmarkerlist){
+
+	/*Some notes on dimensions: 
+	index  of size nelx3
+	x and y of size nodsx1
+	segments of size nsegsx3*/
+	
+	/*Error management: */
+	int noerr=1;
+	
+	int i,j,k,l;
+	int node;
+	int el;
+
+	int  nriftsegs;
+	int* riftsegments=NULL; 
+	int* flags=NULL;
+	
+	int  NumGridElementListOnOneSideOfRift;
+	int* GridElementListOnOneSideOfRift=NULL;
+
+	/*Input: */
+	int     nel;
+	double* index=NULL;
+	int     nods;
+	double* x=NULL;
+	double* y=NULL;
+	double* segments=NULL;
+	double*    segmentmarkerlist=NULL;
+	int     nsegs;
+
+	/*Recover input: */
+	nel=*pnel;
+	index=*pindex;
+	nods=*pnods;
+	x=*px;
+	y=*py;
+	nsegs=*pnsegs;
+	segments=*psegments;
+	segmentmarkerlist=*psegmentmarkerlist;
+
+
+	/*Establish list of segments that belong to a rift: */
+	RiftSegmentsFromSegments(&nriftsegs,&riftsegments,nel,index,nsegs,segments); /*riftsegments of size nriftsegsx4 (4 for first element on segment,second element, 
+																				   first node and second snode)*/
+
+	/*Go through all nodes of the rift segments, and start splitting the mesh: */
+	flags=(int*)xcalloc(nods,sizeof(int)); //to make sure we don't split the same nodes twice!
+	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.*/
+				
+				//augment number of nodes 
+				nods=nods+1;
+				//create new node
+				x=(double*)xrealloc(x,nods*sizeof(double));
+				y=(double*)xrealloc(y,nods*sizeof(double));
+				x[nods-1]=x[node-1]; //matlab indexing
+				y[nods-1]=y[node-1]; //matlab indexing
+
+				//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);
+
+	/*Assign output pointers: */
+	*pnel=nel;
+	*pindex=index;
+	*pnods=nods;
+	*px=x;
+	*py=y;
+	*pnsegs=nsegs;
+	*psegments=segments;
+	*psegmentmarkerlist=segmentmarkerlist;
+	return noerr;
+}
Index: /issm/trunk-jpl-damage/src/c/shared/TriMesh/TriMeshUtils.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 11330)
@@ -0,0 +1,1220 @@
+/*
+ * TriMeshUtils: mesh manipulation routines: 
+ */
+
+#include <stdio.h>
+
+#include "./trimesh.h"
+#include "../Exceptions/exceptions.h"
+#include "../Alloc/alloc.h"
+#include "../../include/include.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,double * 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=(int*)xmalloc(max_number_elements*sizeof(int));
+
+	for (i=0;i<nel;i++){
+		for (j=0;j<3;j++){
+			if ((int)*(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=(int*)xrealloc(GridElements,(current_size+max_number_elements)*sizeof(int));
+					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){
+		xfree((void**)&GridElements);
+	}
+	/*Allocate return pointers: */
+	*pGridElements=GridElements;
+	*pNumGridElements=NumGridElements;
+	return noerr;
+}
+
+
+int IsNeighbor(int el1,int el2,double* 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;
+}
+
+
+/******************************************************************************************************************************
+                                   RiftSegmentsFromSegments
+******************************************************************************************************************************/
+
+int RiftSegmentsFromSegments(int* pnriftsegs, int** priftsegments, int nel, double* index, int nsegs,double* segments){
+	
+	int i,counter;
+	int el,el2;
+	
+	int  nriftsegs;
+	int* riftsegments=NULL;
+	int* riftsegments_uncompressed=NULL; 
+	double element_nodes[3];
+
+	/*Allocate segmentflags: */
+	riftsegments_uncompressed=(int*)xcalloc(nsegs*5,sizeof(int));
+
+	/*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)=(int)*(segments+3*i+0);
+		    *(riftsegments_uncompressed+5*i+4)=(int)*(segments+3*i+1);
+			nriftsegs++;
+		}
+	}
+
+	/*Compress riftsegments_uncompressed:*/
+	riftsegments=(int*)xmalloc(nriftsegs*4*sizeof(int));
+	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++;
+		}
+	}
+
+	xfree((void**)&riftsegments_uncompressed);
+	
+	/*Assign output pointers: */
+	*priftsegments=riftsegments;
+	*pnriftsegs=nriftsegs;
+}
+
+/******************************************************************************************************************************
+                                   DetermineGridElementListOnOneSideOfRift
+******************************************************************************************************************************/
+
+int DetermineGridElementListOnOneSideOfRift(int* pNumGridElementListOnOneSideOfRift, int** pGridElementListOnOneSideOfRift, int segmentnumber, int nriftsegs, int* riftsegments, int node,double* 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=(int*)xmalloc(NumGridElements*sizeof(int));
+	//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: */
+	xfree((void**)&GridElements);
+	/*Assign output pointers: */
+	*pNumGridElementListOnOneSideOfRift=NumGridElementListOnOneSideOfRift;
+	*pGridElementListOnOneSideOfRift=GridElementListOnOneSideOfRift;
+	return noerr;
+}
+
+/******************************************************************************************************************************
+                                   UpdateSegments
+******************************************************************************************************************************/
+
+int UpdateSegments(double** psegments,double** psegmentmarkerlist, int* pnsegs, double* index, double* x,double* y,int* riftsegments,int nriftsegs){
+
+	int noerr=1;
+	int i,j,k;
+	int el1,el2;
+
+	double* segments=NULL;
+	double*    segmentmarkerlist=NULL;
+	int     nsegs;
+
+	/*Recover input: */
+	segments=*psegments;
+	segmentmarkerlist=*psegmentmarkerlist;
+	nsegs=*pnsegs;
+
+	/*Reallocate segments: */
+	segments=(double*)xrealloc(segments,(nsegs+nriftsegs)*3*sizeof(double));
+	segmentmarkerlist=(double*)xrealloc(segmentmarkerlist,(nsegs+nriftsegs)*sizeof(double));
+
+	/*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[(int)*(index+el1*3+k)-1]==x[(int)*(segments+3*j+0)-1]) && (y[(int)*(index+el1*3+k)-1]==y[(int)*(segments+3*j+0)-1])){
+						*(segments+3*j+0)=*(index+el1*3+k);
+						break;
+					}
+				}
+				for (k=0;k<3;k++){
+					if ((x[(int)*(index+el1*3+k)-1]==x[(int)*(segments+3*j+1)-1])  && (y[(int)*(index+el1*3+k)-1]==y[(int)*(segments+3*j+1)-1])){
+						*(segments+3*j+1)=*(index+el1*3+k);
+						break;
+					}
+				}
+				/*Deal with el2: */
+				*(segments+3*(nsegs+i)+2)=el2+1;
+				*(segmentmarkerlist+(nsegs+i))=*(segmentmarkerlist+j);
+				for (k=0;k<3;k++){
+					if ((x[(int)*(index+el2*3+k)-1]==x[(int)*(segments+3*j+0)-1]) && (y[(int)*(index+el2*3+k)-1]==y[(int)*(segments+3*j+0)-1])){
+						*(segments+3*(nsegs+i)+0)=*(index+el2*3+k);
+						break;
+					}
+				}
+				for (k=0;k<3;k++){
+					if ((x[(int)*(index+el2*3+k)-1]==x[(int)*(segments+3*j+1)-1]) && (y[(int)*(index+el2*3+k)-1]==y[(int)*(segments+3*j+1)-1])){
+						*(segments+3*(nsegs+i)+1)=*(index+el2*3+k);
+						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[(int)*(index+el2*3+k)-1]==x[(int)*(segments+3*j+0)-1]) && (y[(int)*(index+el2*3+k)-1]==y[(int)*(segments+3*j+0)-1])){
+						*(segments+3*j+0)=*(index+el2*3+k);
+						break;
+					}
+				}
+				for (k=0;k<3;k++){
+					if ((x[(int)*(index+el2*3+k)-1]==x[(int)*(segments+3*j+1)-1]) && (y[(int)*(index+el2*3+k)-1]==y[(int)*(segments+3*j+1)-1])){
+						*(segments+3*j+1)=*(index+el2*3+k);
+						break;
+					}
+				}
+				/*Deal with el1: */
+				*(segments+3*(nsegs+i)+2)=el1+1;
+				*(segmentmarkerlist+(nsegs+i))=*(segmentmarkerlist+j);
+				for (k=0;k<3;k++){
+					if ((x[(int)*(index+el1*3+k)-1]==x[(int)*(segments+3*j+0)-1]) && (y[(int)*(index+el1*3+k)-1]==y[(int)*(segments+3*j+0)-1])){
+						*(segments+3*(nsegs+i)+0)=*(index+el1*3+k);
+						break;
+					}
+				}
+				for (k=0;k<3;k++){
+					if ((x[(int)*(index+el1*3+k)-1]==x[(int)*(segments+3*j+1)-1]) && (y[(int)*(index+el1*3+k)-1]==y[(int)*(segments+3*j+1)-1])){
+						*(segments+3*(nsegs+i)+1)=*(index+el1*3+k);
+						break;
+					}
+				}
+			}
+		}
+	}
+	nsegs+=nriftsegs;
+
+	/*Assign output pointers: */
+	*psegments=segments;
+	*psegmentmarkerlist=segmentmarkerlist;
+	*pnsegs=nsegs;
+	
+	return noerr;
+}
+
+/******************************************************************************************************************************
+                                   pnpoly
+******************************************************************************************************************************/
+int pnpoly(int npol, double *xp, double *yp, double x, double y) {
+	int i, j, c = 0;
+	for (i = 0, j = npol-1; i < npol; j = i++) {
+		if ((((yp[i]<=y) && (y<yp[j])) ||
+					((yp[j]<=y) && (y<yp[i]))) &&
+				(x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i]))
+			c = !c;
+	}
+	return c;
+}
+
+/******************************************************************************************************************************
+                                   IsInPoly
+******************************************************************************************************************************/
+int IsInPoly(double* in,double* xc,double* yc,int numnodes,double* x,double* y,int nods){
+
+	int i;
+	double x0,y0;
+
+	/*Go through all nodes of the mesh:*/
+	for (i=0;i<nods;i++){
+		if (in[i]){
+			/*this node already is inside one of the contours, continue*/
+			continue;
+		}
+		/*pick up node: */
+		x0=x[i];
+		y0=y[i];
+		if (pnpoly(numnodes,xc,yc,x0,y0)){
+			in[i]=1;
+		}
+	}
+}
+
+/******************************************************************************************************************************
+                                   FindElement
+******************************************************************************************************************************/
+
+int FindElement(double A,double B,double* index,int nel){
+
+	int n;
+	int el=-1;
+	for (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;
+}
+/******************************************************************************************************************************
+                                   SplitRiftSegments
+******************************************************************************************************************************/
+
+int SplitRiftSegments(double** psegments,double** psegmentmarkerlist, int* pnumsegs, int* pnumrifts,int** priftsnumsegs,double*** priftssegments,int numrifts){
+
+	/*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: */
+	double* segments=NULL;
+	double* segmentmarkerlist=NULL;
+	int numsegs;
+	
+	/*output: */
+	int* riftsnumsegs=NULL;
+	double** riftssegments=NULL;
+	int new_numsegs;
+	double* new_segments=NULL;
+	double* new_segmentmarkers=NULL;
+
+	/*intermediary: */
+	double* 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=(double*)xmalloc(new_numsegs*3*sizeof(double));
+	new_segmentmarkers=(double*)xmalloc(new_numsegs*sizeof(double));
+
+	/*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=(int*)xmalloc(numrifts*sizeof(int));
+	riftssegments=(double**)xmalloc(numrifts*sizeof(double*));
+	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=(double*)xmalloc(counter*3*sizeof(double));
+		/*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);
+				*(riftsegment+3*counter+1)=*(segments+3*j+1);
+				*(riftsegment+3*counter+2)=*(segments+3*j+2);
+				counter++;
+			}
+		}
+		*(riftssegments+i)=riftsegment;
+	}
+
+	/*Free ressources: */
+	xfree((void**)&segments);
+
+	/*Assign output pointers: */
+	*psegments=new_segments;
+	*psegmentmarkerlist=new_segmentmarkers;
+	*pnumsegs=new_numsegs;
+	*pnumrifts=numrifts;
+	*priftssegments=riftssegments;
+	*priftsnumsegs=riftsnumsegs;
+	return noerr;
+}
+
+/******************************************************************************************************************************
+                                   PairRiftElements
+******************************************************************************************************************************/
+
+int PairRiftElements(int** priftsnumpairs, double*** priftspairs,int numrifts,int* riftsnumsegments, double** riftssegments,double* x,double* y){
+
+
+	int noerr=1;
+	int i,j,k;
+
+	/*output: */
+	int* riftsnumpairs=NULL;
+	double** riftspairs=NULL;
+
+	/*intermediary :*/
+	int     numsegs;
+	double* segments=NULL;
+	double* pairs=NULL;
+	int     node1,node2,node3,node4;
+
+	riftsnumpairs=(int*)xmalloc(numrifts*sizeof(int));
+	riftspairs=(double**)xmalloc(numrifts*sizeof(double*));
+	for (i=0;i<numrifts;i++){
+		segments=riftssegments[i];
+		numsegs=riftsnumsegments[i];
+		riftsnumpairs[i]=numsegs;
+		pairs=(double*)xmalloc(2*numsegs*sizeof(double));
+		for (j=0;j<numsegs;j++){
+			*(pairs+2*j+0)=*(segments+3*j+2); //retrieve element to which this segment belongs.
+			node1=(int)*(segments+3*j+0)-1; node2=(int)*(segments+3*j+1)-1;
+			/*Find element facing on other side of rift: */
+			for (k=0;k<numsegs;k++){
+				if (k==j)continue;
+				node3=(int)*(segments+3*k+0)-1; node4=(int)*(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;
+}
+
+
+/******************************************************************************************************************************
+                                   RemoveRifts
+******************************************************************************************************************************/
+
+double dabs(double x){
+	if (x<0)x=-x;
+	return x;
+}
+int RemoveRifts(double** pindex,double** px,double** py,int* pnods,double** psegments,int* pnumsegs,int numrifts1,int* rifts1numsegs,double** rifts1segments,double** rifts1pairs,int nel){
+
+	int noerr=1;
+	int i,j,k,counter,counter1,counter2;
+
+	/*input: */
+	double* index=NULL;
+	double* x=NULL;
+	double* y=NULL;
+	int     nods;
+	double* segments=NULL;
+	int     numsegs;
+
+	/*intermediary: */
+	double* riftsegments=NULL;
+	double* riftpairs=NULL;
+	int     node1,node2,node3,node4,temp_node;
+	double  el2;
+	int     newnods; //temporary # node counter.
+	double  xmin,ymin;
+	double* xreal=NULL;
+	double* yreal=NULL;
+	int* nodes=NULL;
+	int* mergingnodes=NULL;
+	int     max_size;
+	int     redundant;
+
+
+	/*Recover input: */
+	index=*pindex;
+	x=*px;
+	y=*py;
+	nods=*pnods;;
+	segments=*psegments;
+	numsegs=*pnumsegs;
+
+	/*initialize newnods : */
+	newnods=nods;
+
+	/*Figure out a unique value to flag x and y for node removal: */
+	xmin=x[0];
+	ymin=y[0];
+	for (i=0;i<nods;i++){
+		if (x[i]<xmin)xmin=x[i];
+		if (y[i]<ymin)ymin=y[i];
+	}
+	xmin=xmin-dabs(xmin); 
+	ymin=ymin-dabs(ymin);
+
+	/*Initialize two arrays, one for nodes that are going to be merged, the other with corresponding nodes being merge into: */
+	max_size=0;
+	for (i=0;i<numrifts1;i++){
+		max_size+=rifts1numsegs[i];
+	}
+	nodes=(int*)xmalloc(max_size*sizeof(int));
+	mergingnodes=(int*)xmalloc(max_size*sizeof(int));
+
+	/*Go through the rifts segments, and identify which node we are going to merge with its counterpart on the other side 
+	 *of the rift. The way we identify this node is by looking at the element pairs, and the corresponding nodes: */
+	counter=0;
+	for (i=0;i<numrifts1;i++){
+		riftsegments=rifts1segments[i];
+		riftpairs=rifts1pairs[i];
+		for (j=0;j<rifts1numsegs[i];j++){
+			el2=*(riftpairs+2*j+1);
+			node1=(int)*(riftsegments+3*j+0);
+			node2=(int)*(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<rifts1numsegs[i];k++){
+				if (*(riftsegments+3*k+2)==el2){
+					node3=(int)*(riftsegments+3*k+0);
+					node4=(int)*(riftsegments+3*k+1);
+					break;
+				}
+			}
+			/* Make sure node3 faces node1 and node4 faces node2: */
+			if ((x[node1]==x[node4]) && (y[node1]==y[node4])){
+				/*Swap node3 and node4:*/
+				temp_node=node3;
+				node3=node4;
+				node4=temp_node;
+			}
+			/* Is any of these two node pairs on the tip of a rift, in which case, we don't include it in nodes or mergingnodes: */
+			if ((node1==node3) || (node2==node4)){
+				if(node1!=node3){
+					/*Add node1 and node3 to nodes and mergingnodes if they have not already been added: */
+					redundant=0;
+					for (k=0;k<counter;k++){
+						if ((mergingnodes[k]==node1) || (nodes[k]==node1))redundant=1;
+					}
+					if(!redundant){
+						/*Ok, add node1 to nodes, and node3 to mergingnodes: */
+						nodes[counter]=node1;
+						mergingnodes[counter]=node3;
+						counter++;
+					}
+				}
+				if(node2!=node4){
+					/*Add node2 and node4 to nodes and mergingnodes if they have not already been added: */
+					redundant=0;
+					for (k=0;k<counter;k++){
+						if ((mergingnodes[k]==node2) || (nodes[k]==node2))redundant=1;
+					}
+					if(!redundant){
+						/*Ok, add node2 to nodes, and node4 to mergingnodes: */
+						nodes[counter]=node2;
+						mergingnodes[counter]=node4;
+						counter++;
+					}
+				}
+			}
+			else{
+				/*Check that node1 is not already present in the mergingnodes: */
+				redundant=0;
+				for (k=0;k<counter;k++){
+					if ((mergingnodes[k]==node1) || (nodes[k]==node1))redundant=1;
+				}
+				if(!redundant){
+					/*Ok, add node1 to nodes, and node3 to mergingnodes: */
+					nodes[counter]=node1;
+					mergingnodes[counter]=node3;
+					counter++;
+				}
+				/*Check that node2 is not already present in the mergingnodes: */
+				redundant=0;
+				for (k=0;k<counter;k++){
+					if ((mergingnodes[k]==node1) || (nodes[k]==node1))redundant=1;
+				}
+				if(!redundant){
+					/*Ok, add node2 to nodes, and node4 to mergingnodes: */
+					nodes[counter]=node2;
+					mergingnodes[counter]=node4;
+					counter++;
+				}
+			}
+		}
+	}
+
+	/*Ok, we have counter pairs of nodes (nodes and mergingnodes): start merging nodes in the triangulation: */
+	newnods=nods;
+	for (i=0;i<counter;i++){
+		node1=nodes[i];
+		node3=mergingnodes[i];
+		/*Merge node3 into node1: */ 
+		x[node3]=xmin; //flag  for later removal from x
+		y[node3]=ymin; //flag  for later removal from y
+		newnods--;
+		for (k=0;k<nel;k++){
+			if (*(index+3*k+0)==node3)*(index+3*k+0)=node1;
+			if (*(index+3*k+1)==node3)*(index+3*k+1)=node1;
+			if (*(index+3*k+2)==node3)*(index+3*k+2)=node1;
+		}
+	}
+
+	/*Reallocate x and y: */
+	xreal=(double*)xrealloc(x,newnods*sizeof(double));
+	yreal=(double*)xrealloc(y,newnods*sizeof(double));
+	counter1=0;
+	counter2=0;
+	for (i=0;i<nods;i++){
+		if (x[i]!=xmin){
+			xreal[counter1]=x[i];
+			counter1++;
+		}
+		if (y[i]!=ymin){
+			yreal[counter2]=y[i];
+			counter2++;
+		}
+	}
+	xfree((void**)&x); x=xreal;
+	xfree((void**)&y); y=yreal;
+
+	/*Assign output pointers:*/
+	*pindex=index;
+	*px=x;
+	*py=y;
+	*pnods=newnods;
+	*psegments=segments;
+	*pnumsegs=numsegs;
+
+	return noerr;
+}
+
+/******************************************************************************************************************************
+                                   IsRiftPresent
+******************************************************************************************************************************/
+
+int IsRiftPresent(int* priftflag,int* pnumrifts, double* segmentmarkerlist,int nsegs){
+
+	int i;
+	int noerr=1;
+	
+	/*output: */
+	int riftflag=0;
+	int numrifts=0;
+
+	double 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;
+}
+
+/******************************************************************************************************************************
+                                   OrderRifts
+******************************************************************************************************************************/
+
+int OrderRifts(double** priftstips, double** riftssegments,double** riftspairs,int numrifts,int* riftsnumsegments,double* x,double* y){
+	
+	int noerr=1;
+	int i,j,k,counter;
+
+	/*intermediary: */
+	double* riftsegments=NULL;
+	double* riftpairs=NULL;
+	int numsegs;
+
+	/*ordering and copy: */
+	int*    order=NULL;
+	double* riftsegments_copy=NULL;
+	double* riftpairs_copy=NULL;
+
+	/*node and element manipulation: */
+	int     node1,node2,node3,node4,temp_node,tip1,tip2,node;
+	double  el2;
+	int     already_ordered=0;
+
+	/*output: */
+	double* riftstips=NULL;
+
+
+	/*Allocate byproduct of this routine, riftstips: */
+	riftstips=(double*)xmalloc(numrifts*2*sizeof(double));
+
+	/*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=(double*)xmalloc(numsegs*3*sizeof(double));
+		riftpairs_copy=(double*)xmalloc(numsegs*2*sizeof(double));
+		order=(int*)xmalloc(numsegs*sizeof(int));
+
+		/*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=(int)*(riftsegments+3*j+0);
+			node2=(int)*(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=(int)*(riftsegments+3*k+0);
+					node4=(int)*(riftsegments+3*k+1);
+					break;
+				}
+			}
+			/* Make sure node3 faces node1 and node4 faces node2: */
+			if ((x[node1]==x[node4]) && (y[node1]==y[node4])){
+				/*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)=(double)tip1;
+		*(riftstips+2*i+1)=(double)tip2;
+
+
+		/*We have the two tips for this rift.  Go from tip1 to tip2, and figure out the order in which segments are sequential. 
+		 *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=(int)*(riftsegments+3*j+0);
+				node2=(int)*(riftsegments+3*j+1);
+				
+				if ((node1==node) || (node2==node)){
+					/*Ok, this segment is connected to node, plug its index into order, unless we already plugged it before: */
+					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);
+		}
+
+		xfree((void**)&order);
+		xfree((void**)&riftsegments_copy);
+		xfree((void**)&riftpairs_copy);
+
+	}
+
+	/*Assign output pointer:*/
+	*priftstips=riftstips;
+	return noerr;
+}
+
+/******************************************************************************************************************************
+                                   PenaltyPairs
+******************************************************************************************************************************/
+
+int PenaltyPairs(double*** priftspenaltypairs,int** priftsnumpenaltypairs,int numrifts,double** riftssegments,
+		int* riftsnumsegs,double** riftspairs,double* 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;
+	double* riftsegments=NULL;
+	double* riftpairs=NULL;
+	int counter;
+	double normal[2];
+	double length;
+	int    k1,k2;
+
+	/*Allocate: */
+	riftspenaltypairs=(double**)xmalloc(numrifts*sizeof(double*));
+	riftsnumpenaltypairs=(int*)xmalloc(numrifts*sizeof(int));
+
+	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=(double*)xcalloc((numsegs/2-1)*RIFTPENALTYPAIRSWIDTH,sizeof(double));
+		
+		/*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( *(riftpenaltypairs+j*7+4),2) + pow( *(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;
+}
+
+/******************************************************************************************************************************
+                                   RemoveCorners
+******************************************************************************************************************************/
+
+int RemoveCornersFromRifts(double** pindex,int* pnel,double** px,double** py,int* pnods, double* segments,double* segmentmarkers,int num_seg){
+
+	int noerr=1;
+	int i,j,k;
+	double node1,node2,node3;
+	int el;
+
+	/*input: */
+	double* index=NULL;
+	int     nel;
+	double* x=NULL;
+	double* y=NULL;
+	int     nods;
+	double  pair[2];
+	int     pair_count=0;
+	int     triple=0;
+
+	/*Recover input: */
+	index=*pindex;
+	nel=*pnel;
+	x=*px;
+	y=*py;
+	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=(double*)xrealloc(x,(nods+1)*sizeof(double));
+					y=(double*)xrealloc(y,(nods+1)*sizeof(double));
+					x[nods]=(x[(int)node1-1]+x[(int)node2-1]+x[(int)node3-1])/3;
+					y[nods]=(y[(int)node1-1]+y[(int)node2-1]+y[(int)node3-1])/3;
+
+					index=(double*)xrealloc(index,(nel+2)*3*sizeof(double));
+					/*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)==(double)(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)=(double)(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)=(double)(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)=(double)(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/trunk-jpl-damage/src/c/shared/TriMesh/trimesh.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/TriMesh/trimesh.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/TriMesh/trimesh.h	(revision 11330)
@@ -0,0 +1,44 @@
+/*!\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(double** psegments,int nseg, double* index,int nel);
+int OrderSegments(double** psegments,int nseg, double* index,int nel);
+		
+int GridInsideHole(double* px0,double* py0,int n,double* x,double* y);
+int FindElement(double A,double B,double* index,int nel);
+
+int SplitMeshForRifts(int* pnel,double** pindex,int* pnods,double** px,double** py,int* pnsegs,double** psegments,double** 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,double* index);
+int IsOnRift(int el,int nriftsegs,int* riftsegments);
+int RiftSegmentsFromSegments(int* pnriftsegs, int** priftsegments, int nel, double* index, int nsegs,double* segments);
+int DetermineGridElementListOnOneSideOfRift(int* pNumGridElementListOnOneSideOfRift, int** pGridElementListOnOneSideOfRift, int segmentnumber, int nriftsegs, int* riftsegments, int node,double* index,int nel);
+int UpdateSegments(double** psegments,double** psegmentmarkerlist, int* pnsegs, double* index, double* x,double* y,int* riftsegments,int nriftsegs);
+int pnpoly(int npol, double *xp, double *yp, double x, double y);
+int FindElement(double A,double B,double* index,int nel);
+int RemoveRifts(double** pindex,double** px,double** py,int* pnods,double** psegments,int* pnumsegs,int numrifts1,int* rifts1numsegs,double** rifts1segments,double** rifts1pairs,int nel);
+int IsRiftPresent(int* priftflag,int* pnumrifts, double* segmentmarkerlist,int nsegs);
+int SplitRiftSegments(double** psegments,double** psegmentmarkerlist, int* pnumsegs, int* pnumrifts,int** priftsnumsegs,double*** priftssegments,int numrifts);
+int OrderRifts(double** priftstips, double** riftssegments,double** riftspairs,int numrifts,int* riftsnumsegments,double* x,double* y);
+int PenaltyPairs(double*** priftspenaltypairs,int** priftsnumpenaltypairs,int numrifts,double**  riftssegments,
+		int* riftsnumsegments,double** riftspairs,double* riftstips,double* x,double* y);
+
+int RemoveCornersFromRifts(double** pindex,int* pnel,double** px,double** py,int* pnods, double* segments,double* segmentmarkers,int num_seg);
+int PairRiftElements(int** priftsnumpairs, double*** priftspairs,int numrifts,int* riftsnumsegments, double** riftssegments,double* x,double* y);
+
+
+#endif  /* _SHARED_TRIMESH_H */
Index: /issm/trunk-jpl-damage/src/c/shared/shared.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/shared/shared.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/shared/shared.h	(revision 11330)
@@ -0,0 +1,22 @@
+/* \file shared.h
+ * \brief: header file for all shared  routines.
+ */
+
+#ifndef _SHARED_H_
+#define _SHARED_H_
+
+
+#include "Alloc/alloc.h"
+#include "Exceptions/exceptions.h"
+#include "Exp/exp.h"
+#include "TriMesh/trimesh.h"
+#include "Sorting/sorting.h"
+#include "Elements/elements.h"
+#include "Matrix/matrix.h"
+#include "Numerics/numerics.h"
+#include "Dofs/dofs.h"
+#include "Threads/issm_threads.h"
+#include "Bamg/shared.h"
+#include "Matlab/matlabshared.h"
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp	(revision 11330)
@@ -0,0 +1,45 @@
+/*!\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 "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void AdjointCorePointerFromSolutionEnum(void (**padjointcore)(FemModel*),int solutiontype){
+
+	/*output: */
+	void (*adjointcore)(FemModel*)=NULL;
+
+	switch(solutiontype){
+	
+		case DiagnosticSolutionEnum:
+			adjointcore=&adjointdiagnostic_core;
+			break;
+		case SteadystateSolutionEnum:
+			adjointcore=&adjointdiagnostic_core;
+			break;
+		case BalancethicknessSolutionEnum:
+			adjointcore=&adjointbalancethickness_core;
+			break;
+		default:
+			_error_("No adjoint has been implemented for solution %s yet",EnumToStringx(solutiontype));
+			break;
+	}
+	
+	/*Assign output pointer:*/
+	_assert_(padjointcore);
+	*padjointcore=adjointcore;
+
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/AnalysisConfiguration.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/AnalysisConfiguration.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/AnalysisConfiguration.cpp	(revision 11330)
@@ -0,0 +1,118 @@
+/*!\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 "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void AnalysisConfiguration(int** panalyses,int* pnumanalyses, int solutiontype){
+
+	/*output: */
+	int  numanalyses;
+	int* analyses=NULL;
+
+	/*Analyses lists*/
+	switch(solutiontype){
+	
+		case DiagnosticSolutionEnum:
+			numanalyses=5;
+			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses[0]=DiagnosticHorizAnalysisEnum;
+			analyses[1]=DiagnosticVertAnalysisEnum;
+			analyses[2]=DiagnosticHutterAnalysisEnum;
+			analyses[3]=SurfaceSlopeAnalysisEnum;
+			analyses[4]=BedSlopeAnalysisEnum;
+			break;
+
+		case SteadystateSolutionEnum:
+			numanalyses=7;
+			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses[0]=DiagnosticHorizAnalysisEnum;
+			analyses[1]=DiagnosticVertAnalysisEnum;
+			analyses[2]=DiagnosticHutterAnalysisEnum;
+			analyses[3]=SurfaceSlopeAnalysisEnum;
+			analyses[4]=BedSlopeAnalysisEnum;
+			analyses[5]=ThermalAnalysisEnum;
+			analyses[6]=MeltingAnalysisEnum;
+			break;
+
+		case ThermalSolutionEnum:
+			numanalyses=2;
+			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses[0]=ThermalAnalysisEnum;
+			analyses[1]=MeltingAnalysisEnum;
+			break;
+		
+		case EnthalpySolutionEnum:
+			numanalyses=1;
+			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses[0]=EnthalpyAnalysisEnum;
+			break;
+		
+		case HydrologySolutionEnum:
+			numanalyses=3;
+			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses[0]=HydrologyAnalysisEnum;
+			analyses[1]=SurfaceSlopeAnalysisEnum;
+			analyses[2]=BedSlopeAnalysisEnum;
+			break;
+
+		case PrognosticSolutionEnum:
+			numanalyses=1;
+			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses[0]=PrognosticAnalysisEnum;
+			break;
+
+		case BalancethicknessSolutionEnum:
+			numanalyses=1;
+			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses[0]=BalancethicknessAnalysisEnum;
+			break;
+
+		case SurfaceSlopeSolutionEnum:
+			numanalyses=1;
+			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses[0]=SurfaceSlopeAnalysisEnum;
+			break;
+
+		case BedSlopeSolutionEnum:
+			numanalyses=1;
+			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses[0]=BedSlopeAnalysisEnum;
+			break;
+
+		case TransientSolutionEnum:
+			numanalyses=8;
+			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses[0]=DiagnosticHorizAnalysisEnum;
+			analyses[1]=DiagnosticVertAnalysisEnum;
+			analyses[2]=DiagnosticHutterAnalysisEnum;
+			analyses[3]=SurfaceSlopeAnalysisEnum;
+			analyses[4]=BedSlopeAnalysisEnum;
+			analyses[5]=ThermalAnalysisEnum;
+			analyses[6]=MeltingAnalysisEnum;
+			analyses[7]=PrognosticAnalysisEnum;
+			break;
+		
+		default:
+			_error_("%s%s%s"," solution type: ",EnumToStringx(solutiontype)," not supported yet!");
+			break;
+	}
+
+	/*Assign output pointers:*/
+	if(pnumanalyses) *pnumanalyses=numanalyses;
+	if(panalyses)    *panalyses=analyses;
+	else              xfree((void**)&analyses);
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/CorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/CorePointerFromSolutionEnum.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/CorePointerFromSolutionEnum.cpp	(revision 11330)
@@ -0,0 +1,106 @@
+/*!\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 "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void CorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype){
+
+	/*output: */
+	void (*solutioncore)(FemModel*)=NULL;
+
+	switch(solutiontype){
+	
+		case DiagnosticSolutionEnum:
+			#ifdef _HAVE_DIAGNOSTIC_
+			solutioncore=&diagnostic_core;
+			#else
+			_error_("ISSM was not compiled with diagnostic capabilities. Exiting");
+			#endif
+			break;
+		case SteadystateSolutionEnum:
+			#ifdef _HAVE_STEADYSTATE_
+			solutioncore=&steadystate_core;
+			#else
+			_error_("ISSM was not compiled with steady state capabilities. Exiting");
+			#endif
+			break;
+		case ThermalSolutionEnum:
+			#ifdef _HAVE_THERMAL_
+			solutioncore=&thermal_core;
+			#else
+			_error_("ISSM was not compiled with thermal capabilities. Exiting");
+			#endif
+			break;
+		case EnthalpySolutionEnum:
+			#ifdef _HAVE_THERMAL_
+			solutioncore=&enthalpy_core;
+			#else
+			_error_("ISSM was not compiled with thermal capabilities. Exiting");
+			#endif
+			break;
+		case BalancethicknessSolutionEnum:
+			#ifdef _HAVE_BALANCED_
+			solutioncore=&balancethickness_core;
+			#else
+			_error_("ISSM was not compiled with balanced capabilities. Exiting");
+			#endif
+			break;
+		case HydrologySolutionEnum:
+			#ifdef _HAVE_HYDROLOGY_
+			solutioncore=&hydrology_core;
+			#else
+			_error_("ISSM was not compiled with hydrology capabilities. Exiting");
+			#endif
+			break;
+		case SurfaceSlopeSolutionEnum:
+			#ifdef _HAVE_SLOPE_
+			solutioncore=&surfaceslope_core;
+			#else
+			_error_("ISSM was not compiled with slope capabilities. Exiting");
+			#endif
+			break;
+		case BedSlopeSolutionEnum:
+			#ifdef _HAVE_SLOPE_
+			solutioncore=&bedslope_core;
+			#else
+			_error_("ISSM was not compiled with slope capabilities. Exiting");
+			#endif
+			break;
+		case TransientSolutionEnum:
+			#ifdef _HAVE_TRANSIENT_
+			solutioncore=&transient_core;
+			#else
+			_error_("ISSM was not compiled with transient capabilities. Exiting");
+			#endif
+			break;
+		case PrognosticSolutionEnum:
+			#ifdef _HAVE_PROGNOSTIC_
+			solutioncore=&prognostic_core;
+			#else
+			_error_("ISSM was not compiled with prognostic capabilities. Exiting");
+			#endif
+			break;
+		default:
+			_error_("%s%s%s"," solution type: ",EnumToStringx(solutiontype)," not supported yet!");
+			break;
+	}
+	
+	/*Assign output pointer:*/
+	_assert_(psolutioncore);
+	*psolutioncore=solutioncore;
+
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/ProcessArguments.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/ProcessArguments.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/ProcessArguments.cpp	(revision 11330)
@@ -0,0 +1,31 @@
+/*!\file:  ProcessArguments.cpp
+ * \brief: process arguments
+ */ 
+
+#include <stdio.h>
+#include "../shared/shared.h"
+#include "../include/include.h"
+
+void ProcessArguments(int* solution_type,char** pbinfilename,char** poutbinfilename,char** ppetscfilename,char** plockfilename,int argc,char **argv){
+
+	char *modelname      = NULL;
+	char *binfilename    = NULL;
+	char *outbinfilename = NULL;
+	char *petscfilename  = NULL;
+	char *lockfilename   = NULL;
+
+	if(argc<2)_error_("Usage error: no solution requested");
+	*solution_type=StringToEnumx(argv[1]);
+	if(argc<3)_error_("Usage error: missing model name");
+	modelname=argv[3];
+	binfilename    = (char*)xmalloc((strlen(modelname)+strlen(".bin")   +1)*sizeof(char)); sprintf(binfilename,   "%s%s",modelname,".bin");
+	outbinfilename = (char*)xmalloc((strlen(modelname)+strlen(".outbin")+1)*sizeof(char)); sprintf(outbinfilename,"%s%s",modelname,".outbin");
+	petscfilename  = (char*)xmalloc((strlen(modelname)+strlen(".petsc") +1)*sizeof(char)); sprintf(petscfilename, "%s%s",modelname,".petsc");
+	lockfilename   = (char*)xmalloc((strlen(modelname)+strlen(".lock")  +1)*sizeof(char)); sprintf(lockfilename,  "%s%s",modelname,".lock");
+
+	/*Clean up and assign output pointer*/
+	*pbinfilename=binfilename;
+	*poutbinfilename=outbinfilename;
+	*ppetscfilename=petscfilename;
+	*plockfilename=lockfilename;
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/ResetBoundaryConditions.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/ResetBoundaryConditions.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/ResetBoundaryConditions.cpp	(revision 11330)
@@ -0,0 +1,33 @@
+/*!\file: ResetBoundaryConditions.cpp
+ * \brief: change boundary conditions of a model, using a solution vector from another analysis
+ */ 
+
+#include "../objects/objects.h"
+#include "../modules/modules.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+void ResetBoundaryConditions(FemModel* femmodel, int analysis_type){
+	
+	/*variables: */
+	Vec    yg    = NULL;
+	Nodes *nodes = NULL;
+	int    i;
+
+	_printf_(VerboseSolution(),"%s\n","   updating boundary conditions...");
+			
+	/*set current analysis: */
+	femmodel->SetCurrentConfiguration(analysis_type);
+
+	/*recover nodes: */
+	nodes=femmodel->nodes;
+
+	/*retrieve boundary conditions from element inputs :*/
+	GetSolutionFromInputsx( &yg, femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,  femmodel->parameters);
+
+	/*update spcs using this new vector of constraints: */
+	UpdateDynamicConstraintsx(femmodel->constraints,femmodel->nodes,femmodel->parameters,yg);
+
+	/*Free ressources:*/
+	VecFree(&yg);
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/WriteLockFile.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/WriteLockFile.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/WriteLockFile.cpp	(revision 11330)
@@ -0,0 +1,25 @@
+/*!\file:  WriteLockFile.cpp
+ * \brief
+ */ 
+#include <stdio.h>
+#include "../shared/shared.h"
+#include "../include/include.h"
+
+void WriteLockFile(char* filename){
+
+	int i;
+	extern int my_rank;
+	
+	/* output: */
+	FILE* fid=NULL;
+
+	/* Open lock file and write 1 into it: */
+	if(my_rank==0){
+		fid=fopen(filename,"w");
+		if(fid==NULL) _error_("%s%s","error message: could not open lock file ",filename);
+
+		/*Close file: */
+		if(fclose(fid)!=0) _error_("%s%s","could not close lock file ",filename);
+	}
+
+}	
Index: /issm/trunk-jpl-damage/src/c/solutions/adjointbalancethickness_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/adjointbalancethickness_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/adjointbalancethickness_core.cpp	(revision 11330)
@@ -0,0 +1,43 @@
+/*!\file:  adjointbalancethickness_core.cpp
+ * \brief compute inverse method adjoint state
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void adjointbalancethickness_core(FemModel* femmodel){
+	
+	/*parameters: */
+	bool control_analysis;
+	int  solution_type;
+
+	/*retrieve parameters:*/
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	/*compute thickness */
+	_printf_(VerboseSolution(),"%s\n","   computing thickness");
+	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+	solver_linear(femmodel);
+
+	/*Call SurfaceAreax, because some it might be needed by PVector*/
+	SurfaceAreax(NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+
+	/*compute adjoint*/
+	_printf_(VerboseSolution(),"%s\n","   computing adjoint");
+	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum,AdjointBalancethicknessAnalysisEnum);
+	solver_adjoint_linear(femmodel);
+	
+	/*Save results*/
+	if(solution_type==AdjointSolutionEnum && !control_analysis){
+		_printf_(VerboseSolution(),"   saving results\n");
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,AdjointEnum);
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/adjointdiagnostic_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/adjointdiagnostic_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/adjointdiagnostic_core.cpp	(revision 11330)
@@ -0,0 +1,51 @@
+/*!\file:  adjointdiagnostic_core.cpp
+ * \brief compute inverse method adjoint state
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void adjointdiagnostic_core(FemModel* femmodel){
+	
+	/*parameters: */
+	bool isstokes;
+	bool control_analysis;
+	bool conserve_loads   = true;
+	int  solution_type;
+
+	/*retrieve parameters:*/
+	femmodel->parameters->FindParam(&isstokes,FlowequationIsstokesEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	/*Compute velocities*/
+	_printf_(VerboseSolution(),"%s\n","   computing velocities");
+	femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
+	solver_nonlinear(femmodel,conserve_loads); 
+
+	/*Call SurfaceAreax, because some it might be needed by PVector*/
+	SurfaceAreax(NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+
+	/*Compute adjoint*/
+	_printf_(VerboseSolution(),"%s\n","   computing adjoint");
+	femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum,AdjointHorizAnalysisEnum);
+	solver_adjoint_linear(femmodel);
+	
+	/*Save results*/
+	if(solution_type==AdjointSolutionEnum && !control_analysis){
+		_printf_(VerboseSolution(),"   saving results\n");
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,AdjointxEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,AdjointyEnum);
+		if (isstokes){
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,AdjointzEnum);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,AdjointpEnum);
+		}
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/balancethickness_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/balancethickness_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/balancethickness_core.cpp	(revision 11330)
@@ -0,0 +1,38 @@
+/*!\file: balancethickness_core.cpp
+ * \brief: core of the balancethickness solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../solvers/solvers.h"
+
+void balancethickness_core(FemModel* femmodel){
+
+	/*parameters: */
+	int  dim;
+	int  solution_type;
+	bool control_analysis;
+
+	/*activate formulation: */
+	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+	
+	/*recover parameters: */
+	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	_printf_(VerboseSolution(),"call computational core:\n");
+	solver_linear(femmodel);
+
+	if(solution_type==BalancethicknessSolutionEnum && !control_analysis){
+		_printf_(VerboseSolution(),"   saving results\n");
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ThicknessEnum);
+	}
+
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/bedslope_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/bedslope_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/bedslope_core.cpp	(revision 11330)
@@ -0,0 +1,41 @@
+/*!\file: bedslope_core.cpp
+ * \brief: core of the slope solution 
+ */ 
+
+#include "./solutions.h"
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../modules/modules.h"
+#include "../solvers/solvers.h"
+
+void bedslope_core(FemModel* femmodel){
+
+	/*parameters: */
+	int  dim;
+	bool isstokes;
+	bool ishutter;
+	bool control_analysis;
+	int  solution_type;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	_printf_(VerboseSolution(),"%s\n","   computing slope");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(BedSlopeAnalysisEnum,BedSlopeXAnalysisEnum);
+	solver_linear(femmodel);
+	femmodel->SetCurrentConfiguration(BedSlopeAnalysisEnum,BedSlopeYAnalysisEnum);
+	solver_linear(femmodel);
+	
+	if(solution_type==BedSlopeSolutionEnum && !control_analysis){
+		_printf_(VerboseSolution(),"   saving results\n");
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BedSlopeXEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BedSlopeYEnum);
+	}
+
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/control_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/control_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/control_core.cpp	(revision 11330)
@@ -0,0 +1,130 @@
+/*!\file: control_core.cpp
+ * \brief: core of the control solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void control_core(FemModel* femmodel){
+
+	int     i,n;
+	
+	/*parameters: */
+	int     num_controls,num_responses;
+	int     nsteps;
+	double  tol_cm;
+	bool    cm_gradient;
+	int     dim;
+	int     solution_type;
+	bool    isstokes;
+	bool    dakota_analysis=false;
+
+	int*    control_type = NULL;
+	double* responses=NULL;
+	int*    step_responses=NULL;
+	double* maxiter=NULL;
+	double* cm_jump=NULL;
+		
+	/*intermediary: */
+	double  search_scalar=1;
+	OptArgs optargs;
+	OptPars optpars;
+
+	/*Solution and Adjoint core pointer*/
+	void (*solutioncore)(FemModel*)=NULL;
+	void (*adjointcore)(FemModel*)=NULL;
+
+	/*output: */
+	double* J=NULL;
+
+	/*Recover parameters used throughout the solution*/
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	femmodel->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+	femmodel->parameters->FindParam(&responses,NULL,NULL,InversionCostFunctionsEnum);
+	femmodel->parameters->FindParam(&nsteps,InversionNstepsEnum);
+	femmodel->parameters->FindParam(&maxiter,NULL,InversionMaxiterPerStepEnum);
+	femmodel->parameters->FindParam(&cm_jump,NULL,InversionStepThresholdEnum);
+	femmodel->parameters->FindParam(&tol_cm,InversionCostFunctionThresholdEnum);
+	femmodel->parameters->FindParam(&cm_gradient,InversionGradientOnlyEnum);
+	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&isstokes,FlowequationIsstokesEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+
+	/*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*/
+	_printf_(VerboseControl(),"%s\n","   preparing initial solution");
+	if (isstokes) solutioncore(femmodel);
+
+	/*Initialize responses: */
+	J=(double*)xmalloc(nsteps*sizeof(double));
+	step_responses=(int*)xmalloc(num_responses*sizeof(double));
+		
+	/*Initialize some of the BrentSearch arguments: */
+	optargs.femmodel=femmodel;
+	optpars.xmin=0; optpars.xmax=1;
+	
+	/*Start looping: */
+	for(n=0;n<nsteps;n++){
+
+		/*Display info*/
+		_printf_(VerboseControl(),"\n%s%i%s%i\n","   control method step ",n+1,"/",nsteps);
+		for(i=0;i<num_responses;i++) step_responses[i]=(int)responses[n*num_responses+i];
+		femmodel->parameters->SetParam(step_responses,1,num_responses,StepResponsesEnum);
+		
+		/*In steady state inversion, compute new temperature field now*/
+		if(solution_type==SteadystateSolutionEnum) solutioncore(femmodel);
+
+		_printf_(VerboseControl(),"%s\n","   compute adjoint state:");
+		adjointcore(femmodel);
+		gradient_core(femmodel,n,search_scalar==0);
+
+		/*Return gradient if asked: */
+		if (cm_gradient){
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,GradientEnum);
+			goto cleanup_and_return;
+		}
+
+		_printf_(VerboseControl(),"%s\n","   optimizing along gradient direction");
+		optpars.maxiter=(int)maxiter[n]; optpars.cm_jump=cm_jump[n];
+		BrentSearch(&search_scalar,J+n,&optpars,&objectivefunctionC,&optargs);
+
+		_printf_(VerboseControl(),"%s\n","   updating parameter using optimized search scalar"); //true means update save controls
+		InputControlUpdatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,search_scalar,true);
+		
+		if(controlconvergence(J[n],tol_cm)) break;
+	}
+
+	_printf_(VerboseControl(),"%s\n","   preparing final solution");
+	femmodel->parameters->SetParam(false,InversionIscontrolEnum); //needed to turn control result output in solutioncore
+	solutioncore(femmodel);
+
+	/*some results not computed by steadystate_core or diagnostic_core: */
+	if(!dakota_analysis){ //do not save this if we are running the control core from a qmu run!
+		for(i=0;i<num_controls;i++) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,control_type[i]);
+		femmodel->results->AddObject(new DoubleVecExternalResult(femmodel->results->Size()+1,JEnum,J,nsteps,1,0));
+	}
+
+	cleanup_and_return:
+	/*Free ressources: */
+	xfree((void**)&control_type);
+	xfree((void**)&responses);
+	xfree((void**)&step_responses);
+	xfree((void**)&maxiter);
+	xfree((void**)&cm_jump);
+	xfree((void**)&J);
+	
+	/*control_core might be used in Qmu, so leave everything similar to where it started: */
+	femmodel->parameters->SetParam(true,InversionIscontrolEnum);
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/controlconvergence.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/controlconvergence.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/controlconvergence.cpp	(revision 11330)
@@ -0,0 +1,31 @@
+/*!\file: controlconvergence.cpp
+ * \brief: determine convergence of control_core solution
+ */ 
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../Container/Container.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../include/include.h"
+#include "../modules/modules.h"
+#include "./solutions.h"
+
+bool controlconvergence(double J, double tol_cm){
+
+	int i;
+	bool converged=false;
+
+	/*Has convergence been reached?*/
+	if (!isnan(tol_cm) && J<tol_cm){
+		converged=true;
+		_printf_(VerboseConvergence(),"      Convergence criterion reached: J = %g < %g",J,tol_cm);
+	}
+
+	return converged;
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/controlrestart.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/controlrestart.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/controlrestart.cpp	(revision 11330)
@@ -0,0 +1,36 @@
+/*!\file: controlrestart.cpp
+ * \brief: save as much as possible, to be able to restart the control_core solution
+ */ 
+
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+void controlrestart(FemModel* femmodel,double* J){
+
+	int      num_controls;
+	int*     control_type = NULL;
+	int      nsteps;
+	bool     dakota_analysis=true;
+
+	/*retrieve output file name: */
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+	femmodel->parameters->FindParam(&nsteps,InversionNstepsEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+
+	/*only save if we are not running qmu analysis. We certainly don't want to save control results each time we 
+	 * run on control core!: */
+	if(!dakota_analysis){
+		/*we essentially want J and the parameter: */
+		for(int i=0;i<num_controls;i++) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,control_type[i]);
+		femmodel->results->AddObject(new DoubleVecExternalResult(femmodel->results->Size()+1,JEnum,J,nsteps,1,0));
+		//femmodel->results->AddObject(new StringExternalResult(femmodel->results->Size()+1,InversionControlParametersEnum,EnumToStringx(control_type),1,0));
+
+		/*write to disk: */
+		OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,&femmodel->results);
+	}
+
+	/*Clean up and return*/
+	xfree((void**)&control_type);
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/controltao_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/controltao_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/controltao_core.cpp	(revision 11330)
@@ -0,0 +1,99 @@
+/*!\file: control_core.cpp
+ * \brief: core of the control solution 
+ */ 
+#include <config.h>
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+#if defined (_HAVE_TAO_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ == 2)
+#include <tao.h>
+
+/*Local prototype*/
+int FormFunctionGradient(TaoSolver tao,Vec,double*,Vec,void*);
+typedef struct {
+	FemModel* femmodel;
+} AppCtx;
+
+void controltao_core(FemModel* femmodel){
+
+	/*TAO*/
+	int       ierr,numberofvertices;
+	AppCtx    user;
+	TaoSolver tao;
+	Vec       X  = NULL;
+	Vec       XL = NULL;
+	Vec       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");
+
+	/*Initialize TAO*/
+	TaoCreate(PETSC_COMM_WORLD,&tao);
+	PetscOptionsSetValue("-tao_monitor","");
+	TaoSetFromOptions(tao);
+	TaoSetType(tao,"tao_blmvm");
+
+	/*Prepare all TAO parameters*/
+	TaoSetMaximumFunctionEvaluations(tao,50);
+	TaoSetMaximumIterations(tao,10);
+	TaoSetTolerances(tao,10e-28,0.0000,0.0000,0.0000,10e-28);
+
+	numberofvertices = femmodel->vertices->NumberOfVertices();
+	XL=NewVec(numberofvertices); VecSet(XL,1.);
+	XU=NewVec(numberofvertices); VecSet(XU,200.);
+	TaoSetVariableBounds(tao,XL,XU); VecFree(&XL); VecFree(&XU);
+
+	GetVectorFromInputsx(&X,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,FrictionCoefficientEnum,VertexEnum);
+	TaoSetInitialVector(tao,X);
+
+	user.femmodel=femmodel;
+	TaoSetObjectiveAndGradientRoutine(tao,FormFunctionGradient,(void*)&user); 
+
+	/*Solver optimization problem*/
+	TaoSolve(tao);
+	TaoView(tao,PETSC_VIEWER_STDOUT_WORLD);
+	TaoGetSolutionVector(tao,&X);
+	InputUpdateFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X,FrictionCoefficientEnum,VertexEnum);
+	InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,FrictionCoefficientEnum);
+
+	/*Clean up and return*/
+	VecFree(&X);
+	TaoDestroy(&tao);
+	TaoFinalize();
+}
+int FormFunctionGradient(TaoSolver tao, Vec X, double *fcn,Vec G,void *userCtx){
+
+	/*Retreive arguments*/
+	AppCtx   *user     = (AppCtx*)userCtx;
+	FemModel *femmodel = user->femmodel;
+	Vec       gradient = NULL;
+
+	int costfunction=SurfaceAbsVelMisfitEnum;
+	femmodel->parameters->SetParam(&costfunction,1,1,StepResponsesEnum);
+	//InputUpdateFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X,MaterialsRheologyBbarEnum,VertexEnum);
+	InputUpdateFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X,FrictionCoefficientEnum,VertexEnum);
+	adjointdiagnostic_core(user->femmodel);
+	//Gradjx(&gradient,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,MaterialsRheologyBbarEnum);
+	Gradjx(&gradient,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,FrictionCoefficientEnum);
+	VecScale(gradient,-1.);
+	VecCopy(gradient,G);
+	VecFree(&gradient);
+	CostFunctionx(fcn,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	return 0;
+}
+
+#else
+void controltao_core(FemModel* femmodel){
+	_error_("TAO not installed or PETSc version not supported");
+}
+#endif //_HAVE_TAO_ 
Index: /issm/trunk-jpl-damage/src/c/solutions/convergence.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/convergence.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/convergence.cpp	(revision 11330)
@@ -0,0 +1,144 @@
+/*!\file: convergence.cpp
+ * \brief: figure out if convergence has been reached
+ */ 
+
+#include "../objects/objects.h"
+#include "../modules/modules.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+void convergence(bool* pconverged, Mat Kff,Vec pf,Vec uf,Vec old_uf,Parameters* parameters){
+
+	/*output*/
+	bool converged=false;
+
+	/*intermediary*/
+	Vec KU=NULL;
+	Vec KUF=NULL;
+	Vec KUold=NULL;
+	Vec KUoldF=NULL;
+	Vec duf=NULL;
+	double ndu,nduinf,nu;
+	double nKUF;
+	double nKUoldF;
+	double nF;
+	double solver_residue,res;
+
+	/*convergence options*/
+	double eps_res;
+	double eps_rel;
+	double eps_abs;
+	double yts;
+
+	/*If uf is NULL in input, f-set is nil, model is fully constrained, therefore converged from 
+	 * the get go: */
+	if(!uf){
+		*pconverged=true;
+		return;
+	}
+
+	/*get convergence options*/
+	parameters->FindParam(&eps_res,DiagnosticRestolEnum);
+	parameters->FindParam(&eps_rel,DiagnosticReltolEnum);
+	parameters->FindParam(&eps_abs,DiagnosticAbstolEnum);
+	parameters->FindParam(&yts,ConstantsYtsEnum);
+
+	/*Display solver caracteristics*/
+	if (VerboseConvergence()){
+
+		//compute KUF = KU - F = K*U - F
+		VecDuplicate(uf,&KU); MatMultPatch(Kff,uf,KU);
+		VecDuplicate(KU,&KUF);VecCopy(KU,KUF); VecAYPX(KUF,-1.0,pf);
+
+		//compute norm(KUF), norm(F) and residue
+		VecNorm(KUF,NORM_2,&nKUF);
+		VecNorm(pf,NORM_2,&nF);
+		solver_residue=nKUF/nF;
+		_printf_(true,"\n%s%g\n","   solver residue: norm(KU-F)/norm(F)=",solver_residue);
+
+		//clean up
+		VecFree(&KU);
+		VecFree(&KUF);
+	}
+
+	/*Force equilibrium (Mandatory)*/
+
+	//compute K[n]U[n-1]F = K[n]U[n-1] - F
+	VecDuplicate(uf,&KUold); MatMultPatch(Kff,old_uf,KUold);
+	VecDuplicate(KUold,&KUoldF);VecCopy(KUold,KUoldF); VecAYPX(KUoldF,-1.0,pf);
+	VecNorm(KUoldF,NORM_2,&nKUoldF);
+	VecNorm(pf,NORM_2,&nF);
+	res=nKUoldF/nF;
+	if (isnan(res)){
+		_printf_(true,"norm nf = %lf and norm kuold = %lf\n",nF,nKUoldF);
+		_error_("mechanical equilibrium convergence criterion is NaN!");
+	}
+
+	//clean up
+	VecFree(&KUold);
+	VecFree(&KUoldF);
+
+	//print
+	if(res<eps_res){
+		_printf_(VerboseConvergence(),"%-50s%g%s%g%s\n","   mechanical equilibrium convergence criterion",res*100," < ",eps_res*100," %");
+		converged=true;
+	}
+	else{ 
+		_printf_(VerboseConvergence(),"%-50s%g%s%g%s\n","   mechanical equilibrium convergence criterion",res*100," > ",eps_res*100," %");
+		converged=false;
+	}
+
+	/*Relative criterion (optional)*/
+	if (!isnan(eps_rel) || (VerboseConvergence())){
+
+		//compute norm(du)/norm(u)
+		VecDuplicate(old_uf,&duf);VecCopy(old_uf,duf); VecAYPX(duf,-1.0,uf);
+		VecNorm(duf,NORM_2,&ndu); VecNorm(old_uf,NORM_2,&nu);
+
+		if (isnan(ndu) || isnan(nu)) _error_("convergence criterion is NaN!");
+
+		//clean up
+		VecFree(&duf);
+
+		//print
+		if (!isnan(eps_rel)){
+			if((ndu/nu)<eps_rel){
+				_printf_(VerboseConvergence(),"%-50s%g%s%g%s\n","   Convergence criterion: norm(du)/norm(u)",ndu/nu*100," < ",eps_rel*100," %");
+			}
+			else{ 
+				_printf_(VerboseConvergence(),"%-50s%g%s%g%s\n","   Convergence criterion: norm(du)/norm(u)",ndu/nu*100," > ",eps_rel*100," %");
+				converged=false;
+			}
+		}
+		else _printf_(true,"%-50s%g%s\n","   Convergence criterion: norm(du)/norm(u)",ndu/nu*100," %");
+
+	}
+
+	/*Absolute criterion (Optional) = max(du)*/
+	if (!isnan(eps_abs) || (VerboseConvergence())){
+
+		//compute max(du)
+		VecDuplicate(old_uf,&duf);VecCopy(old_uf,duf); VecAYPX(duf,-1.0,uf);
+		VecNorm(duf,NORM_2,&ndu); VecNorm(duf,NORM_INFINITY,&nduinf);
+		if (isnan(ndu) || isnan(nu)) _error_("convergence criterion is NaN!");
+
+		//clean up
+		VecFree(&duf);
+
+		//print
+		if (!isnan(eps_abs)){
+			if ((nduinf*yts)<eps_abs){
+				_printf_(VerboseConvergence(),"%-50s%g%s%g%s\n","   Convergence criterion: max(du)",nduinf*yts," < ",eps_abs," m/yr");
+			}
+			else{
+				_printf_(VerboseConvergence(),"%-50s%g%s%g%s\n","   Convergence criterion: max(du)",nduinf*yts," > ",eps_abs," m/yr");
+				converged=false;
+			}
+		}
+		else  _printf_(true,"%-50s%g%s\n","   Convergence criterion: max(du)",nduinf*yts," m/yr");
+
+	}
+
+	/*assign output*/
+	*pconverged=converged;
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/diagnostic_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/diagnostic_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/diagnostic_core.cpp	(revision 11330)
@@ -0,0 +1,103 @@
+/*!\file: diagnostic_core.cpp
+ * \brief: core of the diagnostic solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void diagnostic_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool   dakota_analysis         = false;
+	int    dim                  = -1;
+	bool   ishutter             = false;
+	bool   ismacayealpattyn     = false;
+	bool   isstokes             = false;
+	bool   conserve_loads       = true;
+	bool   modify_loads         = true;
+	bool   control_analysis;
+	int    solution_type;
+	int    numoutputs         = 0;
+	int    *requested_outputs = NULL;
+
+	/* recover parameters:*/
+	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
+	femmodel->parameters->FindParam(&ishutter,FlowequationIshutterEnum);
+	femmodel->parameters->FindParam(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
+	femmodel->parameters->FindParam(&isstokes,FlowequationIsstokesEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&numoutputs,DiagnosticNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,DiagnosticRequestedOutputsEnum);
+
+	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
+	if(dakota_analysis && solution_type==DiagnosticSolutionEnum){
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVxEnum,VxEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVyEnum,VyEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVzEnum,VzEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuPressureEnum,PressureEnum);
+	}
+
+	/*Compute slopes: */
+	if(ishutter) surfaceslope_core(femmodel);
+	if(isstokes){
+		bedslope_core(femmodel);
+		femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
+		ResetCoordinateSystemx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	}
+
+	if(ishutter){
+			
+		_printf_(VerboseSolution(),"%s\n","   computing hutter velocities");
+
+		//Take the last velocity into account so that the velocity on the MacAyeal domain is not zero
+		if (ismacayealpattyn) ResetBoundaryConditions(femmodel,DiagnosticHutterAnalysisEnum);
+
+		femmodel->SetCurrentConfiguration(DiagnosticHutterAnalysisEnum);
+		solver_linear(femmodel);
+		
+		if (ismacayealpattyn) ResetBoundaryConditions(femmodel,DiagnosticHorizAnalysisEnum);
+	}
+
+	if (ismacayealpattyn ^ isstokes){ // ^ = xor
+		
+		_printf_(VerboseSolution(),"%s\n","   computing velocities");
+		femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
+		solver_nonlinear(femmodel,modify_loads); 
+	}
+
+	if (ismacayealpattyn && isstokes){
+
+		_printf_(VerboseSolution(),"%s\n","   computing coupling macayealpattyn and stokes velocities and pressure ");
+		solver_stokescoupling_nonlinear(femmodel,conserve_loads);
+	}
+
+	if (dim==3 & (ishutter || ismacayealpattyn)){
+
+		_printf_(VerboseSolution(),"%s\n","   computing vertical velocities");
+		femmodel->SetCurrentConfiguration(DiagnosticVertAnalysisEnum);
+		solver_linear(femmodel);
+	}
+
+
+	if(solution_type==DiagnosticSolutionEnum && !control_analysis){
+		_printf_(VerboseSolution(),"   saving results\n");
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VxEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VyEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VelEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,PressureEnum);
+		if(dim==3) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VzEnum);
+		RequestedOutputsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,requested_outputs,numoutputs);
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&requested_outputs);
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/enthalpy_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/enthalpy_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/enthalpy_core.cpp	(revision 11330)
@@ -0,0 +1,58 @@
+/*!\file: enthalpy_core.cpp
+ * \brief: core of the enthalpy solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../io/io.h"
+#include "../solvers/solvers.h"
+
+void enthalpy_core(FemModel* femmodel){
+
+	int i;
+
+	/*intermediary*/
+	double time;
+	int    nsteps;
+	double final_time;
+	double dt;
+	double melting_offset;
+	bool control_analysis;
+	int solution_type;
+
+	//first recover parameters common to all solutions
+	femmodel->parameters->FindParam(&final_time,TimesteppingFinalTimeEnum);
+	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	/*Compute number of time steps: */
+	if((dt==0)|| (final_time==0)){
+		dt=0;
+		nsteps=1;
+	}
+	else nsteps=(int)(final_time/dt);
+
+	/*Loop through time: */
+	for(i=0;i<nsteps;i++){
+		
+		if(nsteps)_printf_(VerboseSolution(),"time step: %i/%i\n",i+1,nsteps);
+		time=(i+1)*dt;
+
+		/*call enthalpy_core_step: */
+		enthalpy_core_step(femmodel,i,time);
+
+		if(solution_type==EnthalpySolutionEnum && !control_analysis){
+			_printf_(VerboseSolution(),"   saving results\n");
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,TemperatureEnum,i+1,time);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EnthalpyEnum,i+1,time);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,WaterfractionEnum,i+1,time);
+		}
+
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/enthalpy_core_step.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/enthalpy_core_step.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/enthalpy_core_step.cpp	(revision 11330)
@@ -0,0 +1,26 @@
+/*!\file: enthalpy_core_step.cpp
+ * \brief: core of the enthalpy solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void enthalpy_core_step(FemModel* femmodel,int step, double time){
+	
+	bool modify_loads=true;
+
+	_printf_(VerboseSolution(),"   computing enthalpy\n");
+	femmodel->SetCurrentConfiguration(EnthalpyAnalysisEnum);
+	solver_nonlinear(femmodel,modify_loads);
+
+	/*transfer enthalpy to enthalpy picard for the next step: */
+	InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EnthalpyEnum,EnthalpyPicardEnum);
+
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/gradient_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/gradient_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/gradient_core.cpp	(revision 11330)
@@ -0,0 +1,67 @@
+/*!\file:  gradient_core.cpp
+ * \brief compute inverse method gradient direction.
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void gradient_core(FemModel* femmodel,int step,bool orthogonalize){ 
+	
+	/*parameters: */
+	bool    control_steady;
+	int     num_controls;
+	int    *control_type   = NULL;
+	double *optscal_list   = NULL;
+	double  optscal,norm_grad;
+
+	/*Intermediaries*/
+	Vec new_gradient=NULL;
+	Vec gradient=NULL;
+	Vec old_gradient=NULL;
+
+	/*retrieve parameters:*/
+	femmodel->parameters->FindParam(&control_steady,ControlSteadyEnum);
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+	femmodel->parameters->FindParam(&optscal_list,NULL,NULL,InversionGradientScalingEnum);
+
+	/*Compute and norm gradient of all controls*/
+	for (int i=0;i<num_controls;i++){
+
+		_printf_(VerboseControl(),"   compute gradient of J with respect to %s\n",EnumToStringx(control_type[i]));
+		Gradjx(&gradient, femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,femmodel->parameters, control_type[i]);
+
+		if (orthogonalize){
+			_printf_(VerboseControl(),"   orthogonalization\n");
+			ControlInputGetGradientx(&old_gradient,femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,femmodel->parameters,control_type[i]);
+			Orthx(&new_gradient,gradient,old_gradient); VecFree(&old_gradient); VecFree(&gradient);
+		}
+		else{ 
+			new_gradient=gradient;
+		}
+
+		/*Get scaling factor of current control:*/
+		VecNorm(new_gradient,NORM_INFINITY,&norm_grad);
+		if(norm_grad<=0)    _error_("||∂J/∂α||∞ = 0    gradient norm of J with respect to %s is zero",EnumToStringx(control_type[i]));
+		if(isnan(norm_grad))_error_("||∂J/∂α||∞ = NaN  gradient norm of J with respect to %s is NaN" ,EnumToStringx(control_type[i]));
+		optscal=optscal_list[num_controls*step+i]/norm_grad;
+
+		/*plug back into inputs: */
+		ControlInputSetGradientx(femmodel-> elements,femmodel-> nodes, femmodel-> vertices,femmodel-> loads, femmodel-> materials,  femmodel->parameters,control_type[i],new_gradient);
+		VecFree(&new_gradient);
+	}
+
+	/*Scale Gradients*/
+	for (int i=0;i<num_controls;i++) ControlInputScaleGradientx(femmodel-> elements,femmodel-> nodes, femmodel-> vertices,femmodel-> loads, femmodel-> materials,  femmodel->parameters,control_type[i],optscal);
+
+	/*Clean up and return*/
+	xfree((void**)&control_type);
+	xfree((void**)&optscal_list);
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/hydrology_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/hydrology_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/hydrology_core.cpp	(revision 11330)
@@ -0,0 +1,69 @@
+/*!\file: hydrology_core.cpp
+ * \brief: core of the hydrology solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../solvers/solvers.h"
+
+void hydrology_core(FemModel* femmodel){
+
+	int i;
+
+	/*intermediary*/
+	double time;
+	int    nsteps;
+	double final_time;
+	double dt;
+	bool control_analysis;
+	int solution_type;
+	int output_frequency;
+
+	//first recover parameters common to all solutions
+	femmodel->parameters->FindParam(&final_time,TimesteppingFinalTimeEnum);
+	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&output_frequency,SettingsOutputFrequencyEnum);
+	/*first compute slopes: */
+	surfaceslope_core(femmodel);
+	bedslope_core(femmodel);
+
+	/*Compute number of time steps: */
+	if((dt==0)|| (final_time==0)){
+		dt=0;
+		nsteps=1;
+	}
+	else nsteps=(int)(final_time/dt);
+
+	/*Loop through time: */
+	for(i=0;i<nsteps;i++){
+		
+		if(nsteps)_printf_(VerboseSolution(),"time step:%i/%i\n",i+1,nsteps);
+		time=(i+1)*dt;
+		femmodel->parameters->SetParam(time,TimeEnum);
+
+		/*call hydrology_core step: */
+		hydrology_core_step(femmodel,i,time);
+
+		if(solution_type==HydrologySolutionEnum && !control_analysis && ((i+1)%output_frequency==0 || (i+1)==nsteps)){
+			
+			_printf_(VerboseSolution(),"   saving results \n");
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,WatercolumnEnum,i+1,time);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,HydrologyWaterVxEnum,i+1,time);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,HydrologyWaterVyEnum,i+1,time);
+			
+			/*unload results*/
+			_printf_(VerboseSolution(),"   saving temporary results\n");
+			OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,&femmodel->results);
+
+		}
+
+	}
+}
+
Index: /issm/trunk-jpl-damage/src/c/solutions/hydrology_core_step.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/hydrology_core_step.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/hydrology_core_step.cpp	(revision 11330)
@@ -0,0 +1,26 @@
+/*!\file: hydrology_core_step.cpp
+ * \brief: core of the hydrology solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void hydrology_core_step(FemModel* femmodel,int step, double time){
+	
+	bool modify_loads=true;
+
+	_printf_(VerboseSolution(),"   computing water column\n");
+	femmodel->SetCurrentConfiguration(HydrologyAnalysisEnum);
+	solver_nonlinear(femmodel,modify_loads);
+
+	/*transfer water column thickness to old water column thickness: */
+	InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,WatercolumnEnum,WaterColumnOldEnum);
+
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/issm.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/issm.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/issm.cpp	(revision 11330)
@@ -0,0 +1,140 @@
+/*!\file:  issm.cpp
+ * \brief: ISSM main parallel program
+ */ 
+
+#include "../issm.h"
+#include "../include/globals.h"
+
+int main(int argc,char **argv){
+
+	/*MPI: */
+	extern int my_rank;
+	extern int num_procs;
+
+	/*I/O: */
+	FILE *output_fid       = NULL;
+	FILE *petscoptionsfid  = NULL;
+	bool  waitonlock       = false;
+	bool  dakota_analysis,control_analysis,tao_analysis;
+
+	/*FemModel: */
+	FemModel *femmodel = NULL;
+
+	/*configuration: */
+	void (*solutioncore)(FemModel*)=NULL; //core solution function pointer
+	int* analyses=NULL;
+	int  numanalyses;
+	int  solution_type;
+
+	/*File names*/
+	char *lockfilename   = NULL;
+	char *binfilename    = NULL;
+	char *outbinfilename = NULL;
+	char *petscfilename  = NULL;
+
+	/*time*/
+	double   start, finish;
+	double   start_core, finish_core;
+	double   start_init, finish_init;
+
+	MODULEBOOT();
+
+	#if !defined(_PARALLEL_) || (defined(_PARALLEL_) && !defined(_HAVE_PETSC_))
+	_error_(" parallel executable was compiled without support of parallel libraries!");
+	#endif
+
+	/*Initialize Petsc and get start time*/
+	int ierr=PetscInitialize(&argc,&argv,(char*)0,"");  
+	if(ierr) _error_("Could not initialize Petsc");
+	MPI_Barrier(MPI_COMM_WORLD); start=MPI_Wtime();
+
+	/*Size and rank: */
+	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);  
+	MPI_Comm_size(MPI_COMM_WORLD,&num_procs); 
+
+	/*First process inputs*/
+	_printf_(true,"Launching solution sequence\n");
+	ProcessArguments(&solution_type,&binfilename,&outbinfilename,&petscfilename,&lockfilename,argc,argv);
+
+	/*out of solution_type, figure out types of analyses needed in the femmodel: */
+	AnalysisConfiguration(&analyses,&numanalyses,solution_type);
+	
+	/*Create femmodel, using input file: */
+	MPI_Barrier(MPI_COMM_WORLD); start_init=MPI_Wtime();
+	femmodel=new FemModel(binfilename,outbinfilename,solution_type,analyses,numanalyses);
+	
+	/*get type of solution we are going to run: */
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+
+	/*Open output file once for all*/
+	output_fid=pfopen(outbinfilename,"wb");
+	femmodel->parameters->SetParam(output_fid,OutputFilePointerEnum);
+
+	/*add petsc options to parameters: */
+	petscoptionsfid=pfopen(petscfilename,"r");
+	ParsePetscOptionsx(femmodel->parameters,petscoptionsfid);
+	pfclose(petscoptionsfid,petscfilename);
+
+	/*get parameters: */
+	femmodel->parameters->FindParam(&waitonlock,SettingsWaitonlockEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&tao_analysis,InversionTaoEnum);
+	MPI_Barrier(MPI_COMM_WORLD); finish_init=MPI_Wtime();
+
+	_printf_(true,"call computational core:\n");
+	MPI_Barrier(MPI_COMM_WORLD); start_core=MPI_Wtime( );
+	if(dakota_analysis){
+		#ifdef _HAVE_DAKOTA_
+		Dakotax(femmodel);
+		#else
+		_error_("ISSM was not compiled with dakota support, cannot carry out dakota analysis!");
+		#endif
+	}
+	else if(control_analysis){
+		#ifdef _HAVE_CONTROL_
+		if(tao_analysis)
+		 controltao_core(femmodel);
+		else
+		 control_core(femmodel);
+		#else
+		_error_("ISSM was not compiled with control support, cannot carry out dakota analysis!");
+		#endif
+	}
+	else{
+		solutioncore(femmodel);
+	}
+	MPI_Barrier(MPI_COMM_WORLD); finish_core=MPI_Wtime( );
+
+	_printf_(true,"write results to disk:\n");
+	OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,&femmodel->results);
+
+	/*Close output and petsc options file and write lock file if requested*/
+	pfclose(output_fid,lockfilename);
+	if (waitonlock>0){
+		_printf_(true,"write lock file:\n");
+		WriteLockFile(lockfilename);
+	}
+
+	/*Free ressources */
+	xfree((void**)&analyses);
+	xfree((void**)&lockfilename);
+	xfree((void**)&binfilename);
+	xfree((void**)&outbinfilename);
+	xfree((void**)&petscfilename);
+	delete femmodel;
+
+	/*Get finish time and close*/
+	MPI_Barrier(MPI_COMM_WORLD); finish = MPI_Wtime( );
+	_printf_(true,"\n   %-34s %f seconds  \n","FemModel initialization elapsed time:",finish_init-start_init);
+	_printf_(true,"   %-34s %f seconds  \n","Core solution elapsed time:",finish_core-start_core);
+	_printf_(true,"\n   %s %i hrs %i min %i sec\n\n","Total elapsed time:",int((finish-start)/3600),int(int(finish-start)%3600/60),int(finish-start)%60);
+	_printf_(true,"closing MPI and Petsc\n");
+	PetscFinalize(); 
+	
+	/*end module: */
+	MODULEEND();
+
+	return 0; //unix success return;
+}
+
Index: /issm/trunk-jpl-damage/src/c/solutions/objectivefunctionC.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/objectivefunctionC.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/objectivefunctionC.cpp	(revision 11330)
@@ -0,0 +1,76 @@
+/*!\file:  objectivefunctionC
+ * \brief  objective function that returns a misfit, for a certain parameter.
+ */ 
+
+/*include files: {{{1*/
+#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 "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../solvers/solvers.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+/*}}}*/
+
+double objectivefunctionC(double search_scalar,OptArgs* optargs){
+
+	int i;  
+	
+	/*output: */
+	double J;
+	
+	/*parameters: */
+	int        solution_type,analysis_type;
+	bool       isstokes       = false;
+	bool       conserve_loads = true;
+	FemModel  *femmodel       = NULL;
+
+	/*Recover finite element model: */
+	femmodel=optargs->femmodel;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&isstokes,FlowequationIsstokesEnum);
+	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	/*set analysis type to compute velocity: */
+	if (solution_type==SteadystateSolutionEnum || solution_type==DiagnosticSolutionEnum){
+		femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
+	}
+	else if (solution_type==BalancethicknessSolutionEnum){
+		femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
+	}
+	else{
+		_error_("Solution %s not implemented yet",EnumToStringx(solution_type));
+	}
+
+	/*update parameter according to scalar: */ //false means: do not save control
+	InputControlUpdatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,search_scalar,false);
+
+	/*Run diagnostic with updated inputs: */
+	if (solution_type==SteadystateSolutionEnum){
+		diagnostic_core(femmodel);	//We need a 3D velocity!! (vz is required for the next thermal run)
+	}
+	else if (solution_type==DiagnosticSolutionEnum){
+		solver_nonlinear(femmodel,conserve_loads); 
+	}
+	else if (solution_type==BalancethicknessSolutionEnum){
+		solver_linear(femmodel); 
+	}
+	else{
+		_error_("Solution %s not implemented yet",EnumToStringx(solution_type));
+	}
+
+	/*Compute misfit for this velocity field.*/
+	CostFunctionx(&J, femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
+
+	/*Free ressources:*/
+	return J;
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/prognostic_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/prognostic_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/prognostic_core.cpp	(revision 11330)
@@ -0,0 +1,36 @@
+/*!\file: prognostic_core.cpp
+ * \brief: core of the prognostic solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../solvers/solvers.h"
+
+void prognostic_core(FemModel* femmodel){
+
+	/*parameters: */
+	int solution_type;
+	bool control_analysis;
+
+	/*activate formulation: */
+	femmodel->SetCurrentConfiguration(PrognosticAnalysisEnum);
+	
+	/*recover parameters: */
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	_printf_(VerboseSolution(),"   call computational core\n");
+	solver_linear(femmodel);
+		
+	if(solution_type==PrognosticSolutionEnum && !control_analysis){
+		_printf_(VerboseSolution(),"   saving results\n");
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ThicknessEnum);
+	}
+	
+}
+
Index: /issm/trunk-jpl-damage/src/c/solutions/solutions.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/solutions.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/solutions.h	(revision 11330)
@@ -0,0 +1,55 @@
+/*
+ * solutions.h: 
+ */
+
+#ifndef SOLUTIONS_H_
+#define SOLUTIONS_H_
+
+#include "../objects/objects.h"
+#include "../io/io.h"
+
+struct OptArgs;
+class FemModel;
+
+/*cores: */
+void adjointdiagnostic_core(FemModel* femmodel);
+void adjointbalancethickness_core(FemModel* femmodel);
+void gradient_core(FemModel* femmodel,int n=0,bool orthogonalize=false);
+void diagnostic_core(FemModel* femmodel);
+void hydrology_core(FemModel* femmodel);
+void hydrology_core_step(FemModel* femmodel,int step, double time);
+void thermal_core(FemModel* femmodel);
+void thermal_core_step(FemModel* femmodel,int step, double time);
+void enthalpy_core(FemModel* femmodel);
+void enthalpy_core_step(FemModel* femmodel,int step, double time);
+void surfaceslope_core(FemModel* femmodel);
+void bedslope_core(FemModel* femmodel);
+void control_core(FemModel* femmodel);
+void controltao_core(FemModel* femmodel);
+void prognostic_core(FemModel* femmodel);
+void balancethickness_core(FemModel* femmodel);
+void slopecompute_core(FemModel* femmodel);
+void steadystate_core(FemModel* femmodel);
+void transient_core(FemModel* femmodel);
+double objectivefunctionC(double search_scalar,OptArgs* optargs);
+
+//convergence:
+void convergence(bool* pconverged, Mat K_ff,Vec p_f,Vec u_f,Vec u_f_old,Parameters* parameters);
+bool controlconvergence(double J,double tol_cm);
+bool steadystateconvergence(FemModel* femmodel);
+
+//optimization
+int GradJSearch(double* search_vector,FemModel* femmodel,int step);
+
+//diverse
+void ProcessArguments(int* solution,char** pbinname,char** poutbinname,char** ppetscname,char** plockname,int argc,char **argv);
+void WriteLockFile(char* filename);
+void controlrestart(FemModel* femmodel,double* J);
+void ResetBoundaryConditions(FemModel* femmodel, int analysis_type);
+
+//solution configuration
+void AnalysisConfiguration(int** panalyses,int* pnumanalyses, int solutiontype);
+void CorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype);
+void AdjointCorePointerFromSolutionEnum(void (**padjointcore)(FemModel*),int solutiontype);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/solutions/steadystate_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/steadystate_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/steadystate_core.cpp	(revision 11330)
@@ -0,0 +1,91 @@
+/*!\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 "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void steadystate_core(FemModel* femmodel){
+
+	/*intermediary: */
+	int step; 
+
+	/*parameters: */
+	int dim;
+	int solution_type;
+	int maxiter;
+	bool control_analysis;
+	int  numoutputs         = 0;
+	int  *requested_outputs = NULL;
+	
+	/* recover parameters:*/
+	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&maxiter,SteadystateMaxiterEnum);
+	femmodel->parameters->FindParam(&numoutputs,SteadystateNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,SteadystateRequestedOutputsEnum);
+
+	/*intialize counters: */
+	step=1;
+
+	for(;;){
+	
+		_printf_(VerboseSolution(),"%s%i\n","   computing temperature and velocity for step: ",step);
+		#ifdef _HAVE_THERMAL_
+		thermal_core(femmodel);
+		#else
+		_error_("ISSM was not compiled with thermal capabilities. Exiting");
+		#endif
+
+		_printf_(VerboseSolution(),"%s\n","   computing new velocity");
+		diagnostic_core(femmodel);
+
+		if (step>1){
+			_printf_(VerboseSolution(),"%s\n","   checking velocity, temperature and pressure convergence");
+			if(steadystateconvergence(femmodel)) break;
+		}
+		if(step>maxiter){
+			_printf_(VerboseSolution(),"%s%i%s\n","   maximum number steadystate iterations ",maxiter," reached");
+			break;
+		}
+		
+		_printf_(VerboseSolution(),"%s\n","   saving velocity, temperature and pressure to check for convergence at next step");
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VxEnum,VxPicardEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VyEnum,VyPicardEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VzEnum,VzPicardEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,PressureEnum,PressurePicardEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,TemperatureEnum,TemperatureOldEnum);
+		
+		//increase counter
+		step++;
+	}
+	
+	if(solution_type==SteadystateSolutionEnum && !control_analysis){
+		_printf_(VerboseSolution(),"   saving results\n");
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VxEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VyEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VzEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VelEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,PressureEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,TemperatureEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BasalforcingsMeltingRateEnum);
+		RequestedOutputsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,requested_outputs,numoutputs);
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&requested_outputs);
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/steadystateconvergence.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/steadystateconvergence.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/steadystateconvergence.cpp	(revision 11330)
@@ -0,0 +1,43 @@
+/*!\file: steadystateconvergence.cpp
+ * \brief: determine convergence of steady state solution
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../Container/Container.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../include/include.h"
+#include "../modules/modules.h"
+#include "./solutions.h"
+
+bool steadystateconvergence(FemModel* femmodel){
+	
+	/*output: */
+	bool converged=false;
+	bool velocity_converged=false;
+	bool temperature_converged=false;
+
+	/*intermediary: */
+	int velocityenums[8]={VxEnum,VxPicardEnum,VyEnum,VyPicardEnum,VzEnum,VzPicardEnum,PressureEnum,PressurePicardEnum}; //pairs of enums (new and old) on which to carry out the converence tests
+	int temperatureenums[2]={TemperatureEnum,TemperatureOldEnum};
+	int convergencecriterion[1]={RelativeEnum}; //criterions for convergence, RelativeEnum or AbsoluteEnum 
+	double convergencecriterionvalue[1]; //value of criterion to be respected
+
+	/*retrieve parameters: */
+	femmodel->parameters->FindParam(&convergencecriterionvalue[0],SteadystateReltolEnum);
+	
+	/*figure out convergence at the input level, because we don't have the solution vectors!: */
+	velocity_converged=InputConvergencex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,&velocityenums[0],8,&convergencecriterion[0],&convergencecriterionvalue[0],1);
+	temperature_converged=InputConvergencex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,&temperatureenums[0],2,&convergencecriterion[0],&convergencecriterionvalue[0],1);
+
+	if(velocity_converged && temperature_converged) converged=true;
+
+	/*return: */
+	return converged;
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/surfaceslope_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/surfaceslope_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/surfaceslope_core.cpp	(revision 11330)
@@ -0,0 +1,41 @@
+/*!\file: surfaceslope_core.cpp
+ * \brief: core of the slope solution 
+ */ 
+
+#include "./solutions.h"
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../solvers/solvers.h"
+#include "../modules/modules.h"
+
+void surfaceslope_core(FemModel* femmodel){
+
+	/*parameters: */
+	int dim;
+	bool isstokes;
+	bool ishutter;
+	bool control_analysis;
+	int solution_type;
+
+	/*Recover some parameters: */
+	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	_printf_(VerboseSolution(),"%s\n","computing slope...");
+
+	/*Call on core computations: */
+	femmodel->SetCurrentConfiguration(SurfaceSlopeAnalysisEnum,SurfaceSlopeXAnalysisEnum);
+	solver_linear(femmodel);
+	femmodel->SetCurrentConfiguration(SurfaceSlopeAnalysisEnum,SurfaceSlopeYAnalysisEnum);
+	solver_linear(femmodel);
+	
+	if(solution_type==SurfaceSlopeSolutionEnum && !control_analysis){
+		_printf_(VerboseSolution(),"saving results:\n");
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceSlopeXEnum);
+		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceSlopeYEnum);
+	}
+
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/thermal_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/thermal_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/thermal_core.cpp	(revision 11330)
@@ -0,0 +1,65 @@
+/*!\file: thermal_core.cpp
+ * \brief: core of the thermal solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void thermal_core(FemModel* femmodel){
+
+	int i;
+
+	/*intermediary*/
+	double time;
+	int    nsteps;
+	double final_time;
+	double dt;
+	double melting_offset;
+	bool control_analysis;
+	int solution_type;
+	bool   dakota_analysis         = false;
+
+	//first recover parameters common to all solutions
+	femmodel->parameters->FindParam(&final_time,TimesteppingFinalTimeEnum);
+	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+
+	/*Compute number of time steps: */
+	if((dt==0)|| (final_time==0)){
+		dt=0;
+		nsteps=1;
+	}
+	else nsteps=(int)(final_time/dt);
+
+	if(dakota_analysis){
+		femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
+		ResetConstraintsx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	}
+
+	/*Loop through time: */
+	for(i=0;i<nsteps;i++){
+		
+		if(nsteps)_printf_(VerboseSolution(),"time step: %i/%i\n",i+1,nsteps);
+		time=(i+1)*dt;
+		femmodel->parameters->SetParam(time,TimeEnum);
+
+		/*call thermal_core_step: */
+		thermal_core_step(femmodel,i,time);
+
+		if(solution_type==ThermalSolutionEnum && !control_analysis){
+			_printf_(VerboseSolution(),"   saving results\n");
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,TemperatureEnum,i+1,time);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BasalforcingsMeltingRateEnum,i+1,time);
+		}
+
+	}
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/thermal_core_step.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/thermal_core_step.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/thermal_core_step.cpp	(revision 11330)
@@ -0,0 +1,24 @@
+/*!\file: thermal_core_step.cpp
+ * \brief: core of the thermal solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void thermal_core_step(FemModel* femmodel,int step, double time){
+
+	_printf_(VerboseSolution(),"   computing temperatures\n");
+	femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
+	solver_thermal_nonlinear(femmodel);
+
+	_printf_(VerboseSolution(),"   computing melting\n");
+	femmodel->SetCurrentConfiguration(MeltingAnalysisEnum);
+	solver_linear(femmodel);
+}
Index: /issm/trunk-jpl-damage/src/c/solutions/transient_core.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solutions/transient_core.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solutions/transient_core.cpp	(revision 11330)
@@ -0,0 +1,150 @@
+/*!\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 "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+#include <float.h>
+
+void transient_core(FemModel* femmodel){
+
+	/*parameters: */
+	double finaltime,dt,yts;
+	bool   control_analysis,isdiagnostic,isprognostic,isthermal,isgroundingline;
+	bool   dakota_analysis=false;
+	bool   time_adapt=false;
+	int    solution_type;
+	int    output_frequency;
+	int    dim,groundingline_migration;
+	int    numoutputs         = 0;
+	int    *requested_outputs = NULL;
+	
+	/*intermediary: */
+	int    step;
+	double time;
+
+	//first recover parameters common to all solutions
+	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
+	femmodel->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
+	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&output_frequency,SettingsOutputFrequencyEnum);
+	femmodel->parameters->FindParam(&time_adapt,TimesteppingTimeAdaptEnum);
+	femmodel->parameters->FindParam(&isdiagnostic,TransientIsdiagnosticEnum);
+	femmodel->parameters->FindParam(&isprognostic,TransientIsprognosticEnum);
+	femmodel->parameters->FindParam(&isthermal,TransientIsthermalEnum);
+	femmodel->parameters->FindParam(&isgroundingline,TransientIsgroundinglineEnum);
+	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=0;
+
+	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
+	if(dakota_analysis){
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVxEnum,VxEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVyEnum,VyEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVzEnum,VzEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuPressureEnum,PressureEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuThicknessEnum,ThicknessEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuSurfaceEnum,SurfaceEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuBedEnum,BedEnum);
+		if(isthermal && dim==3){
+			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuTemperatureEnum,TemperatureEnum);
+			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuMeltingEnum,BasalforcingsMeltingRateEnum);
+		}
+	}
+
+	while(time < finaltime - (yts*DBL_EPSILON)){ //make sure we run up to finaltime.
+
+		/*Increment*/
+		if(time_adapt){
+			TimeAdaptx(&dt,femmodel->elements, femmodel->nodes,femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters); 
+			if(time+dt>finaltime) dt=finaltime-time;
+			femmodel->parameters->SetParam(dt,TimesteppingTimeStepEnum);
+		}
+		step+=1;
+		time+=dt;
+		femmodel->parameters->SetParam(time,TimeEnum);
+
+		_printf_(VerboseSolution(),"iteration %i/%g  time [yr]: %-7.3g (time step: %.2g)\n",step,floor((finaltime-time)/dt)+step,time/yts,dt/yts);
+
+		if(isthermal && dim==3){
+			_printf_(VerboseSolution(),"   computing temperatures:\n");
+			#ifdef _HAVE_THERMAL_
+			thermal_core_step(femmodel,step,time);
+			#else
+			_error_("ISSM was not compiled with thermal capabilities. Exiting");
+			#endif
+		}
+
+		if(isdiagnostic){
+			_printf_(VerboseSolution(),"   computing new velocity\n");
+			#ifdef _HAVE_DIAGNOSTIC_
+			diagnostic_core(femmodel);
+			#else
+			_error_("ISSM was not compiled with diagnostic capabilities. Exiting");
+			#endif
+		}
+
+		if(isprognostic){
+			_printf_(VerboseSolution(),"   computing new thickness\n");
+			prognostic_core(femmodel);
+			_printf_(VerboseSolution(),"   updating vertices positions\n");
+			UpdateVertexPositionsx(femmodel->elements, femmodel->nodes,femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters); 
+		}
+
+		if(isgroundingline){
+			_printf_(VerboseSolution(),"   computing new grounding line position\n");
+			#ifdef _HAVE_GROUNDINGLINE_
+			GroundinglineMigrationx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+			#else
+			_error_("ISSM was not compiled with grounding line migration capabilities. Exiting");
+			#endif
+		}
+
+		//save should be done by the analysis... see control_core
+		if(solution_type==TransientSolutionEnum && !control_analysis && (step%output_frequency==0 || time==finaltime)){
+			_printf_(VerboseSolution(),"   saving results\n");
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VzMeshEnum,step,time);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VxEnum,step,time);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VyEnum,step,time);
+			if(dim==3) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VzEnum,step,time);
+			if(isdiagnostic)InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VelEnum,step,time);
+			if(isdiagnostic)InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,PressureEnum,step,time);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ThicknessEnum,step,time);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceEnum,step,time);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BedEnum,step,time);
+			if(dim==3 && isthermal) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,TemperatureEnum,step,time);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BasalforcingsMeltingRateEnum,step,time);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceforcingsMassBalanceEnum,step,time);
+			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,MaskElementonfloatingiceEnum,step,time);
+			RequestedOutputsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,requested_outputs,numoutputs,step,time);
+
+			/*unload results*/
+			_printf_(VerboseSolution(),"   saving temporary results\n");
+			OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,&femmodel->results);
+		}
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&requested_outputs);
+}
Index: /issm/trunk-jpl-damage/src/c/solvers/solver_adjoint_linear.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solvers/solver_adjoint_linear.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solvers/solver_adjoint_linear.cpp	(revision 11330)
@@ -0,0 +1,33 @@
+/*!\file: solver_adjoint_linear.cpp
+ * \brief: numerical core of linear solutions
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../modules/modules.h"
+
+void solver_adjoint_linear(FemModel* femmodel){
+	/*This is axactly the same solver as solver_linear except that Reduceloadfromgtofx and Mergesolutionfromftogx
+	 * use the flag "true" so that all spc are taken as 0*/
+
+	/*intermediary: */
+	Mat  Kff = NULL, Kfs = NULL;
+	Vec  ug  = NULL, uf  = NULL;
+	Vec  pf  = NULL;
+	Vec  df  = NULL;
+	Vec  ys  = NULL;
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
+
+	SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+	Reduceloadx(pf, Kfs, ys,true); MatFree(&Kfs); //true means spc = 0
+	Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); MatFree(&Kff); VecFree(&pf); VecFree(&df);
+	Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters,true); VecFree(&uf);VecFree(&ys); //true means spc0
+	InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug);
+	VecFree(&ug); VecFree(&uf); 
+}
Index: /issm/trunk-jpl-damage/src/c/solvers/solver_linear.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solvers/solver_linear.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solvers/solver_linear.cpp	(revision 11330)
@@ -0,0 +1,32 @@
+/*!\file: solver_linear.cpp
+ * \brief: numerical core of linear solutions
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../modules/modules.h"
+
+void solver_linear(FemModel* femmodel){
+
+	/*intermediary: */
+	Mat  Kff = NULL, Kfs   = NULL;
+	Vec  ug  = NULL;
+	Vec  uf  = NULL;
+	Vec  pf  = NULL;
+	Vec  df  = NULL;
+	Vec  ys  = NULL;
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
+
+	SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+	Reduceloadx(pf, Kfs, ys); MatFree(&Kfs);
+	Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); MatFree(&Kff); VecFree(&pf); VecFree(&df);
+	Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);VecFree(&uf);VecFree(&ys);
+	InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug); 
+	VecFree(&ug); VecFree(&uf);
+}
Index: /issm/trunk-jpl-damage/src/c/solvers/solver_nonlinear.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solvers/solver_nonlinear.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solvers/solver_nonlinear.cpp	(revision 11330)
@@ -0,0 +1,97 @@
+/*!\file: solver_nonlinear.cpp
+ * \brief: core of a non-linear solution, using fixed-point method 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../modules/modules.h"
+#include "../solutions/solutions.h"
+#include "./solvers.h"
+
+void solver_nonlinear(FemModel* femmodel,bool conserve_loads){
+
+	/*intermediary: */
+	Mat Kff = NULL, Kfs   = NULL;
+	Vec ug  = NULL, old_ug = NULL;
+	Vec uf  = NULL, old_uf = NULL;
+	Vec pf  = NULL;
+	Vec df  = NULL;
+	Vec ys  = NULL;
+	
+	Loads* loads=NULL;
+	bool converged;
+	int constraints_converged;
+	int num_unstable_constraints;
+	int count;
+
+	/*parameters:*/
+	int min_mechanical_constraints;
+	int max_nonlinear_iterations;
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&min_mechanical_constraints,DiagnosticRiftPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
+
+	/*Were loads requested as output? : */
+	if(conserve_loads) loads=(Loads*)femmodel->loads->Copy(); //protect loads from being modified by the solution
+	else               loads=(Loads*)femmodel->loads;         //modify loads  in this solution
+
+	count=1;
+	converged=false;
+
+	/*Start non-linear iteration using input velocity: */
+	GetSolutionFromInputsx(&ug, femmodel->elements, femmodel->nodes, femmodel->vertices, loads, femmodel->materials, femmodel->parameters);
+	Reducevectorgtofx(&uf, ug, femmodel->nodes,femmodel->parameters);
+
+	//Update once again the solution to make sure that vx and vxold are similar (for next step in transient or steadystate)
+	InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,converged,ConvergedEnum);
+	InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug);
+
+	for(;;){
+
+		//save pointer to old velocity
+		VecFree(&old_ug);old_ug=ug;
+		VecFree(&old_uf);old_uf=uf;
+
+		SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,loads,femmodel->materials,femmodel->parameters);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf, Kfs, ys); MatFree(&Kfs);
+		Solverx(&uf, Kff, pf, old_uf, df, femmodel->parameters);
+		Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);VecFree(&ys);
+
+		convergence(&converged,Kff,pf,uf,old_uf,femmodel->parameters); MatFree(&Kff);VecFree(&pf); VecFree(&df);
+		InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,converged,ConvergedEnum);
+		InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug);
+
+		ConstraintsStatex(&constraints_converged, &num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,loads,femmodel->materials,femmodel->parameters);
+		_printf_(VerboseConvergence(),"   number of unstable constraints: %i\n",num_unstable_constraints);
+
+		//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)break;
+		if(count>=max_nonlinear_iterations){
+			_printf_(true,"   maximum number of iterations (%i) exceeded\n",max_nonlinear_iterations); 
+			break;
+		}
+	}
+
+	/*clean-up*/
+	if(conserve_loads) delete loads;
+	VecFree(&uf);
+	VecFree(&ug);
+	VecFree(&old_ug);
+	VecFree(&old_uf);
+}
Index: /issm/trunk-jpl-damage/src/c/solvers/solver_stokescoupling_nonlinear.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solvers/solver_stokescoupling_nonlinear.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solvers/solver_stokescoupling_nonlinear.cpp	(revision 11330)
@@ -0,0 +1,98 @@
+/*!\file: solver_stokescoupling_nonlinear.cpp
+ * \brief: core of the coupling between stokes and macayealpattyn
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../io/io.h"
+#include "../modules/modules.h"
+#include "../solutions/solutions.h"
+#include "./solvers.h"
+
+void solver_stokescoupling_nonlinear(FemModel* femmodel,bool conserve_loads){
+
+	/*intermediary: */
+	Mat  Kff_horiz = NULL, Kfs_horiz   = NULL;
+	Vec  ug_horiz  = NULL, uf_horiz  = NULL, old_uf_horiz = NULL;
+	Vec  pf_horiz  = NULL;
+	Vec  df_horiz  = NULL;
+	Mat  Kff_vert  = NULL, Kfs_vert    = NULL;
+	Vec  ug_vert   = NULL, uf_vert   = NULL;
+	Vec  pf_vert   = NULL;
+	Vec  df_vert   = NULL;
+	Vec  ys   = NULL;
+	bool converged;
+	int  constraints_converged;
+	int  num_unstable_constraints;
+	int  count;
+
+	/*parameters:*/
+	int  min_mechanical_constraints;
+	int  max_nonlinear_iterations;
+	int  configuration_type;
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&min_mechanical_constraints,DiagnosticRiftPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
+	UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
+	
+	count=1;
+	converged=false;
+
+	/*First get ug_horiz:*/
+	femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
+	GetSolutionFromInputsx(&ug_horiz, femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters);
+	Reducevectorgtofx(&uf_horiz, ug_horiz, femmodel->nodes,femmodel->parameters);
+
+	for(;;){
+
+		/*First diagnostic horiz:*/
+		femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
+		femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	
+		//Update once again the solution to make sure that vx and vxold are similar (for next step in transient or steadystate)
+		InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug_horiz);
+		VecFree(&ug_horiz);
+
+		//save pointer to old velocity
+		VecFree(&old_uf_horiz);old_uf_horiz=uf_horiz;
+
+		/*solve: */
+		SystemMatricesx(&Kff_horiz, &Kfs_horiz, &pf_horiz, &df_horiz, NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf_horiz, Kfs_horiz, ys); MatFree(&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); VecFree(&ys);
+		InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug_horiz);
+
+		convergence(&converged,Kff_horiz,pf_horiz,uf_horiz,old_uf_horiz,femmodel->parameters); MatFree(&Kff_horiz);VecFree(&pf_horiz); VecFree(&df_horiz);
+
+		/*Second compute vertical velocity: */
+		femmodel->SetCurrentConfiguration(DiagnosticVertAnalysisEnum);
+		femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+		
+		/*solve: */
+		SystemMatricesx(&Kff_vert, &Kfs_vert, &pf_vert,  &df_vert,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf_vert, Kfs_vert, ys); MatFree(&Kfs_vert);
+		Solverx(&uf_vert, Kff_vert, pf_vert, NULL, df_vert,femmodel->parameters); MatFree(&Kff_vert); VecFree(&pf_vert); VecFree(&df_vert);
+		Mergesolutionfromftogx(&ug_vert, uf_vert,ys,femmodel->nodes,femmodel->parameters);VecFree(&uf_vert); VecFree(&ys);
+		InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug_vert);
+		VecFree(&ug_vert); VecFree(&uf_vert);
+
+		/*Increase count: */
+		count++;
+		if(converged==true)break;
+		if(count>=max_nonlinear_iterations){
+			_printf_(true,"   maximum number of iterations (%i) exceeded\n",max_nonlinear_iterations); 
+			break;
+		}
+	}
+
+	/*clean-up*/
+	VecFree(&old_uf_horiz);
+	VecFree(&uf_horiz);
+	VecFree(&ug_horiz);
+	VecFree(&ys);
+}
Index: /issm/trunk-jpl-damage/src/c/solvers/solver_thermal_nonlinear.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/solvers/solver_thermal_nonlinear.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solvers/solver_thermal_nonlinear.cpp	(revision 11330)
@@ -0,0 +1,90 @@
+/*!\file: solver_thermal_nonlinear.cpp
+ * \brief: core of the thermal solution 
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../objects/objects.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../modules/modules.h"
+
+void solver_thermal_nonlinear(FemModel* femmodel){
+
+	/*solution : */
+	Vec tg=NULL; 
+	Vec tf=NULL; 
+	Vec tf_old=NULL; 
+	Vec ys=NULL; 
+	double melting_offset;
+
+	/*intermediary: */
+	Mat Kff=NULL;
+	Mat Kfs=NULL;
+	Vec pf=NULL;
+	Vec df=NULL;
+
+	bool converged;
+	int constraints_converged;
+	int num_unstable_constraints;
+	int count;
+	int thermal_penalty_threshold;
+	int thermal_maxiter;
+
+	/*parameters:*/
+	int kflag,pflag;
+	bool lowmem=0;
+	int  configuration_type;
+
+
+	/*Recover parameters: */
+	kflag=1; pflag=1;
+	femmodel->parameters->FindParam(&lowmem,SettingsLowmemEnum);
+	femmodel->parameters->FindParam(&thermal_penalty_threshold,ThermalPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&thermal_maxiter,ThermalMaxiterEnum);
+
+	count=1;
+	converged=false;
+
+	_printf_(VerboseSolution(),"%s\n","starting direct shooting method");
+	InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,true,ResetPenaltiesEnum);
+	InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,false,ConvergedEnum);
+	UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
+
+	for(;;){
+
+		SystemMatricesx(&Kff, &Kfs, &pf,&df, &melting_offset,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+		Reduceloadx(pf, Kfs, ys); MatFree(&Kfs); VecFree(&tf);
+		Solverx(&tf, Kff, pf,tf_old, df, femmodel->parameters);
+		VecFree(&tf_old); VecDuplicatePatch(&tf_old,tf);
+		MatFree(&Kff);VecFree(&pf);VecFree(&tg); VecFree(&df);
+		Mergesolutionfromftogx(&tg, tf,ys,femmodel->nodes,femmodel->parameters); VecFree(&ys);
+		InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,tg);
+
+		ConstraintsStatex(&constraints_converged, &num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+
+		if (!converged){
+			_printf_(VerboseConvergence(),"%s%i\n","   #unstable constraints = ",num_unstable_constraints);
+			if (num_unstable_constraints <= thermal_penalty_threshold)converged=true;
+			if (count>=thermal_maxiter){
+				converged=true;
+				_printf_(true,"   maximum number of iterations (%i) exceeded\n",thermal_maxiter); 
+			}
+		}
+		count++;
+
+		InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,converged,ConvergedEnum);
+		
+		if(converged)break;
+	}
+
+	InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,tg);
+	InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,melting_offset,MeltingOffsetEnum);
+
+	/*Free ressources: */
+	VecFree(&tg);
+	VecFree(&tf);
+	VecFree(&tf_old);
+	VecFree(&ys);
+}
Index: /issm/trunk-jpl-damage/src/c/solvers/solvers.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/solvers/solvers.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/solvers/solvers.h	(revision 11330)
@@ -0,0 +1,20 @@
+/*
+ * solvers.h: 
+ */
+
+#ifndef SOLVERS_H_
+#define SOLVERS_H_
+
+#include "../objects/objects.h"
+#include "../io/io.h"
+
+struct OptArgs;
+class FemModel;
+
+void solver_thermal_nonlinear(FemModel* femmodel);
+void solver_nonlinear(FemModel* femmodel,bool conserve_loads);
+void solver_stokescoupling_nonlinear(FemModel* femmodel,bool conserve_loads);
+void solver_linear(FemModel* femmodel);
+void solver_adjoint_linear(FemModel* femmodel);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/toolkits/matlab/MatlabNArrayToNArray.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/matlab/MatlabNArrayToNArray.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/matlab/MatlabNArrayToNArray.cpp	(revision 11330)
@@ -0,0 +1,274 @@
+/* \file MatlabNArrayToNArray.cpp
+ * \brief: convert a sparse or dense matlab n-dimensional array to cpp n-dimensional array
+ */
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+
+#ifdef _SERIAL_
+#include <mex.h>
+
+/*FUNCTION MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{1*/
+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;
+	int     nnz;
+	int     nz;
+
+	/*get Matlab matrix information: */
+	numel=mxGetNumberOfElements(mxmatrix);
+	ndims=mxGetNumberOfDimensions(mxmatrix);
+	ipt  =mxGetDimensions(mxmatrix);
+	size =(int *) xcalloc(ndims,sizeof(int));
+	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);
+		nnz=mxGetNzmax(mxmatrix);
+		nz=(int)((double)nnz/(double)rows);
+
+		matrix=(double*)xcalloc(rows*cols,sizeof(double));
+
+		/*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=(double*)xcalloc(numel,sizeof(double));
+
+		dims=(int *) xcalloc(ndims,sizeof(int));
+		for(i=0;i<numel;i++){
+			ColumnWiseDimsFromIndex(dims,i,size,ndims);
+			j=IndexFromRowWiseDims(dims,size,ndims);
+			*(matrix+j)=*(mxmatrix_ptr+i);
+		}
+		xfree((void**)&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){{{1*/
+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;
+	int     nnz;
+	int     nz;
+
+	/*get Matlab matrix information: */
+	numel=mxGetNumberOfElements(mxmatrix);
+	ndims=mxGetNumberOfDimensions(mxmatrix);
+	ipt  =mxGetDimensions(mxmatrix);
+	size =(int *) xcalloc(ndims,sizeof(int));
+	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);
+		nnz=mxGetNzmax(mxmatrix);
+		nz=(int)((double)nnz/(double)rows);
+
+		matrix=(bool*)xcalloc(rows*cols,sizeof(bool));
+
+		/*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=(bool*)xcalloc(numel,sizeof(bool));
+
+		dims=(int *) xcalloc(ndims,sizeof(int));
+		for(i=0;i<numel;i++){
+			ColumnWiseDimsFromIndex(dims,i,size,ndims);
+			j=IndexFromRowWiseDims(dims,size,ndims);
+			*(matrix+j)=(bool)*(mxmatrix_ptr+i);
+		}
+		xfree((void**)&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){{{1*/
+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;
+	int     nnz;
+	int     nz;
+
+	/*get Matlab matrix information: */
+	numel=mxGetNumberOfElements(mxmatrix);
+	ndims=mxGetNumberOfDimensions(mxmatrix);
+	ipt  =mxGetDimensions(mxmatrix);
+	size =(int *) xcalloc(ndims,sizeof(int));
+	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);
+		nnz=mxGetNzmax(mxmatrix);
+		nz=(int)((double)nnz/(double)rows);
+
+		matrix=(char*)xcalloc(rows*cols,sizeof(double));
+
+		/*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=(char*)xcalloc(numel+1,sizeof(mxChar));
+
+		/*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;
+}
+/*}}}*/
+#endif
Index: /issm/trunk-jpl-damage/src/c/toolkits/matlab/matlabincludes.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/matlab/matlabincludes.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/matlab/matlabincludes.h	(revision 11330)
@@ -0,0 +1,15 @@
+/* \file matlabincludes.h
+ * \brief all includes for Matlab patches
+ */
+
+#ifndef _MATLAB_INCLUDES_H_
+#define _MATLAB_INCLUDES_H_
+
+#ifdef _SERIAL_
+#include <mex.h>
+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);
+#endif
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/toolkits/metis/metisincludes.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/metis/metisincludes.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/metis/metisincludes.h	(revision 11330)
@@ -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/trunk-jpl-damage/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp	(revision 11330)
@@ -0,0 +1,67 @@
+/*!\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 way 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=(idx_t*)xmalloc((*pnumberofelements+1)*sizeof(idx_t));
+	eptr[0]=0;
+	for(i=0;i<*pnumberofelements;i++){
+		k+=3;
+		eptr[i+1]=k;
+	}
+
+
+	/*create tpwgts: */
+	tpwgts=(real_t*)xmalloc(*pnum_procs*sizeof(real_t));
+	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);
+	
+
+	#else
+	_error_("METIS version not supported yet");
+	#endif
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/metis/patches/metispatches.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/metis/patches/metispatches.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/metis/patches/metispatches.h	(revision 11330)
@@ -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/trunk-jpl-damage/src/c/toolkits/mpi/mpiincludes.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/mpi/mpiincludes.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/mpi/mpiincludes.h	(revision 11330)
@@ -0,0 +1,14 @@
+/* \file mpiincludes.h
+ * \brief all includes for MPI layer
+ */
+
+#ifndef _MPI_INCLUDES_H_
+#define _MPI_INCLUDES_H_
+
+/*MPI includes: */
+#include "mpi.h"
+
+/*Patches: */
+#include "./patches/mpipatches.h"
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/toolkits/mpi/patches/MPI_Boundariesfromrange.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/mpi/patches/MPI_Boundariesfromrange.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/mpi/patches/MPI_Boundariesfromrange.cpp	(revision 11330)
@@ -0,0 +1,43 @@
+/*!\file MPI_Boundariesfromrange.cpp
+ * \brief: routine to figure out from a range distribution, the lower and upper 
+ * bounds for the current cpu.
+ */
+
+#include "../../petsc/patches/petscpatches.h"
+#include "./mpipatches.h"
+#include "../../../shared/shared.h"
+
+int MPI_Boundariesfromrange(int* plower_row, int* pupper_row,int range){
+
+	extern int num_procs;
+	extern int my_rank;
+	
+	/*output: */
+	int lower_row,upper_row;
+
+	/*intermediary: */
+	int  i;
+	int* allranges=NULL;
+
+	/*Gather all range values into allranges, for all nodes*/
+	allranges=(int*)xmalloc(num_procs*sizeof(int));
+	MPI_Allgather(&range,1,MPI_INT,allranges,1,MPI_INT,MPI_COMM_WORLD);
+
+
+	/*From all ranges, get lower row and upper row*/
+	lower_row=0;
+	upper_row=lower_row+allranges[0];
+	for (i=1;i<=my_rank;i++){
+		lower_row=lower_row+allranges[i-1];
+		upper_row=upper_row+allranges[i];
+	}
+	
+	/*free: */
+	xfree((void**)&allranges);
+
+	/*Assign output pointers: */
+	*plower_row=lower_row;
+	*pupper_row=upper_row;
+
+	return 1;
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/mpi/patches/MPI_Lowerrow.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/mpi/patches/MPI_Lowerrow.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/mpi/patches/MPI_Lowerrow.cpp	(revision 11330)
@@ -0,0 +1,28 @@
+/*!\file MPI_Lowerrow.cpp
+ * \brief: routine to distribute jobs in parallel. 
+ * This handy routine will provide, along with the MPI_Upperrow, a distributed range 
+ * for an index (like i,j, in a for loop). 
+ * Ex: for(i=MPI_Lowerrow(num_procs)0;i<MPI_Upperrow(num_procs);i++)
+ * This ensures easy parallelisation of loops if needed.
+ */
+
+#include "../../petsc/patches/petscpatches.h"
+#include "./mpipatches.h"
+
+int MPI_Lowerrow(int n){
+
+
+	int range;
+	int lower_row;
+	int upper_row;
+	
+
+	/*First, figure out our range : */
+	range=PetscDetermineLocalSize(n);
+
+	/*Now determien upper and lower boundaries: */
+	MPI_Boundariesfromrange(&lower_row,&upper_row,range);
+
+	return lower_row;
+	
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/mpi/patches/MPI_Upperrow.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/mpi/patches/MPI_Upperrow.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/mpi/patches/MPI_Upperrow.cpp	(revision 11330)
@@ -0,0 +1,31 @@
+/*!\file MPI_Upperrow.cpp
+ * \brief: routine to distribute jobs in parallel. 
+ * This handy routine will provide, along with the MPI_Lowrrow, a distributed range 
+ * for an index (like i,j, in a for loop). 
+ * Ex: for(i=MPI_Lowerrow(num_procs)0;i<MPI_Upperrow(num_procs);i++)
+ * This ensures easy parallelisation of loops if needed.
+ */
+
+#include "../../petsc/patches/petscpatches.h"
+#include "./mpipatches.h"
+
+int MPI_Upperrow(int n){
+
+	int range;
+	int lower_row;
+	int upper_row;
+
+	/*First, figure out our range : */
+	range=PetscDetermineLocalSize(n);
+
+	/*Now determien upper and lower boundaries: */
+	MPI_Boundariesfromrange(&lower_row,&upper_row,range);
+
+	return upper_row;
+	
+}
+
+
+
+
+
Index: /issm/trunk-jpl-damage/src/c/toolkits/mpi/patches/mpipatches.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/mpi/patches/mpipatches.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/mpi/patches/mpipatches.h	(revision 11330)
@@ -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_
+
+
+int MPI_Boundariesfromrange(int* plower_row, int* pupper_row,int range);
+int MPI_Lowerrow(int n);
+int MPI_Upperrow(int n);
+
+
+
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp	(revision 11330)
@@ -0,0 +1,48 @@
+/*! \file:  GetOwnershipBoundariesFromRange.cpp
+ *  \brief from a local range on each cpu, we determine what 
+ *  lower row and upper row from a matrix a cpu owns.
+ */
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include "../../../shared/shared.h"
+
+void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range){
+
+	/*externals :*/
+	extern int my_rank;
+	extern int num_procs;
+	
+	/*output: */
+	int lower_row,upper_row;
+	
+	/*intermediary :*/
+	int i;
+	int* allranges=NULL;
+
+	/*Gather all range values into allranges, for all nodes*/
+	allranges=(int*)xmalloc(num_procs*sizeof(int));
+	MPI_Allgather(&range,1,MPI_INT,allranges,1,MPI_INT,MPI_COMM_WORLD);
+
+	/*From all ranges, get lower row and upper row*/
+	lower_row=0;
+	upper_row=lower_row+allranges[0];
+	for (i=1;i<=my_rank;i++){
+		lower_row=lower_row+allranges[i-1];
+		upper_row=upper_row+allranges[i];
+	}
+
+	/*Assign output*/
+	*plower_row=lower_row;
+	*pupper_row=upper_row;
+
+	/*Free ressources:*/
+	xfree((void**)&allranges);
+
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISFree.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISFree.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISFree.cpp	(revision 11330)
@@ -0,0 +1,28 @@
+/*!\file:  ISFree.cpp
+ * \brief wrapper to ISDestroy
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+
+/*Petsc includes: */
+#include "petscmat.h"
+#include "petscmat.h"
+#include "petscksp.h"
+
+void ISFree(IS* pis){
+
+	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+	if(*pis)ISDestroy(*pis);
+	*pis=NULL;
+	#else
+	if(*pis)ISDestroy(pis);
+	*pis=NULL;
+	#endif
+
+}
+
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/KSPFree.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/KSPFree.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/KSPFree.cpp	(revision 11330)
@@ -0,0 +1,28 @@
+/*!\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/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatFree.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatFree.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatFree.cpp	(revision 11330)
@@ -0,0 +1,28 @@
+/*!\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/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatInvert.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatInvert.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatInvert.cpp	(revision 11330)
@@ -0,0 +1,77 @@
+/*!\file:  MatInvert.cpp
+ * \brief  invert petsc matrix using LU factorization, and multiple right hand sides.
+ */ 
+
+/*Petsc includes: */
+#include "petscmat.h"
+#include "petscvec.h"
+#include "petscksp.h"
+
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+
+void MatInvert(Mat* pinv, Mat matrix){
+
+
+	/*output: */
+	Mat inv=NULL;
+
+	/*intermediary: */
+	int M,N;
+	double sparsity=.001;
+
+	Mat factored_matrix=NULL;
+	Mat identity=NULL;
+	Vec diagonal=NULL;
+	KSP ksp=NULL;
+	PC pc=NULL;
+
+	/*Some checks: */
+	MatGetSize(matrix,&M,&N);
+	if(M!=N) _error_("trying to invert a non square matrix!");
+
+	/*Create identitiy matrix: */
+	identity=NewMat(M,N,sparsity);
+	diagonal=NewVec(M);
+	VecSet(diagonal,1.0);
+	MatDiagonalSet(identity,diagonal,INSERT_VALUES);
+	MatAssemblyBegin(identity,MAT_FINAL_ASSEMBLY);
+	MatAssemblyEnd(identity,MAT_FINAL_ASSEMBLY);
+	MatConvert(identity, MATMPIDENSE,MAT_REUSE_MATRIX,&identity);
+	
+	/*Initialize inverse: */
+	MatDuplicate(identity,MAT_DO_NOT_COPY_VALUES,&inv);
+
+	/* Compute X=inv(A) by MatMatSolve(), from tests in petsc test27 */
+	KSPCreate(PETSC_COMM_WORLD,&ksp);
+	KSPSetOperators(ksp,matrix,matrix,DIFFERENT_NONZERO_PATTERN);
+	KSPGetPC(ksp,&pc);
+	PCSetType(pc,PCLU);
+	KSPSetUp(ksp);
+	//PCGetFactoredMatrix(pc,&factored_matrix); //not found any replacement yet
+	MatMatSolve(factored_matrix,identity,inv);
+
+	/*Assemble inverse: */
+	MatAssemblyBegin(inv,MAT_FINAL_ASSEMBLY);
+	MatAssemblyEnd(inv,MAT_FINAL_ASSEMBLY);
+
+	#ifdef _SERIAL_
+		MatConvert(inv, MATSEQAIJ,MAT_REUSE_MATRIX,&inv);
+	#else
+		MatConvert(inv, MATMPIAIJ,MAT_REUSE_MATRIX,&inv);
+	#endif
+	
+	/*Free ressources:*/
+	MatFree(&identity);
+	VecFree(&diagonal);
+	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+	KSPDestroy(ksp);
+	#else
+	KSPDestroy(&ksp);
+	#endif
+
+	/*Assign output pointers:*/
+	*pinv=inv;
+
+}
+
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatMultPatch.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatMultPatch.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatMultPatch.cpp	(revision 11330)
@@ -0,0 +1,111 @@
+/*!\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 "../../../shared/shared.h"
+
+/*Function prototypes: */
+int MatMultCompatible(Mat A,Vec x);
+void VecRelocalize(Vec* outvector,Vec vector,int m);
+
+void MatMultPatch(Mat A,Vec X, Vec AX){ //same prototype as MatMult in Petsc
+
+	int m,n;
+	Vec X_rel=NULL;
+
+	_assert_(A); _assert_(X);
+
+	if (MatMultCompatible(A,X)){
+		MatMult(A,X,AX); 
+	}
+	else{
+		MatGetLocalSize(A,&m,&n);;
+		VecRelocalize(&X_rel,X,n);
+		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){
+	
+	/*error management*/
+	
+	int local_m,local_n;
+	int lower_row,upper_row,range;
+	int result=1;
+	int sumresult;
+	extern int num_procs;
+
+	MatGetLocalSize(A,&local_m,&local_n);;
+	VecGetLocalSize(x,&range);;
+	
+	if (local_n!=range)result=0;
+	
+	/*synchronize result: */
+	MPI_Reduce (&result,&sumresult,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&sumresult,1,MPI_INT,0,MPI_COMM_WORLD);                
+	if (sumresult!=num_procs){
+		result=0;
+	}
+	else{
+		result=1;\
+	}
+	return result;
+}
+
+void VecRelocalize(Vec* poutvector,Vec vector,int m){
+
+	/*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(PETSC_COMM_WORLD,&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=(int*)xmalloc(range*sizeof(int));
+		values=(double*)xmalloc(range*sizeof(double));
+		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:*/
+	xfree((void**)&index);
+	xfree((void**)&values);	
+
+	/*Assign output pointers:*/
+	*poutvector=outvector;
+
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatPartition.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatPartition.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatPartition.cpp	(revision 11330)
@@ -0,0 +1,126 @@
+/*!\file: MatPartition.cpp
+ * \brief partition matrix according to node sets
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*Petsc includes: */
+#include "petscmat.h"
+#include "petscvec.h"
+#include "petscksp.h"
+
+#include "../../../shared/shared.h"
+
+int MatPartition(Mat* poutmatrix,Mat matrixA,double* row_partition_vector,int row_partition_vector_size ,
+		double* col_partition_vector,int col_partition_vector_size){
+
+	int i;
+	
+	/*Petsc matrix*/
+	int d_nz;
+	int o_nz;
+	int* node_rows=NULL;
+	int* node_cols=NULL;
+	int count;
+	IS col_index=NULL;
+	IS row_index=NULL;
+	int lower_row,upper_row,range;
+	int MA,NA; //matrixA dimensions
+	const char* type=NULL;
+	int csize;
+
+	/*output*/
+	Mat outmatrix=NULL;
+	
+	/*get input matrix size: */
+	MatGetSize(matrixA,&MA,&NA);
+
+    /*If one of the partitioning row or col vectors has a 0 dimension, we return a NILL matrix. Return it with the same type as matrixA.*/
+	
+    if ((row_partition_vector_size==0) || (col_partition_vector==0)){
+		MatGetType(matrixA,&type);
+		if (strcmp(type,"mpiaij")==0){
+			d_nz=0;
+			o_nz=0;
+			MatCreateMPIAIJ(MPI_COMM_WORLD,PETSC_DETERMINE,PETSC_DETERMINE, 0,0,d_nz,PETSC_NULL,o_nz,PETSC_NULL,&outmatrix);
+		}
+		else if (strcmp(type,"mpidense")==0){
+			MatCreateMPIDense(MPI_COMM_WORLD,PETSC_DETERMINE,PETSC_DETERMINE, 0,0,PETSC_NULL,&outmatrix);
+		}
+		/*Assemble*/
+		MatAssemblyBegin(outmatrix,MAT_FINAL_ASSEMBLY);
+		MatAssemblyEnd(outmatrix,MAT_FINAL_ASSEMBLY);
+	}
+	else{
+		/*Both vectors are non nill, use MatGetSubMatrix to condense out*/
+		/*Figure out which rows each node is going to get from matrix A.*/
+		MatGetOwnershipRange(matrixA,&lower_row,&upper_row);
+		upper_row--;
+		range=upper_row-lower_row+1;
+
+		count=0;
+		if (range){
+			node_rows=(int*)xmalloc(range*sizeof(int)); //this is the maximum number of rows one node can extract.
+		
+			for (i=0;i<row_partition_vector_size;i++){
+				if ( ((int)(*(row_partition_vector+i))>=(lower_row+1)) && ((int)(*(row_partition_vector+i))<=(upper_row+1)) ){
+					*(node_rows+count)=(int)*(row_partition_vector+i)-1;
+					count++;
+				}
+			}
+		}
+		else{
+			count=0;
+		}
+		
+		/*Now each node has a node_rows vectors holding which rows they should extract from matrixA. Create an Index Set from node_rows.*/
+		#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+		ISCreateGeneral(MPI_COMM_WORLD,count,node_rows,&row_index);
+		#else
+		ISCreateGeneral(MPI_COMM_WORLD,count,node_rows,PETSC_COPY_VALUES,&row_index);
+		#endif
+		
+		/*Same deal for columns*/
+		node_cols=(int*)xmalloc(col_partition_vector_size*sizeof(int));
+		for (i=0;i<col_partition_vector_size;i++){
+			*(node_cols+i)=(int)*(col_partition_vector+i)-1;
+		}
+		#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+		ISCreateGeneral(MPI_COMM_WORLD,col_partition_vector_size,node_cols,&col_index);
+		#else
+		ISCreateGeneral(MPI_COMM_WORLD,col_partition_vector_size,node_cols,PETSC_COPY_VALUES,&col_index);
+		#endif
+
+		/*Call MatGetSubMatrix*/
+		csize=PetscDetermineLocalSize(col_partition_vector_size);
+		if(col_partition_vector_size==row_partition_vector_size){
+			#if _PETSC_MAJOR_ >= 3 
+			MatGetSubMatrix(matrixA,row_index,col_index,MAT_INITIAL_MATRIX,&outmatrix);
+			#else
+			MatGetSubMatrix(matrixA,row_index,col_index,count,MAT_INITIAL_MATRIX,&outmatrix);
+			#endif
+		}
+		else{
+			#if _PETSC_MAJOR_ >= 3 
+			MatGetSubMatrix(matrixA,row_index,col_index,MAT_INITIAL_MATRIX,&outmatrix);
+			#else
+			MatGetSubMatrix(matrixA,row_index,col_index,csize,MAT_INITIAL_MATRIX,&outmatrix);
+			#endif
+		}
+
+	}
+
+	/*Free ressources:*/
+	xfree((void**)&node_rows);
+	xfree((void**)&node_cols);
+	ISFree(&col_index);
+	ISFree(&row_index);
+
+	/*Assign output pointers:*/
+	*poutmatrix=outmatrix;
+	return 1;
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatToSerial.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatToSerial.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatToSerial.cpp	(revision 11330)
@@ -0,0 +1,83 @@
+/*!\file MatToSerial.cpp
+ * \brief gather a Petsc Mat matrix onto cpu 0
+ */
+
+#include "../petscincludes.h"
+#include "../../../shared/shared.h"
+
+void MatToSerial(double** poutmatrix,Mat matrix){
+
+	int i;
+	extern int my_rank;
+	extern int num_procs;
+	
+	/*Petsc variables*/
+	PetscInt lower_row,upper_row; 
+	int range;
+	int M,N; //size of matrix
+	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];
+	
+	/*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=(double*)xmalloc(M*N*sizeof(double));
+	
+	if (range){
+		local_matrix=(double*)xmalloc(N*range*sizeof(double));
+		idxm=(int*)xmalloc(range*sizeof(int));  
+		idxn=(int*)xmalloc(N*sizeof(int));  
+	 
+		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;
+			MPI_Send(buffer,3,MPI_INT,0,1,MPI_COMM_WORLD);   
+			if (range)MPI_Send(local_matrix,N*range,MPI_DOUBLE,0,1,MPI_COMM_WORLD); 
+		}
+		if (my_rank==0){
+			MPI_Recv(buffer,3,MPI_INT,i,1,MPI_COMM_WORLD,&status); 
+			if (buffer[2])MPI_Recv(outmatrix+(buffer[1]*N),N*buffer[2],MPI_DOUBLE,i,1,MPI_COMM_WORLD,&status);
+		}
+	} 
+	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;
+	
+	xfree((void**)&idxm);
+	xfree((void**)&idxn);
+	xfree((void**)&local_matrix);
+
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatlabMatrixToDoubleMatrix.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatlabMatrixToDoubleMatrix.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatlabMatrixToDoubleMatrix.cpp	(revision 11330)
@@ -0,0 +1,97 @@
+/* \file MatlabMatrixToDoubleMatrix.cpp
+ * \brief: convert a sparse or dense matlab matrix to a double* pointer
+ */
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+
+#ifdef _SERIAL_
+
+/*Petsc includes: */
+#include "petscmat.h"
+#include "petscvec.h"
+#include "petscksp.h"
+
+/*Matlab includes: */
+#include "mex.h"
+
+#include "../../../shared/shared.h"
+
+int MatlabMatrixToDoubleMatrix(double** pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix){
+
+	int rows, cols;
+	double* mxmatrix_ptr=NULL;
+	int ierr;
+	int i,j;
+
+	/*output: */
+	double* matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex*    ir=NULL;
+	mwIndex*    jc=NULL;
+	double* pr=NULL;
+	int     count;
+	int     nnz;
+	int     nz;
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+		nnz=mxGetNzmax(mxmatrix);
+		nz=(int)((double)nnz/(double)rows);
+
+		matrix=(double*)xcalloc(rows*cols,sizeof(double));
+
+		/*Now, get ir,jc and pr: */
+		pr=mxGetPr(mxmatrix);
+		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)=pr[count];
+				count++;
+			}
+		}
+
+	}
+	else{
+
+
+		/*Dealing with dense matrix: recover pointer and size: */
+		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		
+		/*Create serial matrix: */
+		matrix=(double*)xcalloc(rows*cols,sizeof(double));
+
+		for(i=0;i<rows;i++){
+			for(j=0;j<cols;j++){
+				*(matrix+cols*i+j)=*(mxmatrix_ptr+rows*j+i);
+			}
+		}
+		
+	}
+
+	/*Assign output pointer: */
+	*pmatrix=matrix;
+	*pmatrix_rows=rows;
+	*pmatrix_cols=cols;
+
+	return 1;
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatlabMatrixToPetscMatrix.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatlabMatrixToPetscMatrix.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatlabMatrixToPetscMatrix.cpp	(revision 11330)
@@ -0,0 +1,123 @@
+/* \file MatlabMatrixToPetscMatrix.cpp
+ * \brief: convert a sparse or dense matlab matrix to a serial Petsc matrix:
+ */
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+
+#ifdef _SERIAL_
+
+/*Petsc includes: */
+#include "petscmat.h"
+#include "petscvec.h"
+#include "petscksp.h"
+
+/*Matlab includes: */
+#include "mex.h"
+
+#include "../../../shared/shared.h"
+
+int MatlabMatrixToPetscMatrix(Mat* pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix){
+
+	int rows, cols;
+	double* mxmatrix_ptr=NULL;
+	double* tmatrix=NULL;
+	int ierr;
+	int i,j;
+
+	/*output: */
+	Mat matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex*    ir=NULL;
+	mwIndex*    jc=NULL;
+	double* pr=NULL;
+	int     count;
+	int     nnz;
+	int     nz;
+
+	/*petsc indices: */
+	int* idxm=NULL;
+	int* idxn=NULL;
+	
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+		nnz=mxGetNzmax(mxmatrix);
+		if(rows){
+			nz=(int)((double)nnz/(double)rows);
+		}
+		else{
+			nz=0;
+		}
+
+		ierr=MatCreateSeqAIJ(PETSC_COMM_SELF,rows,cols,nz,PETSC_NULL,&matrix);CHKERRQ(ierr);
+
+		/*Now, get ir,jc and pr: */
+		pr=mxGetPr(mxmatrix);
+		ir=mxGetIr(mxmatrix);
+		jc=mxGetJc(mxmatrix);
+
+		/*Now, start inserting data into sparse matrix: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				MatSetValue(matrix,ir[count],i,pr[count],INSERT_VALUES);
+				count++;
+			}
+		}
+
+	}
+	else{
+
+		/*Dealing with dense matrix: recover pointer and size: */
+		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*transpose, as Petsc now does not allows MAT_COLUMN_ORIENTED matrices in MatSetValues: */
+		tmatrix=(double*)xmalloc(rows*cols*sizeof(double));
+		for(i=0;i<cols;i++){
+			for(j=0;j<rows;j++){
+				*(tmatrix+rows*i+j)=*(mxmatrix_ptr+cols*j+i);
+			}
+		}
+
+		/*Create serial matrix: */
+		ierr=MatCreateSeqDense(PETSC_COMM_SELF,rows,cols,NULL,&matrix);CHKERRQ(ierr);
+
+		/*Insert mxmatrix_ptr values into petsc matrix: */
+		idxm=(int*)xmalloc(rows*sizeof(int));
+		idxn=(int*)xmalloc(cols*sizeof(int));
+
+		for(i=0;i<rows;i++)idxm[i]=i;
+		for(i=0;i<cols;i++)idxn[i]=i;
+
+		ierr=MatSetValues(matrix,rows,idxm,cols,idxn,tmatrix,INSERT_VALUES); CHKERRQ(ierr);
+
+		xfree((void**)&tmatrix);
+
+	}
+
+	/*Assemble matrix: */
+	MatAssemblyBegin(matrix,MAT_FINAL_ASSEMBLY); 
+	MatAssemblyEnd(matrix,MAT_FINAL_ASSEMBLY);
+
+
+	/*Assign output pointer: */
+	*pmatrix=matrix;
+	*pmatrix_rows=rows;
+	*pmatrix_cols=cols;
+
+	return 1;
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatlabVectorToDoubleVector.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatlabVectorToDoubleVector.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatlabVectorToDoubleVector.cpp	(revision 11330)
@@ -0,0 +1,98 @@
+/* \file MatlabVectorToDoubleVector.cpp
+ * \brief: convert a sparse or dense matlab vector to a serial vector:
+ */
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+
+#ifdef _SERIAL_
+
+#include <string.h>
+
+/*Petsc includes: */
+#include "petscmat.h"
+#include "petscvec.h"
+#include "petscksp.h"
+
+
+/*Matlab includes: */
+#include "mex.h"
+
+#include "../../../shared/shared.h"
+
+int MatlabVectorToDoubleVector(double** pvector,int* pvector_rows,const mxArray* mxvector){
+
+	int rows,cols;
+	double* mxvector_ptr=NULL;
+	int ierr;
+	int i,j;
+
+	/*output: */
+	double* vector=NULL;
+
+	/*matlab indices: */
+	mwIndex*    ir=NULL;
+	mwIndex*    jc=NULL;
+	double* pr=NULL;
+	int     count;
+	int     nnz;
+	int     nz;
+
+	/*Ok, first check if we are dealing with a sparse or full vector: */
+	if (mxIsSparse(mxvector)){
+
+		/*Dealing with sparse vector: recover size first: */
+		mxvector_ptr=(double*)mxGetPr(mxvector);
+		rows=mxGetM(mxvector);
+		cols=mxGetN(mxvector);
+		nnz=mxGetNzmax(mxvector);
+		
+		/*Check that input is actualy a vector*/
+		if (cols!=1) _error_("input vector of size %ix%i should have only one column",rows,cols);
+
+		nz=(int)((double)nnz/(double)rows);
+
+		vector=(double*)xcalloc(rows,sizeof(double));
+
+		/*Now, get ir,jc and pr: */
+		pr=mxGetPr(mxvector);
+		ir=mxGetIr(mxvector);
+		jc=mxGetJc(mxvector);
+
+		/*Now, start inserting data into sparse vector: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				vector[ir[count]]=pr[count];
+				count++;
+			}
+		}
+
+	}
+	else{
+
+		/*Dealing with dense vector: recover pointer and size: */
+		mxvector_ptr=(double*)mxGetPr(mxvector);
+		rows=mxGetM(mxvector);
+		cols=mxGetN(mxvector);
+
+		/*Check that input is actualy a vector*/
+		if (cols!=1) _error_("input vector of size %ix%i should have only one column",rows,cols);
+
+		/*allocate and memcpy*/
+		vector=(double*)xmalloc(rows*sizeof(double));
+		memcpy(vector,mxvector_ptr,rows*sizeof(double));
+	}
+
+	/*Assign output pointer: */
+	*pvector=vector;
+	*pvector_rows=rows;
+
+	return 1;
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatlabVectorToPetscVector.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatlabVectorToPetscVector.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatlabVectorToPetscVector.cpp	(revision 11330)
@@ -0,0 +1,103 @@
+/* \file MatlabVectorToPetscVector.cpp
+ * \brief: convert a sparse or dense matlab vector to a serial Petsc vector:
+ */
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+
+#ifdef _SERIAL_
+
+/*Petsc includes: */
+#include "petscmat.h"
+#include "petscvec.h"
+#include "petscksp.h"
+
+/*Matlab includes: */
+#include "mex.h"
+
+#include "../../../shared/shared.h"
+
+int MatlabVectorToPetscVector(Vec* pvector,int* pvector_rows,const mxArray* mxvector){
+
+	int rows, cols;
+	double* mxvector_ptr=NULL;
+	int ierr;
+	int i,j;
+
+	/*output: */
+	Vec vector=NULL;
+
+	/*matlab indices: */
+	mwIndex*    ir=NULL;
+	mwIndex*    jc=NULL;
+	double* pr=NULL;
+	int     count;
+	int     nnz;
+	int     nz;
+
+	/*petsc indices: */
+	int* idxm=NULL;
+	
+	/*Ok, first check if we are dealing with a sparse or full vector: */
+	if (mxIsSparse(mxvector)){
+
+		/*Dealing with sparse vector: recover size first: */
+		mxvector_ptr=(double*)mxGetPr(mxvector);
+		rows=mxGetM(mxvector);
+		cols=mxGetN(mxvector);
+		nnz=mxGetNzmax(mxvector);
+		nz=(int)((double)nnz/(double)rows);
+
+		ierr=VecCreateSeq(PETSC_COMM_SELF,rows,&vector);CHKERRQ(ierr);
+
+		/*Now, get ir,jc and pr: */
+		pr=mxGetPr(mxvector);
+		ir=mxGetIr(mxvector);
+		jc=mxGetJc(mxvector);
+
+		/*Now, start inserting data into sparse vector: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				VecSetValue(vector,ir[count],pr[count],INSERT_VALUES);
+				count++;
+			}
+		}
+
+	}
+	else{
+
+		/*Dealing with dense vector: recover pointer and size: */
+		mxvector_ptr=(double*)mxGetPr(mxvector);
+		rows=mxGetM(mxvector);
+		cols=mxGetN(mxvector);
+
+		/*Create serial vector: */
+		ierr=VecCreateSeq(PETSC_COMM_SELF,rows,&vector);CHKERRQ(ierr);
+
+		/*Insert mxvector_ptr values into petsc vector: */
+		idxm=(int*)xmalloc(rows*sizeof(int));
+
+		for(i=0;i<rows;i++)idxm[i]=i;
+
+		ierr=VecSetValues(vector,rows,idxm,mxvector_ptr,INSERT_VALUES);CHKERRQ(ierr);
+
+	}
+
+	/*Assemble vector: */
+	VecAssemblyBegin(vector);
+	VecAssemblyEnd(vector);
+
+
+	/*Assign output pointer: */
+	*pvector=vector;
+	*pvector_rows=rows;
+
+	return 1;
+}
+#endif
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/NewMat.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 11330)
@@ -0,0 +1,113 @@
+/*!\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 "../../../include/include.h"
+
+/*NewMat(int M,int N){{{1*/
+Mat NewMat(int M,int N){
+
+	/*output:*/
+	Mat outmatrix=NULL;
+
+	/*parameters: */
+	double sparsity=.001; //default
+	int    m,n;
+	int    d_nz,o_nz,nnz;
+
+	/*Determine local sizes: */
+	m=PetscDetermineLocalSize(M);
+	n=PetscDetermineLocalSize(N);
+	
+	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
+
+	MatCreateMPIAIJ(MPI_COMM_WORLD,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
+
+	return outmatrix;
+}
+/*}}}*/
+/*NewMat(int M,int N,double sparsity){{{1*/
+Mat NewMat(int M,int N,double sparsity){
+
+	/*output:*/
+	Mat outmatrix=NULL;
+
+	/*parameters: */
+	int    m,n;
+	int    d_nz,o_nz;
+	int    nnz;
+
+	/*Determine local sizes: */
+	m=PetscDetermineLocalSize(M);
+	n=PetscDetermineLocalSize(N);
+	
+	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
+
+	MatCreateMPIAIJ(MPI_COMM_WORLD,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
+
+	return outmatrix;
+}
+/*}}}*/
+/*NewMat(int M,int N,int connectivity,int numberofdofspernode){{{1*/
+Mat NewMat(int M,int N,int connectivity,int numberofdofspernode){
+
+	/*output:*/
+	Mat outmatrix=NULL;
+
+	/*parameters: */
+	int    m,n;
+	int    d_nz,o_nz;
+	int    nnz;
+
+	#if _PETSC_MAJOR_ >= 3 
+	const MatType type;
+	#else
+	MatType type;
+	#endif
+
+	/*Determine local sizes: */
+	m=PetscDetermineLocalSize(M);
+	n=PetscDetermineLocalSize(N);
+
+	/*Figure out number of non zeros per row: */
+	d_nz=(int)connectivity*numberofdofspernode/2;
+	o_nz=(int)connectivity*numberofdofspernode/2;
+
+	MatCreate(MPI_COMM_WORLD,&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/trunk-jpl-damage/src/c/toolkits/petsc/patches/NewVec.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/NewVec.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/NewVec.cpp	(revision 11330)
@@ -0,0 +1,43 @@
+/*!\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"
+
+Vec NewVec(int size,bool fromlocalsize){
+
+	int ierr;
+	int local_size;
+
+	/*output: */
+	Vec vector=NULL;
+
+	/*determine local size of vector: */
+	if(fromlocalsize){
+		local_size=size;
+	}
+	else{
+		local_size=PetscDetermineLocalSize(size);
+	}
+	
+	VecCreate(PETSC_COMM_WORLD,&vector); 
+	
+	VecSetSizes(vector,local_size,PETSC_DECIDE); 
+	VecSetFromOptions(vector); 
+
+	/*fill with 0: */
+	VecSet(vector,0.0);
+
+	return vector;
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscDetermineLocalSize.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscDetermineLocalSize.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscDetermineLocalSize.cpp	(revision 11330)
@@ -0,0 +1,50 @@
+/* \file PetscDetermineLocalSize.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 PetscDetermineLocalSize(int global_size){
+
+	/*output: */
+	int  local_size;
+
+	/*intermediary: */
+	int  i;
+	int  row_rest;
+	int* num_local_rows=NULL;
+
+	/*from MPI: */
+	extern int num_procs;
+	extern int my_rank;
+	
+	/*We are  not bound by any library, just use what seems most logical*/
+	num_local_rows=(int*)xmalloc(num_procs*sizeof(int));    
+
+	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: */
+	xfree((void**)&num_local_rows);
+
+	/*return size: */
+	return local_size;
+
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscMatrixToMatlabMatrix.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscMatrixToMatlabMatrix.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscMatrixToMatlabMatrix.cpp	(revision 11330)
@@ -0,0 +1,146 @@
+/* \file PetscMatrixToMatlabMatrix.cpp
+ * \brief: convert a sparse or dense Petsc matrix into a matlab matrix
+ */
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+
+#ifdef _SERIAL_
+
+/*Petsc includes: */
+#include "petscmat.h"
+#include "petscvec.h"
+#include "petscksp.h"
+
+/*Petsc includes: */
+#include "mex.h"
+
+#include "../../../shared/shared.h"
+#include <string>
+
+
+int PetscMatrixToMatlabMatrix(mxArray** pdataref,Mat matrix){
+
+	int i,j,k;
+
+	/*output: */
+	mxArray* dataref=NULL;
+	mxArray* tdataref=NULL;
+	int    rows,cols;
+
+	int ncols;
+	int nnz=0;
+	int nzmax=0;
+	const int* columns=NULL;
+	const double* column_values=NULL;
+	double* matrix_ptr=NULL;
+
+	/*compress row format: */
+	double* val=NULL;
+	mwIndex*    col_ind=NULL;
+	mwIndex*    row_ptr=NULL;
+
+	/*petsc type: */
+	const char* type=NULL;
+	int*    idxm=NULL;
+	int*    idxn=NULL;
+
+	MatGetType(matrix,&type);
+	MatGetSize(matrix,&rows,&cols);
+
+	if (strcmp(type,MATSEQAIJ)==0){
+		
+		/*Dealing with a sparse sequential matrix: build ir, jc and val, as though it was a row comvalessed 
+		 *format, instead of a column comvalessed format. We'll transpose later.*/
+
+		/*First get nnz: */
+		nnz=0;
+		for(i=0;i<rows;i++){
+			MatGetRow(matrix,i,&ncols,&columns,&column_values);
+			nnz+=ncols;
+			MatRestoreRow(matrix,i,&ncols,&columns,&column_values);
+		}
+
+		if(nnz){
+			nzmax=nnz;
+		}
+		else{
+			nzmax=1; //so a null matrix can be returned.
+		}
+
+		val=(double*)xcalloc(nzmax,sizeof(double));
+		col_ind=(mwIndex*)xcalloc(nzmax,sizeof(mwIndex));
+		row_ptr=(mwIndex*)xcalloc((rows+1),sizeof(mwIndex));
+
+		j=0;
+
+		for(i=0;i<rows;i++){
+
+			/*Get row from petsc matrix: */
+			MatGetRow(matrix,i,&ncols,&columns,&column_values);
+
+			/*copy values: */
+			if(ncols)memcpy( val+j, column_values,ncols*sizeof(double));
+			  
+			for(k=0;k<ncols;k++) col_ind[j+k]=(mwIndex)columns[k];
+			row_ptr[i]=(mwIndex)j;
+			
+			j+=ncols;
+			
+			/*restore petsc row, otherwise we are leaking memory: */
+			MatRestoreRow(matrix,i,&ncols,&columns,&column_values);
+		}
+		row_ptr[rows]=(mwIndex)nnz;
+
+		/*Ok, allocate arrays: */
+		dataref = mxCreateSparse((mwSize)0,(mwSize)0,(mwSize)0,mxREAL);
+	
+		/* free first to avoid mem leaks...: */
+		mxFree(mxGetData(dataref));
+		mxFree(mxGetIr(dataref));
+		mxFree(mxGetJc(dataref));
+		
+		/* ...then set data: */
+		mxSetM(dataref,(mwSize)cols);
+		mxSetN(dataref,(mwSize)rows);
+		mxSetNzmax(dataref,(mwSize)nzmax);
+		mxSetData( dataref, val);
+		mxSetIr(dataref,col_ind);
+		mxSetJc(dataref,row_ptr);
+
+	}
+	else{
+		/*Dealing with a dense sequential matrix: recover pointer to the data in the Petsc matrix*/
+
+		idxm=(int*)xmalloc(rows*sizeof(int));
+		idxn=(int*)xmalloc(cols*sizeof(int));
+
+		for(i=0;i<rows;i++)idxm[i]=i;
+		for(i=0;i<cols;i++)idxn[i]=i;
+
+		matrix_ptr=(double*)xmalloc(rows*cols*sizeof(double));
+		MatGetValues(matrix,rows,idxm,cols,idxn,matrix_ptr);
+
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+		mxSetM(dataref,rows);
+		mxSetN(dataref,cols);
+		mxSetPr(dataref,(double*)matrix_ptr);	
+	}
+
+
+	/*Transpose matrcol_indes: */
+	mexCallMATLAB(1,&tdataref,1,&dataref, "transpose");
+
+
+	/*Assign output pointers: */
+	*pdataref=tdataref;
+
+	return 1;
+}
+
+#endif  //#ifdef _SERIAL_
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp	(revision 11330)
@@ -0,0 +1,58 @@
+/*!\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"
+#include "../../../include/include.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;
+	}
+	
+	PetscOptionsGetString(PETSC_NULL,"-issm_option_solver",&option[0],100,&flag);
+	if (strcmp(option,"stokes")==0){
+		solver_type=StokesSolverEnum;
+	}
+
+	*psolver_type=solver_type;
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 11330)
@@ -0,0 +1,93 @@
+/*!\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"
+#include "../../../include/include.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;
+	char* final=NULL;
+	size_t len;
+	int ignore_second;
+	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_("%s%s%s","Option ",first," should be preceded by '-'!");
+			}
+			/*Reduce first to bare option value*/
+			PetscStrlen(first,&len);
+			while (len > 0 && (first[len-1] == ' ' || first[len-1] == 'n')) {
+				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] == ' ' || first[len-1] == 'n')) {
+					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] == ' ' || second[len-1] == 'n')) {
+					len--; second[len] = 0;
+				}
+				PetscOptionsSetValue(first,second);
+				first_token=1;
+			}
+		}
+	}
+
+	PetscTokenDestroy(token);
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscVectorToMatlabVector.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscVectorToMatlabVector.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscVectorToMatlabVector.cpp	(revision 11330)
@@ -0,0 +1,65 @@
+/* \file PetscVectorToMatlabVector.cpp
+ * \brief: convert a sparse or dense Petsc vector into a matlab vector
+ */
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+
+#ifdef _SERIAL_
+
+/*Petsc includes: */
+#include "petscmat.h"
+#include "petscvec.h"
+#include "petscksp.h"
+
+/*Petsc includes: */
+#include "mex.h"
+
+#include "../../../shared/shared.h"
+#include <string>
+
+
+int PetscVectorToMatlabVector(mxArray** pdataref,Vec vector){
+
+
+	int i;
+	int rows;
+	int* idxm=NULL;
+	double* values=NULL;
+
+	/*output: */
+	mxArray* dataref=NULL;
+
+	/*Get size of vector: */
+	VecGetSize(vector,&rows);
+
+	if(rows){
+		idxm=(int*)xmalloc(rows*sizeof(int));
+		values=(double*)xmalloc(rows*sizeof(double));
+		for(i=0;i<rows;i++)idxm[i]=i;
+		 
+		VecGetValues(vector,rows,idxm,values);
+	}
+
+	/*Using values, build a matlab vector: */
+	dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(dataref,rows);
+	mxSetN(dataref,1);
+	mxSetPr(dataref,(double*)values);	
+
+	/*Some logic here to make the vector sparse? Although this could slow down the code quite a bit: */
+
+	/*Assign output pointers: */
+	*pdataref=dataref;
+
+	return 1;
+}
+
+
+#endif  //#ifdef _SERIAL_
+
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/SerialToVec.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/SerialToVec.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/SerialToVec.cpp	(revision 11330)
@@ -0,0 +1,65 @@
+/* \file SerialToVec.cpp
+ * \brief: convert a serial vector on all cpus into a parallel vector
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*Petsc includes: */
+#include "petscmat.h"
+#include "petscvec.h"
+#include "petscksp.h"
+
+/*Matlab includes: */
+#ifdef _SERIAL_
+#include "mex.h"
+#endif
+
+#include "../../../shared/shared.h"
+
+Vec  SerialToVec(double* vector,int vector_size){
+
+	int i;
+
+	/*output: */
+	Vec outvector=NULL;
+
+	/*petsc indices: */
+	int* idxn=NULL;
+	double* values=NULL;
+	int lower_row,upper_row,range;
+	
+		
+	/*Create parallel vector: */
+	outvector=NewVec(vector_size);
+
+	/*plug values from local vector into new parallel vector: */
+	VecGetOwnershipRange(outvector,&lower_row,&upper_row);
+	upper_row--;
+	range=upper_row-lower_row+1;    
+
+	if (range){
+		idxn=(int*)xmalloc(range*sizeof(int)); 
+		values=(double*)xmalloc(range*sizeof(double));
+		for (i=0;i<range;i++){
+			idxn[i]=lower_row+i;
+			values[i]=vector[idxn[i]];
+		}
+
+		VecSetValues(outvector,range,idxn,values,INSERT_VALUES);
+	}
+
+
+	/*Assemble vector: */
+	VecAssemblyBegin(outvector);
+	VecAssemblyEnd(outvector);
+
+	/*Free ressources:*/
+	xfree((void**)&idxn);
+	xfree((void**)&values);
+
+	return outvector;
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/SolverEnum.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/SolverEnum.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/SolverEnum.h	(revision 11330)
@@ -0,0 +1,19 @@
+/*!\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/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecDuplicatePatch.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecDuplicatePatch.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecDuplicatePatch.cpp	(revision 11330)
@@ -0,0 +1,22 @@
+/*!\file:  VecDuplicatePatch.cpp
+ * \brief VecDuplicate + VecCopy wrapped together
+ */ 
+
+#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 VecDuplicatePatch(Vec* output, Vec input){
+
+	VecDuplicate(input,output);
+	VecCopy(input,*output);
+
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecFree.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecFree.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecFree.cpp	(revision 11330)
@@ -0,0 +1,27 @@
+/*!\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/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecMerge.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 11330)
@@ -0,0 +1,68 @@
+/*!\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"
+#include "../../../include/include.h"
+
+void VecMerge(Vec A, Vec B, double* row_partition_vector,int row_partition_size){
+
+	int i;
+	
+	/*Petsc matrix*/
+	int lower_row,upper_row,range;
+	int* idxm=NULL;
+	double* values=NULL;
+
+	/*Vector sizes: */
+	int MA,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=(int*)xmalloc(range*sizeof(int));
+		values=(double*)xmalloc(range*sizeof(double));
+		for (i=0;i<range;i++){
+			*(idxm+i)=lower_row+i;
+		}
+		VecGetValues(B,range,idxm,values);
+		/*Now, modify idxm using the partition vector, and plug values into A*/
+		for (i=0;i<range;i++){
+			*(idxm+i)=(int)*(row_partition_vector+lower_row+i)-1; //-1 because partition vector comes from Matlab, where indices start at 1.
+		}
+		VecSetValues(A,range,idxm,values,INSERT_VALUES);
+	}
+	
+	/*Assemble vector*/
+	VecAssemblyBegin(A);
+	VecAssemblyEnd(A);
+
+	/*Free ressources:*/
+	xfree((void**)&idxm);
+	xfree((void**)&values);
+
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecPartition.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecPartition.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecPartition.cpp	(revision 11330)
@@ -0,0 +1,122 @@
+/*!\file:  VecPartition.cpp
+ * \brief  partition vector according to a node set
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*Petsc includes: */
+#include "petscmat.h"
+#include "petscvec.h"
+#include "petscksp.h"
+
+#include "../../../shared/shared.h"
+
+void VecPartition(Vec* poutvector,Vec vectorA, double* row_partition_vector, int row_partition_vector_size,bool kffpartition){
+
+		
+	int i;
+	
+	/*Petsc matrix*/
+	int* node_rows=NULL;
+	double* values=NULL;
+	int count;
+	int lower_row,upper_row,range;
+
+	/*Input*/
+	int MA; //Vector dimension
+
+	/*output*/
+	Vec outvector=NULL;
+
+	
+	/*Get size of input vector: */
+	VecGetSize(vectorA,&MA);
+	
+    /*Condense out*/
+
+    /*If the partitioning row vector has a 0 dimension, we return a NILL vector*/
+    if (row_partition_vector_size==0){
+		VecCreate(PETSC_COMM_WORLD,&outvector);   
+		VecSetSizes(outvector,PETSC_DECIDE,0);
+		VecSetFromOptions(outvector);
+		
+		VecAssemblyBegin(outvector);
+		VecAssemblyEnd(outvector);
+	}
+	else{
+		/*Locally get values and build a new vector which is a subvector*/
+		
+		VecGetOwnershipRange(vectorA,&lower_row,&upper_row);
+		upper_row--;
+		range=upper_row-lower_row+1;
+
+		if (range){
+			node_rows=(int*)xmalloc(range*sizeof(int)); //this is the maximum number of rows one node can extract.
+		
+			count=0;
+			for (i=0;i<row_partition_vector_size;i++){
+				if ( ((int)(*(row_partition_vector+i))>=(lower_row+1)) && ((int)(*(row_partition_vector+i))<=(upper_row+1)) ){
+					*(node_rows+count)=(int)*(row_partition_vector+i)-1;
+					count++;
+				}
+			}
+		}
+		else{
+			count=0;
+		}
+					
+     	if (count){
+			values=(double*)xmalloc(count*sizeof(double)); //holder for the values to be extracted from vectorA
+		}
+		else{
+			xfree((void**)&node_rows); //count=0 means no values was condensed out for this node. null node_rows for use in VecGetValues.
+			values=NULL;
+		}
+
+		if (count){
+			VecGetValues(vectorA,count,node_rows,values);
+		}
+		
+		/*Ok, each node now have count values corresponding to the node_rows extracted values from vectorA.
+		 * From count and values, create a new vector*/
+		VecCreate(PETSC_COMM_WORLD,&outvector);
+		VecSetSizes(outvector,count,PETSC_DECIDE);
+		VecSetFromOptions(outvector);
+		VecGetOwnershipRange(outvector,&lower_row,&upper_row);
+
+		/*build new node_rows index.*/
+		if (count){
+			for (i=0;i<count;i++){
+				*(node_rows+i)=lower_row+i;
+			}
+		}
+		
+		/* outvector should not be partitioned like it was previously, but according to row_partition_vector_size, this in case we 
+		 * are running with the special kffpartition schema: */
+		if(kffpartition){
+			VecFree(&outvector);
+			outvector=NewVec(row_partition_vector_size);
+		}
+
+		if (count){
+			VecSetValues(outvector,count,node_rows,values,INSERT_VALUES);
+		}
+		
+		/*Assemble vector*/
+		VecAssemblyBegin(outvector);
+		VecAssemblyEnd(outvector);
+		
+	}
+	
+	/*Assign output pointers:*/
+	*poutvector=outvector;
+
+	/*Free ressources:*/
+	xfree((void**)&node_rows);
+	xfree((void**)&values);
+
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecToMPISerial.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecToMPISerial.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecToMPISerial.cpp	(revision 11330)
@@ -0,0 +1,86 @@
+/*!\file VecToMPISerial.cpp
+ * \brief gather a Petsc Vector spread across the cluster, onto node 0, and then broadcast to all nodes. 
+ */
+
+#include "../petscincludes.h"
+#include "../../../shared/shared.h"
+
+int VecToMPISerial(double** pgathered_vector, Vec vector){
+	
+	int i;
+	extern int num_procs; 
+	extern int my_rank;
+
+	/*Petsc*/
+	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.
+
+	VecGetSize(vector,&vector_size);
+	if(vector_size==0){
+		*pgathered_vector=NULL;
+		return 1;
+	}
+
+	/*Allocate gathered vector on all nodes .*/
+	gathered_vector=(double*)xmalloc(vector_size*sizeof(double));
+	
+	/*Allocate local vectors*/
+	VecGetOwnershipRange(vector,&lower_row,&upper_row);
+	upper_row--;
+	range=upper_row-lower_row+1;    
+
+	if (range){
+		idxn=(int*)xmalloc(range*sizeof(int)); 
+		for (i=0;i<range;i++){
+			*(idxn+i)=lower_row+i;
+		} 
+		local_vector=(double*)xmalloc(range*sizeof(double));
+		/*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;
+			MPI_Send(buffer,3,MPI_INT,0,1,MPI_COMM_WORLD);  
+			if (range)MPI_Send(local_vector,range,MPI_DOUBLE,0,1,MPI_COMM_WORLD); 
+		}
+		if (my_rank==0){
+			MPI_Recv(buffer,3,MPI_INT,i,1,MPI_COMM_WORLD,&status); 
+			if (buffer[2])MPI_Recv(gathered_vector+buffer[1],buffer[2],MPI_DOUBLE,i,1,MPI_COMM_WORLD,&status);
+		}
+	}
+
+	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: */
+	MPI_Bcast(gathered_vector,vector_size,MPI_DOUBLE,0,MPI_COMM_WORLD);
+
+	/*Assign output pointers: */
+	*pgathered_vector=gathered_vector;
+	
+	/*free ressources: */
+	xfree((void**)&idxn);
+	xfree((void**)&local_vector);
+	
+	return 1;
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecTranspose.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecTranspose.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecTranspose.cpp	(revision 11330)
@@ -0,0 +1,66 @@
+/*! \file VecTranspose.cpp
+ *  \brief: transpose of a petsc vector
+ */
+
+#include "./petscpatches.h"
+#include "../../../shared/shared.h"
+
+int VecTranspose(Vec* ptvector,Vec vector){
+
+	int i;
+	int size;
+	int lower_row,upper_row,range;
+	
+	int* idxm=NULL;
+	double* values=NULL;
+
+	int* tidxm=NULL;
+	double* tvalues=NULL;
+	
+	/*output: */
+	Vec tvector=NULL;
+
+	/*Get size of input vector: */
+	VecGetSize(vector,&size);
+	
+	/*Create new vector of same size: */
+	tvector=NewVec(size);
+
+	/*Extract values locally from input vector: */
+	VecGetOwnershipRange(vector,&lower_row,&upper_row);
+	upper_row--;
+	range=upper_row-lower_row+1;    
+
+	if (range){
+		idxm=(int*)xmalloc(range*sizeof(int)); 
+		tidxm=(int*)xmalloc(range*sizeof(int)); 
+		for (i=0;i<range;i++){
+			*(idxm+i)=lower_row+i;
+		} 
+		values=(double*)xmalloc(range*sizeof(double));
+		tvalues=(double*)xmalloc(range*sizeof(double));
+		
+		VecGetValues(vector,range,idxm,values);
+		
+		/*Transfer values into tidxm, and idxm into tvalues: */
+		for (i=0;i<range;i++){
+			tidxm[i]=(int)values[i];
+			tvalues[i]=(double)idxm[i];
+		}
+		VecSetValues(tvector,range,tidxm,tvalues,INSERT_VALUES);
+	}
+
+	/*Assemble: */
+	VecAssemblyBegin(tvector);
+	VecAssemblyEnd(tvector);
+
+	/*Free ressources: */
+	xfree((void**)&idxm);
+	xfree((void**)&values);
+	xfree((void**)&tidxm);
+	xfree((void**)&tvalues);
+
+	/*Assign output pointers: */
+	*ptvector=tvector;
+	return 1;
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/petscpatches.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/petscpatches.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/patches/petscpatches.h	(revision 11330)
@@ -0,0 +1,52 @@
+/*\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"
+
+class Parameters;
+
+#ifdef _SERIAL_
+#include "mex.h"
+int MatlabMatrixToPetscMatrix(Mat* matrix,int* prows,int* pcols, const mxArray* mxmatrix);
+int MatlabVectorToPetscVector(Vec* pvector,int* pvector_rows,const mxArray* mxvector);
+int PetscMatrixToMatlabMatrix(mxArray** pdataref,Mat matrix);
+int PetscVectorToMatlabVector(mxArray** pdataref,Vec vector);
+int MatlabMatrixToDoubleMatrix(double** pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix);
+int MatlabVectorToDoubleVector(double** pvector,int* pvector_rows,const mxArray* mxvector);
+#endif
+
+int PetscDetermineLocalSize(int global_size);
+Vec NewVec(int size,bool fromlocalsize=false);
+Mat NewMat(int M,int N);
+Mat NewMat(int M,int N,double sparsity);
+Mat NewMat(int M,int N,int connectivity,int numberofdofspernode);
+
+int VecTranspose(Vec* tvector,Vec vector);
+int VecToMPISerial(double** pgathered_vector, Vec vector);
+void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range);
+void MatFree(Mat* pmat);
+void ISFree(IS* pis);
+void VecFree(Vec* pvec);
+void KSPFree(KSP* pksp);
+void VecPartition(Vec* poutvector,Vec vectorA, double* row_partition_vector, int row_partition_vector_size,bool kffpartitioning);
+int MatPartition(Mat* poutmatrix,Mat matrixA,double* row_partition_vector,int row_partition_vector_size ,
+		double* col_partition_vector,int col_partition_vector_size);
+void MatInvert(Mat* pInv, Mat Matrix);
+void PetscOptionsInsertMultipleString(char* options_string);
+void PetscOptionsDetermineSolverType(int* psolver_type);
+void VecMerge(Vec A, Vec B, double* row_partition_vector,int row_partition_size);
+void MatMultPatch(Mat A,Vec X, Vec AX);
+void MatToSerial(double** poutmatrix,Mat matrix);
+void VecDuplicatePatch(Vec* output, Vec input);
+Vec  SerialToVec(double* vector,int vector_size);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/toolkits/petsc/petscincludes.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/petsc/petscincludes.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/petsc/petscincludes.h	(revision 11330)
@@ -0,0 +1,17 @@
+/* \file petscincludes.h
+ * \brief all includes from Petsc + our own patches
+ */
+
+#ifndef _PETSC_INCLUDES_H_
+#define _PETSC_INCLUDES_H_
+
+/*Petsc includes: */
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
+#include <petscsys.h>
+
+/*our own patches: */
+#include "patches/petscpatches.h"
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/toolkits/plapack/patches/CyclicalFactorization.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/plapack/patches/CyclicalFactorization.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/plapack/patches/CyclicalFactorization.cpp	(revision 11330)
@@ -0,0 +1,84 @@
+/*!\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* decomp=NULL;
+	int prime_factor;
+	int i;
+
+	decomp=xmalloc(input*sizeof(int));
+	*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/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 11330)
@@ -0,0 +1,137 @@
+/*!\file PlapackInvertMatrix.cpp
+ * \brief invert petsc matrix using Plapack
+ */
+#include "../../../include/include.h"
+
+/* 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,MPI_Comm* pcomm_2d);
+	
+int PlapackInvertMatrix(Mat* A,Mat* inv_A,int status,int con){ 
+	/*inv_A does not yet exist, inv_A was just xmalloced, that's all*/
+
+	/*Error management*/
+	int i,j;
+	
+
+	/*input*/
+	int mA,nA;
+	int local_mA,local_nA;
+	int lower_row,upper_row,range,this_range,this_lower_row;
+	MatType type;
+	
+	/*Plapack: */
+	MPI_Datatype   datatype;
+	MPI_Comm       comm_2d;
+	PLA_Obj a=NULL;
+	PLA_Template   templ;	
+	double one=1.0;		
+	int ierror;
+	int nb,nb_alg;
+	int nprows,npcols;
+	int initialized=0;
+
+	/*Petsc to Plapack: */
+	double    *arrayA=NULL;
+	int* idxnA=NULL;
+	int d_nz,o_nz;
+	
+	/*Feedback to client*/
+	int computation_status;  
+
+	/*Verify that A is square*/
+	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(MPI_COMM_WORLD,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 = 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--; 
+	range=upper_row-lower_row+1;
+	arrayA=xmalloc(nA*sizeof(double));
+	idxnA=xmalloc(nA*sizeof(int));
+	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);
+	xfree((void**)&arrayA);
+	xfree((void**)&idxnA);
+	
+	/*Finalize PLAPACK*/
+	PLA_Finalize();
+	MPI_Comm_free(&comm_2d);
+
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackToPetsc.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackToPetsc.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackToPetsc.cpp	(revision 11330)
@@ -0,0 +1,98 @@
+/*!\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){
+
+	
+	int i;
+
+	int lower_row,upper_row,range;
+	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(MPI_COMM_WORLD,local_mA,local_nA, mA,nA,d_nz,PETSC_NULL,o_nz,PETSC_NULL,A);
+	}
+	else if(strcasecmp_eq(type,MATMPIDENSE)){
+		MatCreateMPIDense(MPI_COMM_WORLD,local_mA,local_nA, mA,nA,PETSC_NULL,A); 
+	}
+	
+	MatGetOwnershipRange(*A,&lower_row,&upper_row);
+	upper_row--;
+	range=upper_row-lower_row+1;
+	
+	/*Build the Plapack row and column indices corresponding to the local_buffer stored in a. 
+	  We need those indices to directly plug local_buffer into the Petsc matrix A. We do not 
+	  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=xmalloc(mA*sizeof(int));
+	col_nodes=xmalloc(nA*sizeof(int));
+	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=xmalloc(mA*sizeof(int));
+	count=0;
+	for (i=0;i<mA;i++){
+		if(*(row_nodes+i)==myrow){
+			*(idxm+count)=i;
+			count++;
+		}
+	}
+	idxm_count=count;
+
+	idxn=xmalloc(nA*sizeof(int));
+	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:*/
+	xfree((void**)&row_nodes);
+	xfree((void**)&col_nodes);
+	xfree((void**)&idxm);
+	xfree((void**)&idxn);
+}
Index: /issm/trunk-jpl-damage/src/c/toolkits/plapack/patches/plapackpatches.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/plapack/patches/plapackpatches.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/plapack/patches/plapackpatches.h	(revision 11330)
@@ -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);
+int PlapackToPetsc(Mat* A,int local_mA,int local_nA,int mA,int nA,MatType type,PLA_Obj a,PLA_Template templ,int nprows,int npcols,int nb);
+int CyclicalFactorization(int* pnprows,int* pnpcols,int num_procs);
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/toolkits/plapack/plapackincludes.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/plapack/plapackincludes.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/plapack/plapackincludes.h	(revision 11330)
@@ -0,0 +1,18 @@
+/* \file plapackincludes.h
+ * \brief all includes for Plapack + our own patches
+ */
+
+#ifndef _PLA_INCLUDES_H_
+#define _PLA_INCLUDES_H_
+
+#include "PLA.h"
+
+/* missing Plapack prototypes: */
+int PLA_General_invert( int method, PLA_Obj A );
+
+/*our own patches: */
+#include "patches/petscpatches.h"
+
+
+#endif
+
Index: /issm/trunk-jpl-damage/src/c/toolkits/scalapack/FortranMapping.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/scalapack/FortranMapping.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/scalapack/FortranMapping.h	(revision 11330)
@@ -0,0 +1,43 @@
+#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/trunk-jpl-damage/src/c/toolkits/toolkits.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/toolkits.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/toolkits.h	(revision 11330)
@@ -0,0 +1,14 @@
+/* \file toolkits.h
+ * \brief: this API allows use of external packages, provides patches, etc ...
+ */
+
+#ifndef _TOOLKITS_H_
+#define _TOOLKITS_H_
+
+#include "./petsc/petscincludes.h"
+#include "./mpi/mpiincludes.h"
+#include "./metis/metisincludes.h"
+#include "./triangle/triangleincludes.h"
+#include "./matlab/matlabincludes.h"
+
+#endif
Index: /issm/trunk-jpl-damage/src/c/toolkits/triangle/triangleincludes.h
===================================================================
--- /issm/trunk-jpl-damage/src/c/toolkits/triangle/triangleincludes.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/c/toolkits/triangle/triangleincludes.h	(revision 11330)
@@ -0,0 +1,18 @@
+/* \file triangleincludes.h
+ * \brief all includes from triangle
+ */
+
+#ifndef _TRIANGLE_INCLUDES_H_
+#define _TRIANGLE_INCLUDES_H_
+
+#ifdef _SERIAL_
+
+#ifdef _C_ //only valid for iso C, not C++
+/*Triangle includes: */
+#include "triangle.h"
+#endif //#ifdef _C_
+
+#endif //ifdef _SERIAL_
+
+
+#endif
Index: /issm/trunk-jpl-damage/src/dox/issm.dox
===================================================================
--- /issm/trunk-jpl-damage/src/dox/issm.dox	(revision 11330)
+++ /issm/trunk-jpl-damage/src/dox/issm.dox	(revision 11330)
@@ -0,0 +1,83 @@
+
+/** 
+  \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 comments in 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>
+
+  - Fill out an ISSM download request <a href="http://issm.jpl.nasa.gov/installation/download/">here</a>.
+
+  - ISSM Installation instructions are found <a href="http://issm.jpl.nasa.gov/installation/installation/">here</a>.
+
+  - For help using ISSM, see our online <a href="http://issm.jpl.nasa.gov/doc_html/usersmanual.html">User's Manual</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;">533</td><td  bgcolor=#FFFFFF style="text-align:right;">15491</td><td  bgcolor=#FFFFFF style="text-align:right;">17275</td><td  bgcolor=#FFFFFF style="text-align:right;">58005</td><td  bgcolor=#FFFFFF style="text-align:right;">90771</td>
+</tr>
+<tr>
+<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">977</td><td  bgcolor=#C6E2FF style="text-align:right;">7199</td><td  bgcolor=#C6E2FF style="text-align:right;">13702</td><td  bgcolor=#C6E2FF style="text-align:right;">31690</td><td  bgcolor=#C6E2FF style="text-align:right;">52591</td>
+</tr>
+<tr>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">399</td><td  bgcolor=#FFFFFF style="text-align:right;">3069</td><td  bgcolor=#FFFFFF style="text-align:right;">2727</td><td  bgcolor=#FFFFFF style="text-align:right;">10358</td><td  bgcolor=#FFFFFF style="text-align:right;">16154</td>
+</tr>
+<tr>
+<th  bgcolor=#C6E2FF style="text-align:left;"> m4 </th><td  bgcolor=#C6E2FF style="text-align:right;">7</td><td  bgcolor=#C6E2FF style="text-align:right;">1061</td><td  bgcolor=#C6E2FF style="text-align:right;">242</td><td  bgcolor=#C6E2FF style="text-align:right;">8941</td><td  bgcolor=#C6E2FF style="text-align:right;">10244</td>
+</tr>
+<tr>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Objective  C </th><td  bgcolor=#FFFFFF style="text-align:right;">9</td><td  bgcolor=#FFFFFF style="text-align:right;">98</td><td  bgcolor=#FFFFFF style="text-align:right;">0</td><td  bgcolor=#FFFFFF style="text-align:right;">370</td><td  bgcolor=#FFFFFF style="text-align:right;">468</td>
+</tr>
+<tr>
+<th  bgcolor=#C6E2FF style="text-align:left;"> Bourne  Shell </th><td  bgcolor=#C6E2FF style="text-align:right;">8</td><td  bgcolor=#C6E2FF style="text-align:right;">61</td><td  bgcolor=#C6E2FF style="text-align:right;">98</td><td  bgcolor=#C6E2FF style="text-align:right;">271</td><td  bgcolor=#C6E2FF style="text-align:right;">430</td>
+</tr>
+<tr>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Perl </th><td  bgcolor=#FFFFFF style="text-align:right;">3</td><td  bgcolor=#FFFFFF style="text-align:right;">21</td><td  bgcolor=#FFFFFF style="text-align:right;">23</td><td  bgcolor=#FFFFFF style="text-align:right;">240</td><td  bgcolor=#FFFFFF style="text-align:right;">284</td>
+</tr>
+<tr>
+<th  bgcolor=#C6E2FF style="text-align:left;"> IDL </th><td  bgcolor=#C6E2FF style="text-align:right;">1</td><td  bgcolor=#C6E2FF style="text-align:right;">18</td><td  bgcolor=#C6E2FF style="text-align:right;">4</td><td  bgcolor=#C6E2FF style="text-align:right;">124</td><td  bgcolor=#C6E2FF style="text-align:right;">146</td>
+</tr>
+<tr>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C </th><td  bgcolor=#FFFFFF style="text-align:right;">2</td><td  bgcolor=#FFFFFF style="text-align:right;">3</td><td  bgcolor=#FFFFFF style="text-align:right;">3</td><td  bgcolor=#FFFFFF style="text-align:right;">24</td><td  bgcolor=#FFFFFF style="text-align:right;">30</td>
+</tr>
+<tr>
+<th  bgcolor=#C6E2FF style="text-align:left;"> Python </th><td  bgcolor=#C6E2FF style="text-align:right;">2</td><td  bgcolor=#C6E2FF style="text-align:right;">1</td><td  bgcolor=#C6E2FF style="text-align:right;">4</td><td  bgcolor=#C6E2FF style="text-align:right;">13</td><td  bgcolor=#C6E2FF style="text-align:right;">18</td>
+</tr>
+<tr>
+<th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">1941</td><td  bgcolor=#FFFFFF style="text-align:right;">27022</td><td  bgcolor=#FFFFFF style="text-align:right;">34078</td><td  bgcolor=#FFFFFF style="text-align:right;">110036</td><td  bgcolor=#FFFFFF style="text-align:right;">171136</td>
+</tr>
+</table>
+
+	<I> Copyright (C) 2012 </I>
+  */
Index: /issm/trunk-jpl-damage/src/m/classes/@modellist/display.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@modellist/display.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@modellist/display.m	(revision 11330)
@@ -0,0 +1,16 @@
+function display(mds)
+%DISPLAY - display the fields of a model list
+%
+%   echo function for 'modellist' class
+	
+disp(sprintf('\n%s = \n',inputname(1)));
+
+%name
+if isempty(mds.name), disp(sprintf('   Name:      N/A')); else disp(sprintf('   Name:      %s',mds.name)); end
+disp(sprintf('   Number of models: %i',size(mds.models,1)));
+if isempty(mds.cluster), disp(sprintf('   Cluster:      N/A')); else disp(sprintf('   Cluster:   %s',mds.cluster)); end
+if isempty(mds.queue), disp(sprintf('   Queue:      N/A')); else disp(sprintf('   Queue:     %s',mds.queue)); end
+if isempty(mds.time), disp(sprintf('   Time:      N/A')); else disp(sprintf('   Time:      %i',mds.time)); end
+if ~isnan(mds.np),
+	disp(sprintf('   np:        %i',mds.np));
+end
Index: /issm/trunk-jpl-damage/src/m/classes/@modellist/get.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@modellist/get.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@modellist/get.m	(revision 11330)
@@ -0,0 +1,22 @@
+function val = get(a, propName)
+%GET - gets model propertie from a specified object ans returns the value
+% 
+%   Usage:
+%      val = get(a, propName)
+
+switch propName
+case 'numberofelements'
+	val = a.numberofelements;
+case 'numberofnodes'
+	val = a.numberofnodes;
+case 'elements' 
+	val = a.elements;
+case 'x' 
+	val = a.x;
+case 'y' 
+	val = a.y;
+case 'z' 
+	val = a.z;
+otherwise
+	error(['get error message: ' propName,' is not a valid model property'])
+end
Index: /issm/trunk-jpl-damage/src/m/classes/@modellist/loadmultipleresultsfromcluster.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@modellist/loadmultipleresultsfromcluster.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@modellist/loadmultipleresultsfromcluster.m	(revision 11330)
@@ -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.models);
+
+%Get cluster settings
+cluster=md_list.cluster;
+name=md_list.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
+	md_list.models{i}=loadresultsfromdisk(md_list.models{i},[name '-' num2str(i) 'vs' num2str(nummodels) '.outbin']);
+
+	delete([name '-' num2str(i) 'vs' num2str(nummodels) '.outbin']);
+end
+
+%erase files 
+delete('ModelResults.tar.gz');
Index: /issm/trunk-jpl-damage/src/m/classes/@modellist/modellist.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@modellist/modellist.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@modellist/modellist.m	(revision 11330)
@@ -0,0 +1,67 @@
+function mds = modellist(varargin)
+%MODEL - constructor for a list of models
+%
+%   Usage:
+%      mds = modellist(varargin)
+
+switch nargin
+
+case 0
+
+	% if no input arguments, create a default object
+	mds.models=cell(0,1);
+
+	%fields:
+	mds.name='';
+	mds.cluster='';
+	mds.queue='';
+	mds.time=0;
+	mds.np=0;
+	
+	%output
+	mds=class(mds,'modellist');
+
+	%set default parameters
+	mds=setdefaultparameters(mds);
+
+case 1
+
+	%If single argument of class model, we have a copy constructor. 
+	if (isa(varargin{1},'modellist'))
+		mds = varargin{1};
+	elseif (isa(varargin{1},'cell'))
+		celllist=varargin{1};
+		
+		%user gave us a list of models, plug them in mds.models, and do some set up
+		mds=modellist;
+
+		%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),
+			md=celllist{i};
+			if ~isa(md,'model')
+				error(['modellist constructor error message: element ' num2str(i) ' of cell list is not a model!']);
+			end
+		end
+
+		%initialize
+		mds.models=celllist;
+
+		%set some default parameters: 
+		if size(celllist,1),
+			%pick up 1st model for default parameters
+			mds.cluster=mds.models{1}.cluster;
+			mds.name=mds.models{1}.name;
+			mds.queue=mds.models{1}.queue;
+			mds.time=mds.models{1}.time;
+		end
+	else
+		error('model constructor error message: copy constructor called on a non ''model'' class object');
+	end 
+otherwise
+	error('model constructor error message: 0 of 1 argument only in input.');
+end
Index: /issm/trunk-jpl-damage/src/m/classes/@modellist/setdefaultparameters.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@modellist/setdefaultparameters.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@modellist/setdefaultparameters.m	(revision 11330)
@@ -0,0 +1,18 @@
+function mds=setdefaultparameters(mds);
+%SETDEFAULTPARAMETERS - plug default parameters onto model list
+%
+%   Although the model parameterization should be done in
+%   the parameter file, some parameters are initialized here
+%   with a default value.
+%   These default values can be changed if necessary.
+%
+%   Usage:
+%      mds=setdefaultparameters(mds);
+
+
+%cluster settings
+mds.name='none';
+mds.cluster='none';
+mds.queue='none';
+mds.time=0;
+mds.np=NaN;
Index: /issm/trunk-jpl-damage/src/m/classes/@modellist/solve.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@modellist/solve.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@modellist/solve.m	(revision 11330)
@@ -0,0 +1,81 @@
+function mds=solve(mds,varargin)
+%SOLVE - apply solution sequence for  a list of models. Used in batch mode.
+%
+%   Usage:
+%      mds=solve(mds,varargin)
+%      where varargin is a lit of paired arguments. 
+%      arguments can be: 'analysis_type': 'diagnostic','thermal','prognostic','transient'
+%
+%   Examples:
+%      mds=solve(mds,'analysis_type','diagnostic');
+
+%recover options
+options=pairoptions(varargin{:});
+
+%add default options
+options=process_solve_options(options);
+
+%length of list
+nummodels=length(mds.models);
+
+%name of queue: to make it unique, add a time stamp
+name=[mds.name '-' datestr(now,1) '-' datestr(now,'HH-MM-SS') ];
+
+%name of cluster will be first name of list
+cluster=mds.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=mds.models{i};
+	
+	%recover some fields
+	mdex.analysis_type=options.analysis_type;
+
+	mdex.name=[name '-' num2str(i) 'vs' num2str(nummodels)];
+	mdex.time=mds.time;
+	mdex.queue=mds.queue;
+	mdex.cluster=mds.cluster;
+	if ~isnan(mds.np),
+		mdex.np=mds.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
+	mds.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: 
+mds.name=name;
Index: /issm/trunk-jpl-damage/src/m/classes/@modellist/subsasgn.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@modellist/subsasgn.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@modellist/subsasgn.m	(revision 11330)
@@ -0,0 +1,12 @@
+function mds = subsasgn(mds,index,val)
+%SUBSASGN - handle indexed assignments to list of model objects
+%
+%   the first argument is the object, the second argument a structure array
+%   the third one is the value
+%
+%   Usage:
+%      mds = subsasgn(mds,index,val)
+%
+%   See also SUBSREF
+
+mds=builtin('subsasgn',mds,index,val);
Index: /issm/trunk-jpl-damage/src/m/classes/@modellist/subsref.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@modellist/subsref.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@modellist/subsref.m	(revision 11330)
@@ -0,0 +1,10 @@
+function result = subsref(mds,index)
+%SUBSREF - handle indexed references to list of model objects
+%
+%   the first argument is the object and the second one a structure array
+%   Usage:
+%      result = subsref(mds,index)
+% 
+%   See also SUBSASGN
+	
+result=builtin('subsref',mds,index);
Index: /issm/trunk-jpl-damage/src/m/classes/@pairoptions/addfield.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@pairoptions/addfield.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@pairoptions/addfield.m	(revision 11330)
@@ -0,0 +1,10 @@
+function pairoptions=addfield(pairoptions,field,value),
+%ADDFIELD - add a field to an options list
+%
+%   Usage:
+%      pairoptions=addfield(pairoptions,field,value)
+
+if ischar(field),
+	pairoptions.list{end+1,1}=field;
+	pairoptions.list{end,2}=value;
+end
Index: /issm/trunk-jpl-damage/src/m/classes/@pairoptions/addfielddefault.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@pairoptions/addfielddefault.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@pairoptions/addfielddefault.m	(revision 11330)
@@ -0,0 +1,12 @@
+function pairoptions=addfielddefault(pairoptions,field,value),
+%ADDFIELDDEFAULT - add a field to an options list if it does not exist
+%
+%   Usage:
+%      pairoptions=addfielddefault(pairoptions,field,value)
+
+if ischar(field),
+	if ~exist(pairoptions,field),
+		pairoptions.list{end+1,1}=field;
+		pairoptions.list{end,2}=value;
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/@pairoptions/buildlist.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@pairoptions/buildlist.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@pairoptions/buildlist.m	(revision 11330)
@@ -0,0 +1,22 @@
+function pairoptions=buildlist(pairoptions,varargin),
+%BUILDLIST - build list of pairoptions from input
+%
+%   Usage:
+%      pairoptions=buildlist(pairoptions,varargin)
+
+%check length of input
+if mod((nargin-1),2),
+	error('buildlist error message: an even number of pairoptions is required')
+end
+
+%go through varargin and build list of pairoptions
+for i=1:(nargin-1)/2,
+	if ischar(varargin{2*i-1}),
+		pairoptions.list{end+1,1}=varargin{2*i-1};
+		pairoptions.list{end,2}=varargin{2*i};
+	else
+		%option is not a string, ignore it
+		disp(['buildlist info: option number ' num2str(i) ' is not a string, it will be ignored']);
+		continue
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/@pairoptions/changefieldvalue.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@pairoptions/changefieldvalue.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@pairoptions/changefieldvalue.m	(revision 11330)
@@ -0,0 +1,22 @@
+function pairoptions=changefieldvalue(pairoptions,field,newvalue)
+%CHANGEOPTIONVALUE - change the value of an option in an option list
+%
+%   Usage:
+%      pairoptions=changefieldvalue(pairoptions,field,newvalue)
+%
+%   the value associated with all the fields equal to the one given in
+%   input will be modified. If no field is foud, the field will be to
+%   the option list added
+
+%track occurance of field
+lines=find(strcmpi(pairoptions.list(:,1),field));
+
+%replace value
+if isempty(lines),
+	%add new field if not found
+	pairoptions=addfield(pairoptions,field,newvalue);
+else
+	for i=1:length(lines),
+		pairoptions.list{lines(i),2}=newvalue;
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/@pairoptions/deleteduplicates.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@pairoptions/deleteduplicates.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@pairoptions/deleteduplicates.m	(revision 11330)
@@ -0,0 +1,25 @@
+function pairoptions=deleteduplicates(pairoptions,warn)
+%DELETEDUPLICATES - delete duplicates in an option list
+%
+%   Usage:
+%      pairoptions=deleteduplicates(pairoptions,warn)
+%
+%   if warn==1 display an info message to wan user that
+%   some of his options have been removed.
+
+%track the first occurance of each option
+[dummy lines]=unique(pairoptions.list(:,1),'first');
+clear dummy
+
+%warn user if requested
+if warn,
+	numoptions=size(pairoptions.list,1);
+	for i=1:numoptions,
+		if ~ismember(i,lines),
+			disp(['deleteduplicates info: option ' pairoptions.list{i,1} ' appeared more than once. Only its first occurence will be kept'])
+		end
+	end
+end
+
+%remove duplicates from the options list
+pairoptions.list=pairoptions.list(lines,:);
Index: /issm/trunk-jpl-damage/src/m/classes/@pairoptions/display.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@pairoptions/display.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@pairoptions/display.m	(revision 11330)
@@ -0,0 +1,21 @@
+function display(pairoptions)
+%DISPLAY - displays the fields of a pairoptions element
+%
+%   echo function for 'pairoptions' class
+
+disp(sprintf('\n%s = \n',inputname(1)));
+disp(sprintf('   type: %s',pairoptions.type));
+if ~isempty(pairoptions.list),
+	disp(sprintf('   list: (%ix%i)\n',size(pairoptions.list,1),size(pairoptions.list,2)));
+	for i=1:size(pairoptions.list,1),
+		if ischar(pairoptions.list{i,2}),
+			disp(sprintf('     field: %-10s value: ''%s''',pairoptions.list{i,1},pairoptions.list{i,2}));
+		elseif isnumeric(pairoptions.list{i,2}) & length(pairoptions.list{i,2})==1,
+			disp(sprintf('     field: %-10s value: %g',pairoptions.list{i,1},pairoptions.list{i,2}));
+		else
+			disp(sprintf('     field: %-10s value: (%ix%i)',pairoptions.list{i,1},size(pairoptions.list{i,2},1),size(pairoptions.list{i,2},2)));
+		end
+	end
+else
+	disp(sprintf('   list: empty'));
+end
Index: /issm/trunk-jpl-damage/src/m/classes/@pairoptions/exist.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@pairoptions/exist.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@pairoptions/exist.m	(revision 11330)
@@ -0,0 +1,17 @@
+function bool=exist(pairoptions,field),
+%EXIST - check if the option exist
+%
+%   Usage:
+%      bool=exist(pairoptions,field)
+
+%some argument checking: 
+if ((nargin~=2) | (nargout~=1)),
+	help exist
+	error('exist error message: bad usage');
+end
+if ~ischar(field),
+	error('exist error message: field should be a string');
+end
+
+%Recover option
+bool=any(strcmpi(field,pairoptions.list(:,1)));
Index: /issm/trunk-jpl-damage/src/m/classes/@pairoptions/fieldoccurences.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@pairoptions/fieldoccurences.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@pairoptions/fieldoccurences.m	(revision 11330)
@@ -0,0 +1,14 @@
+function num=fieldoccurences(pairoptions,field),
+%FIELDOCCURENCES - get number of occurence of a field
+%
+%   Usage:
+%      num=fieldoccurences(pairoptions,field);
+
+
+%check input 
+if ~ischar(field),
+	error('fieldoccurences error message: field should be a string');
+end
+
+%get number of occurence
+num=sum(strcmpi(field,pairoptions.list(:,1)));
Index: /issm/trunk-jpl-damage/src/m/classes/@pairoptions/getfieldvalue.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@pairoptions/getfieldvalue.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@pairoptions/getfieldvalue.m	(revision 11330)
@@ -0,0 +1,37 @@
+function value=getfieldvalue(pairoptions,field,varargin),
+%GETOPTION - get the value of an option
+%
+%   Usage:
+%      value=getfieldvalue(pairoptions,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) | (nargout~=1)),
+	help getfieldvalue
+	error('getfieldvalue error message: bad usage');
+end
+
+if ~ischar(field),
+	error('getfieldvalue error message: field should be a string');
+end
+
+%Recover option
+for i=1:size(pairoptions.list,1),
+	if strcmpi(pairoptions.list{i,1},field)
+		value=pairoptions.list{i,2};
+		return
+	end
+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
Index: /issm/trunk-jpl-damage/src/m/classes/@pairoptions/pairoptions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@pairoptions/pairoptions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@pairoptions/pairoptions.m	(revision 11330)
@@ -0,0 +1,36 @@
+function options = pairoptions(varargin),
+%PAIROPTIONS - constructor for pairoptions object
+%
+%   Usage:
+%      pairoptions = pairoptions
+
+%check length of input
+if mod(nargin,2)==1,
+	error('pairoption error message: an even number of options is required')
+end
+
+%get calling function name
+a=dbstack;
+if length(a)>1,
+	functionname=a(2).file(1:end-2);
+else
+	functionname='';
+end
+
+%create a pairoption object
+if nargin==0,
+
+	options.list=cell(0,2);
+	options.type=functionname;
+	options=class(options,'pairoptions');
+
+else
+
+	options.list=cell(0,2);
+	options.type=functionname;
+	options=class(options,'pairoptions');
+
+	%initialize list
+	options=buildlist(options,varargin{:});
+
+end
Index: /issm/trunk-jpl-damage/src/m/classes/@pairoptions/removefield.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@pairoptions/removefield.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@pairoptions/removefield.m	(revision 11330)
@@ -0,0 +1,23 @@
+function pairoptions=removefield(pairoptions,field,warn)
+%REMOVEFIELD - delete a field in an option list
+%
+%   Usage:
+%      pairoptions=removefield(pairoptions,field,warn)
+%
+%   if warn==1 display an info message to wan user that
+%   some of his options have been removed.
+
+%check is field exist
+if exist(pairoptions,field),
+
+	%find where the field is located
+	lines=find(~strcmpi(pairoptions.list(:,1),field));
+
+	%remove duplicates from the options list
+	pairoptions.list=pairoptions.list(lines,:);
+
+	%warn user if requested
+	if warn
+		disp(['removefield info: option ' field ' has been removed from the list of options.'])
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/@pairoptions/subsref.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/@pairoptions/subsref.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/@pairoptions/subsref.m	(revision 11330)
@@ -0,0 +1,10 @@
+function pairoptions = subsref(pairoptions,index)
+%SUBSREF - handles indexed references to objects
+%
+%   the first argument is the object and the second one a structure array
+%   Usage:
+%      pairoptions = subsref(pairoptions,index)
+% 
+%   See also SUBSASGN
+
+pairoptions=builtin('subsref',pairoptions,index);
Index: /issm/trunk-jpl-damage/src/m/classes/autodiff.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/autodiff.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/autodiff.m	(revision 11330)
@@ -0,0 +1,48 @@
+%AUTODIFF class definition
+%
+%   Usage:
+%      autodiff=autodiff();
+
+classdef autodiff
+	properties (SetAccess=public) 
+		isautodiff = false;
+		forward    = true;
+		reverse    = false;
+	end
+	methods
+		function obj = autodiff(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   automatic differentiation parameters:'));
+
+			fielddisplay(obj,'isautodiff','indicates if the automatic differentiation is activated');
+			fielddisplay(obj,'forward','forward differentiation');
+			fielddisplay(obj,'reverse','backward differentiation');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','isautodiff','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','forward','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','reverse','format','Boolean');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/balancethickness.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/balancethickness.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/balancethickness.m	(revision 11330)
@@ -0,0 +1,56 @@
+%BALANCETHICKNESS class definition
+%
+%   Usage:
+%      balancethickness=balancethickness();
+
+classdef balancethickness
+	properties (SetAccess=public) 
+		spcthickness      = NaN;
+		thickening_rate   = NaN;
+		stabilization     = 0;
+	end
+	methods
+		function obj = balancethickness(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%Type of stabilization used
+			obj.stabilization=1;
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+			%Early return
+			if solution~=BalancethicknessSolutionEnum, return; end
+
+			checkfield(md,'balancethickness.spcthickness','forcing',1);
+			checkfield(md,'balancethickness.thickening_rate','size',[md.mesh.numberofvertices 1],'NaN',1);
+			checkfield(md,'balancethickness.stabilization','size',[1 1],'values',[0 1 2 3]);
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   balance thickness solution parameters:'));
+
+			fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint)');
+			fielddisplay(obj,'thickening_rate','ice thickening rate used in the mass conservation (dh/dt)');
+			fielddisplay(obj,'stabilization','0: None, 1: SU, 2: MacAyeal''s artificial diffusivity, 3:DG');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','spcthickness','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','thickening_rate','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/bamggeom.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/bamggeom.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/bamggeom.m	(revision 11330)
@@ -0,0 +1,51 @@
+%BAMGGEOM class definition
+%
+%   Usage:
+%      bamggeom(varargin)
+
+classdef bamggeom
+	properties (SetAccess=public) 
+		% {{{1
+		Vertices=[];
+		Edges=[];
+		TangentAtEdges=[];
+		Corners=[];
+		RequiredVertices=[];
+		RequiredEdges=[];
+		CrackedEdges=[];
+		SubDomains=[];
+		% }}}
+	end
+	methods
+		function bg = bamggeom(varargin)% {{{1
+		%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)% {{{1
+			disp(sprintf('\n%s = \n',inputname(1)));
+			disp(struct(bg))
+		end%}}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/bamgmesh.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/bamgmesh.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/bamgmesh.m	(revision 11330)
@@ -0,0 +1,55 @@
+%BAMGMESH class definition
+%
+%   Usage:
+%      bamgmesh(varargin)
+
+classdef bamgmesh
+	properties (SetAccess=public) 
+		% {{{1
+		Vertices=[];
+		Edges=[];
+		Triangles=[];
+		Quadrilaterals=[];
+		IssmEdges=[];
+		IssmSegments=[];
+		VerticesOnGeomVertex=[];
+		VerticesOnGeomEdge=[];
+		EdgesOnGeomEdge=[];
+		SubDomains=[];
+		SubDomainsFromGeom=[];
+		ElementConnectivity=[];
+		NodalConnectivity=[];
+		NodalElementConnectivity=[];
+		CrackedVertices=[];
+		CrackedEdges=[];
+		% }}}
+	end
+	methods
+		function bg = bamgmesh(varargin)% {{{1
+
+		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)% {{{1
+			disp(sprintf('\n%s = \n',inputname(1)));
+			disp(struct(bm))
+		end%}}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/basalforcings.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/basalforcings.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/basalforcings.m	(revision 11330)
@@ -0,0 +1,58 @@
+%BASAL FORCINGS class definition
+%
+%   Usage:
+%      basalforcings=basalforcings();
+
+classdef basalforcings
+	properties (SetAccess=public) 
+		melting_rate             = NaN;
+		melting_rate_correction  = NaN;
+		geothermalflux           = NaN;
+	end
+	methods
+		function obj = basalforcings(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(PrognosticAnalysisEnum,analyses) & ~(solution==TransientSolutionEnum & md.transient.isprognostic==0),
+				checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum,analyses),
+				checkfield(md,'basalforcings.melting_rate','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			end
+			if ismember(ThermalAnalysisEnum,analyses) & ~(solution==TransientSolutionEnum & md.transient.isthermal==0),
+				checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1);
+				checkfield(md,'basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   basal forcings parameters:'));
+
+			fielddisplay(obj,'melting_rate','basal melting rate (positive if melting)');
+			fielddisplay(obj,'melting_rate_correction','additional melting applied when the grounding line retreats');
+			fielddisplay(obj,'geothermalflux','geothermal heat flux [W/m^2]');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','melting_rate','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','melting_rate_correction','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','geothermalflux','format','DoubleMat','mattype',1);
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/clusters/README
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/clusters/README	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/clusters/README	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/classes/clusters/castor.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/clusters/castor.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/clusters/castor.m	(revision 11330)
@@ -0,0 +1,142 @@
+%CASTOR class definition
+%
+%   Usage:
+%      cluster=castor();
+%      cluster=castor('np',3);
+%      cluster=castor('np',3,'login','username');
+
+classdef castor
+    properties (SetAccess=public) 
+		 % {{{1
+		 name='castor'
+		 login='larour';
+		 np   =128; %number of processors
+		 port=0;
+		 queue='shortc';
+		 time=180;
+		 codepath='/workp/edw/larour/issm-2.0/bin'
+		 executionpath='/workp/edw/larour/Testing/Execution'
+		 %}}}
+	 end
+	 methods
+		 function cluster=castor(varargin) % {{{1
+			 options=pairoptions(varargin{:});
+			 for i=1:size(options.list,1),
+				 fieldname=options.list{i,1};
+				 fieldvalue=options.list{i,2};
+				 if ismember(fieldname,properties('castor')),
+					 cluster.(fieldname)=fieldvalue;
+				 else
+					 disp(['''' fieldname ''' is not a property of cluster castor']);
+				 end
+			 end
+		 end
+		 %}}}
+		 function disp(cluster) % {{{1
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    np: %i',cluster.np));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    time: %i',cluster.time));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+		 end
+		 %}}}
+		 function checkconsistency(cluster,md,solution,analyses) % {{{1
+
+			 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,md) % {{{1
+
+			 %retrieve parameters 
+			 modelname=md.miscellaneous.name; 
+			 solution=md.private.solution;
+
+			 %open file for writing: 
+			 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);
+			 fprintf(fid,'cd $PBS_O_WORKDIR\n');
+			 fprintf(fid,'export OMP_NUM_THREADS=1\n');
+			 fprintf(fid,'dplace -s1 -c0-%i mpiexec -np %i %s/issm.exe %s %s %s',cluster.np-1,cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
+
+			 %close file
+			 fclose(fid);
+
+		 end
+		 %}}}
+		 function LaunchQueueJob(cluster,md,options)% {{{1
+			 
+			 %lauch command, to be executed via ssh
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
+			                ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && qsub ' modelname '.queue '];
+
+			if ~strcmpi(options.batch,'yes'),
+				
+				%compress the files into one zip.
+				compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
+				if md.qmu.isdakota,
+					compressstring=[compressstring md.miscellaneous.name '.qmu.in'];
+				end
+				system(compressstring);
+				
+				disp('uploading input file and queueing script');
+				issmscpout(md.cluster.name,md.cluster.executionpath,md.cluster.login,md.cluster.port,{[md.private.runtimename '.tar.gz']});
+				
+				disp('launching solution sequence on remote cluster');
+				issmssh(md.cluster.name,md.cluster.login,md.cluster.port,launchcommand);
+
+			else
+				disp('batch mode requested: not launching job interactively');
+				disp('launch solution sequence on remote cluster by hand');
+			end
+
+		 end
+		 %}}}
+		 function Download(cluster,md)% {{{1
+
+			%some check
+			if isempty(md.private.runtimename),
+				error('pfe Download error message: supply runtime name for results to be loaded!');
+			end
+
+			%Figure out the  directory where all the files are in: 
+			directory=[cluster.executionpath '/' md.private.runtimename '/'];
+
+			%What packages are we picking up from remote cluster
+			packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
+			if md.qmu.isdakota,
+				packages{end+1}=[md.miscellaneous.name '.qmu.err'];
+				packages{end+1}=[md.miscellaneous.name '.qmu.out'];
+				if isfield(md.qmu.params,'tabular_graphics_data'),
+					if md.qmu.params.tabular_graphics_data==true,
+						packages{end+1}='dakota_tabular.dat'; 
+					end
+				end
+			else
+				packages{end+1}=[md.miscellaneous.name '.outbin'];
+			end
+
+			%copy files from cluster to present directory
+			issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
+		end %}}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/clusters/cosmos.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/clusters/cosmos.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/clusters/cosmos.m	(revision 11330)
@@ -0,0 +1,141 @@
+%COSMOS class definition
+%
+%   Usage:
+%      cluster=cosmos();
+%      cluster=cosmos('np',3);
+%      cluster=cosmos('np',3,'login','username');
+
+classdef cosmos
+    properties (SetAccess=public) 
+		 % {{{1
+		 name='cosmos'
+		 login='larour';
+		 np=128;
+		 port=0;
+		 queue='shortq';
+		 time=3*60;
+		 codepath='/work00/edw/larour/issm-2.0/bin';
+		 executionpath='/work00/edw/larour/Execution';
+		 %}}}
+	 end
+	 methods
+		 function cluster=cosmos(varargin) % {{{1
+			 options=pairoptions(varargin{:});
+			 for i=1:size(options.list,1),
+				 fieldname=options.list{i,1};
+				 fieldvalue=options.list{i,2};
+				 if ismember(fieldname,properties('cosmos')),
+					 cluster.(fieldname)=fieldvalue;
+				 else
+					 disp(['''' fieldname ''' is not a property of cluster cosmos']);
+				 end
+			 end
+		 end
+		 %}}}
+		 function disp(cluster) % {{{1
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    np: %i',cluster.np));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    time: %i',cluster.time));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+		 end
+		 %}}}
+		 function checkconsistency(cluster,md,solution,analyses) % {{{1
+
+			 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,md) % {{{1
+
+			 %retrieve parameters 
+			 modelname=md.miscellaneous.name; 
+			 solution=md.private.solution;
+
+			 %open file for writing: 
+			 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);
+			 fprintf(fid,'cd $PBS_O_WORKDIR\n');
+			 fprintf(fid,'export OMP_NUM_THREADS=1\n');
+			 fprintf(fid,'ulimit -s unlimited\n');
+			 fprintf(fid,'ulimit -c 0\n');
+			 fprintf(fid,'/opt/mpich/gm/intel10.1/bin/mpiexec -np %i %s/issm.exe %s %s %s',cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
+
+			 %close file
+			 fclose(fid);
+
+		 end
+		 %}}}
+		 function LaunchQueueJob(cluster,md,options)% {{{1
+			 
+			 %lauch command, to be executed via ssh
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
+			                ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && qsub -S/bin/sh ' modelname '.queue '];
+
+			if ~strcmpi(options.batch,'yes'),
+				
+				%compress the files into one zip.
+				compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
+				if md.qmu.isdakota,
+					compressstring=[compressstring md.miscellaneous.name '.qmu.in'];
+				end
+				system(compressstring);
+				
+				disp('uploading input file and queueing script');
+				issmscpout(md.cluster.name,md.cluster.executionpath,md.cluster.login,md.cluster.port,{[md.private.runtimename '.tar.gz']});
+				
+				disp('launching solution sequence on remote cluster');
+				issmssh(md.cluster.name,md.cluster.login,md.cluster.port,launchcommand);
+
+			else
+				disp('batch mode requested: not launching job interactively');
+				disp('launch solution sequence on remote cluster by hand');
+			end
+
+		 end
+		 %}}}
+		 function Download(cluster,md)% {{{1
+
+			%some check
+			if isempty(md.private.runtimename),
+				error('pfe Download error message: supply runtime name for results to be loaded!');
+			end
+
+			%Figure out the  directory where all the files are in: 
+			directory=[cluster.executionpath '/' md.private.runtimename '/'];
+
+			%What packages are we picking up from remote cluster
+			packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
+			if md.qmu.isdakota,
+				packages{end+1}=[md.miscellaneous.name '.qmu.err'];
+				packages{end+1}=[md.miscellaneous.name '.qmu.out'];
+				if isfield(md.qmu.params,'tabular_graphics_data'),
+					if md.qmu.params.tabular_graphics_data==true,
+						packages{end+1}='dakota_tabular.dat'; 
+					end
+				end
+			else
+				packages{end+1}=[md.miscellaneous.name '.outbin'];
+			end
+
+			%copy files from cluster to present directory
+			issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
+		end %}}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/clusters/gemini.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/clusters/gemini.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/clusters/gemini.m	(revision 11330)
@@ -0,0 +1,142 @@
+%GEMINI class definition
+%
+%   Usage:
+%      cluster=gemini();
+%      cluster=gemini('np',3);
+%      cluster=gemini('np',3,'login','username');
+
+classdef gemini
+    properties (SetAccess=public) 
+	% {{{1
+		name='gemini'
+		login='larour';
+		np=50;
+		port=0;
+		queue='debug';
+		time=60;
+		codepath='/workg/edw/larour/issm-2.0/bin'
+		executionpath='/workg/edw/larour/Testing/Execution'
+	%}}}
+    end
+    methods
+		 function cluster=gemini(varargin) % {{{1
+			 options=pairoptions(varargin{:});
+			 for i=1:size(options.list,1),
+				 fieldname=options.list{i,1};
+				 fieldvalue=options.list{i,2};
+				 if ismember(fieldname,properties('gemini')),
+					 cluster.(fieldname)=fieldvalue;
+				 else
+					 disp(['''' fieldname ''' is not a property of cluster gemini']);
+				 end
+			 end
+		 end
+		 %}}}
+		 function disp(cluster) % {{{1
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    np: %i',cluster.np));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    time: %i',cluster.time));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+		 end
+		 %}}}
+		 function checkconsistency(cluster,md,solution,analyses) % {{{1
+
+			 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,md) % {{{1
+
+			 %retrieve parameters 
+			 modelname=md.miscellaneous.name; 
+			 solution=md.private.solution;
+
+			 %open file for writing: 
+			 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);
+			 fprintf(fid,'cd $PBS_O_WORKDIR\n');
+			 fprintf(fid,'export OMP_NUM_THREADS=1\n');
+			 fprintf(fid,'dplace -s1 -c0-%i mpiexec -np %i %s/issm.exe %s %s %s',cluster.np-1,cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
+
+			 %close file
+			 fclose(fid);
+
+		 end
+		 %}}}
+		 function LaunchQueueJob(cluster,md,options)% {{{1
+			 
+			 %lauch command, to be executed via ssh
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
+			                ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && qsub ' modelname '.queue '];
+
+			if ~strcmpi(options.batch,'yes'),
+				
+				%compress the files into one zip.
+				compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
+				if md.qmu.isdakota,
+					compressstring=[compressstring md.miscellaneous.name '.qmu.in'];
+				end
+				system(compressstring);
+				
+				disp('uploading input file and queueing script');
+				issmscpout(md.cluster.name,md.cluster.executionpath,md.cluster.login,md.cluster.port,{[md.private.runtimename '.tar.gz']});
+				
+				disp('launching solution sequence on remote cluster');
+				issmssh(md.cluster.name,md.cluster.login,md.cluster.port,launchcommand);
+
+			else
+				disp('batch mode requested: not launching job interactively');
+				disp('launch solution sequence on remote cluster by hand');
+			end
+
+		 end
+		 %}}}
+		 function Download(cluster,md)% {{{1
+
+			%some check
+			if isempty(md.private.runtimename),
+				error('pfe Download error message: supply runtime name for results to be loaded!');
+			end
+
+			%Figure out the  directory where all the files are in: 
+			directory=[cluster.executionpath '/' md.private.runtimename '/'];
+
+			%What packages are we picking up from remote cluster
+			packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
+			if md.qmu.isdakota,
+				packages{end+1}=[md.miscellaneous.name '.qmu.err'];
+				packages{end+1}=[md.miscellaneous.name '.qmu.out'];
+				if isfield(md.qmu.params,'tabular_graphics_data'),
+					if md.qmu.params.tabular_graphics_data==true,
+						packages{end+1}='dakota_tabular.dat'; 
+					end
+				end
+			else
+				packages{end+1}=[md.miscellaneous.name '.outbin'];
+			end
+
+			%copy files from cluster to present directory
+			issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
+		end %}}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/clusters/generic.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/clusters/generic.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/clusters/generic.m	(revision 11330)
@@ -0,0 +1,173 @@
+%GENERIC cluster class definition
+%
+%   Usage:
+%      cluster=generic('name','astrid',);
+%      cluster=generic('name','astrid','np',3);
+%      cluster=generic('name',oshostname(),'np',3,'login','username');
+
+classdef generic
+    properties (SetAccess=public) 
+		 % {{{1
+		 name='';
+		 login='';
+		 np=1;
+		 port=0;
+		 interactive=1;
+		 codepath=[issmtier() '/bin'];
+		 executionpath=[issmtier() '/execution'];
+		 valgrind=[issmtier() '/externalpackages/valgrind/install/bin/valgrind'];
+		 valgrindlib=[issmtier() '/externalpackages/valgrind/install/lib/libmpidebug.so'];
+		 valgrindsup=[issmtier() '/externalpackages/valgrind/issm.supp'];
+		 %}}}
+	 end
+	 methods
+		 function cluster=generic(varargin) % {{{1
+
+			 %use provided options to change fields
+			 options=pairoptions(varargin{:});
+
+			 %get name
+			 if ~exist(options,'name'), error('option ''name'' has not been provided'); end
+			 cluster.name=getfieldvalue(options,'name');
+
+			 %initialize cluster using user settings if provided
+			 if (exist([cluster.name '_settings'])==2), eval([cluster.name '_settings']); end
+
+			 %OK get other fields
+			 for i=1:size(options.list,1),
+				 fieldname=options.list{i,1};
+				 fieldvalue=options.list{i,2};
+				 if ismember(fieldname,properties('generic')),
+					 cluster.(fieldname)=fieldvalue;
+				 else
+					 disp(['''' fieldname ''' is not a property of cluster generic']);
+				 end
+			 end
+		 end
+		 %}}}
+		 function disp(cluster) % {{{1
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    np: %i',cluster.np));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+			 disp(sprintf('    valgrind: %s',cluster.valgrind));
+			 disp(sprintf('    valgrindlib: %s',cluster.valgrindlib));
+			 disp(sprintf('    valgrindsup: %s',cluster.valgrindsup));
+		 end
+		 %}}}
+		 function checkconsistency(cluster,md,solution,analyses) % {{{1
+			 if cluster.np<1
+				 checkmessage(['number of processors should be at least 1']);
+			 end
+			 if isnan(cluster.np),
+				 checkessage('number of processors should not be NaN!');
+			 end
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,md) % {{{1
+		 
+			 %retrieve parameters
+			 modelname=md.miscellaneous.name;
+			 solution=md.private.solution;
+			 isvalgrind=md.debug.valgrind;
+			 isgprof=md.debug.gprof;
+
+			 %open file for writing: 
+			 fid=fopen([modelname '.queue'],'w');
+
+			 %write instructions for launching a job on the cluster
+			 fprintf(fid,'#!/bin/sh\n');
+			 if ~isvalgrind,
+				 if cluster.interactive
+					 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s ',...
+						 cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
+				 else
+					 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+						 cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
+				 end
+			 else
+				 %Add --gen-suppressions=all to get suppression lines
+				 fprintf(fid,'LD_PRELOAD=%s \\\n',cluster.valgrindlib);
+				 fprintf(fid,'mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+					 cluster.np,cluster.valgrind,cluster.valgrindsup, cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
+			 end
+
+			 if isgprof,
+				 fprintf(fid,'\n gprof %s/issm.exe gmon.out > %s.performance',cluster.codepath,modelname);
+			 end
+
+			 if ~md.settings.io_gather,
+				 %concatenate the output files:
+				 fprintf(fid,'\ncat %s.outbin.* > %s.outbin',modelname,modelname);
+			 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,md,options)% {{{1
+			 
+			 %lauch command, to be executed via ssh
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
+			                ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && source  ' md.miscellaneous.name '.queue '];
+
+			if ~strcmpi(options.batch,'yes'),
+				
+				%compress the files into one zip.
+				compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
+				if md.qmu.isdakota,
+					compressstring=[compressstring md.miscellaneous.name '.qmu.in'];
+				end
+				if cluster.interactive,
+					compressstring=[compressstring ' ' md.miscellaneous.name '.errlog ' md.miscellaneous.name '.outlog '];
+				end
+				system(compressstring);
+				
+				disp('uploading input file and queueing script');
+				issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[md.private.runtimename '.tar.gz']});
+
+				disp('launching solution sequence on remote cluster');
+				issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+			else
+				disp('batch mode requested: not launching job interactively');
+				disp('launch solution sequence on remote cluster by hand');
+			end
+
+		 end %}}}
+		 function Download(cluster,md)% {{{1
+
+			%some check
+			if isempty(md.private.runtimename),
+				error('supply runtime name for results to be loaded!');
+			end
+
+			%Figure out the  directory where all the files are in: 
+			directory=[cluster.executionpath '/' md.private.runtimename '/'];
+
+			%What packages are we picking up from remote cluster
+			packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
+			if md.qmu.isdakota,
+				packages{end+1}=[md.miscellaneous.name '.qmu.err'];
+				packages{end+1}=[md.miscellaneous.name '.qmu.out'];
+				if isfield(md.qmu.params,'tabular_graphics_data'),
+					if md.qmu.params.tabular_graphics_data==true,
+						packages{end+1}='dakota_tabular.dat'; 
+					end
+				end
+			else
+				packages{end+1}=[md.miscellaneous.name '.outbin'];
+			end
+
+			%copy files from cluster to present directory
+			issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
+		end %}}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/clusters/none.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/clusters/none.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/clusters/none.m	(revision 11330)
@@ -0,0 +1,40 @@
+%NONE class definition
+%
+%   Usage:
+%      cluster=none();
+%      cluster=none('np',3);
+%      cluster=none('np',3,'login','username');
+
+classdef none
+    properties (SetAccess=public)
+		name='none'
+    end
+    methods
+		 function cluster=none(varargin) % {{{1
+			 options=pairoptions(varargin{:});
+			 for i=1:size(options.list,1),
+				 fieldname=options.list{i,1};
+				 fieldvalue=options.list{i,2};
+				 if ismember(fieldname,properties('none')),
+					 cluster.(fieldname)=fieldvalue;
+				 else
+					 disp(['''' fieldname ''' is not a property of cluster none']);
+				 end
+			 end
+		 end
+		 %}}}
+		 function disp(cluster) % {{{1
+			 %  display the object
+			 disp(sprintf('cluster class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+		 end
+		 %}}}
+		 function checkconsistency(cluster,md,solution,analyses) % {{{1
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,md) % {{{1
+			 error('none.BuildQueueScript error message: serial cluster cannot build queue script');
+		 end
+		 %}}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/clusters/pfe.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/clusters/pfe.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/clusters/pfe.m	(revision 11330)
@@ -0,0 +1,258 @@
+%PFE class definition
+%
+%   Usage:
+%      cluster=pfe();
+%      cluster=pfe('np',3);
+%      cluster=pfe('np',3,'login','username');
+
+classdef pfe
+    properties (SetAccess=public)  
+		 % {{{1
+		 name='pfe'
+		 login='';
+		 numnodes=20;
+		 cpuspernode=8; 
+		 port=1025;
+		 queue='long';
+		 time=12*60;
+		 processor='neh';
+		 codepath='';
+		 executionpath='';
+		 interactive=0;
+		 bbftp=0;
+		 numstreams=8;
+		 hyperthreading=0;
+	 end
+	 properties (SetAccess=private) 
+		 np=20*8;
+		 % }}}
+	 end
+	 methods
+		 function cluster=pfe(varargin) % {{{1
+
+			 %initialize cluster using default settings if provided
+			 if (exist('pfe_settings')==2), pfe_settings; end
+
+			 %use provided options to change fields
+			 options=pairoptions(varargin{:});
+			 for i=1:size(options.list,1),
+				 fieldname=options.list{i,1};
+				 fieldvalue=options.list{i,2};
+				 if ismember(fieldname,properties('pfe')),
+					 cluster.(fieldname)=fieldvalue;
+				 else
+					 disp(['''' fieldname ''' is not a property of cluster pfe']);
+				 end
+			 end
+		 end
+		 %}}}
+		 function disp(cluster) % {{{1
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    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 checkconsistency(cluster,md,solution,analyses) % {{{1
+
+			 available_queues={'long','normal','debug'};
+			 queue_requirements_time=[5*24*60 8*60 2*60];
+			 queue_requirements_np=[2048 2048 150];
+
+			 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)),
+						 checkmessage('cpuspernode should be between 1 and 16 for ''neh'' and ''har'' processors in hyperthreading mode');
+					 end
+				 else
+					 if ((cluster.cpuspernode>8 ) | (cluster.cpuspernode<1)),
+						 checkmessage('cpuspernode should be between 1 and 8 for ''neh'' and ''har'' processors');
+					 end
+				 end
+			 elseif strcmpi(cluster.processor,'wes'),
+				 if cluster.hyperthreading,
+					 if ((cluster.cpuspernode>24 ) | (cluster.cpuspernode<1)),
+						 checkmessage('cpuspernode should be between 1 and 24 for ''wes'' processors in hyperthreading mode');
+					 end
+				 else
+					 if ((cluster.cpuspernode>12 ) | (cluster.cpuspernode<1)),
+						 checkmessage('cpuspernode should be between 1 and 12 for ''wes'' processors');
+					 end
+				 end
+			 else
+				 checkmessage('unknown processor type, should be ''neh'',''wes'' or ''har''');
+			 end
+
+			 %Miscelaneous
+			 if isempty(cluster.login), checkmessage('login empty'); end
+			 if isempty(cluster.codepath), checkmessage('codepath empty'); end
+			 if isempty(cluster.executionpath), checkmessage('executionpath empty'); end
+
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,md) % {{{1
+
+			 %retrieve parameters 
+			 modelname=md.miscellaneous.name; 
+			 solution=md.private.solution;
+			 isvalgrind=md.debug.valgrind;
+
+			 %compute number of processors
+			 cluster.np=cluster.numnodes*cluster.cpuspernode;
+
+			 %open file for writing: 
+			 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=s1010\n');
+			 fprintf(fid,'#PBS -m e\n');
+			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
+			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
+
+			 fprintf(fid,'. /usr/share/modules/init/bash\n\n');
+
+			 fprintf(fid,'module load comp-intel/11.1.046\n');
+			 fprintf(fid,'module load mpi/mpt.1.25\n');
+			 fprintf(fid,'module load math/intel_mkl_64_10.0.011\n\n');
+
+			 fprintf(fid,'export PATH="$PATH:."\n\n');
+			 fprintf(fid,'export MPI_GROUP_MAX=64\n\n');
+
+			 fprintf(fid,'cd $PBS_O_WORKDIR\n\n');
+
+			 fprintf(fid,'mpiexec -np %i %s/issm.exe %s $PBS_O_WORKDIR %s\n',cluster.np,cluster.codepath,EnumToString(solution),modelname);
+
+			 if ~md.settings.io_gather,
+				 %concatenate the output files:
+				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			 end
+
+			 %close file
+			 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 $PBS_O_WORKDIR %s\n',cluster.np,cluster.codepath,EnumToString(solution),modelname);
+				 else
+					 fprintf(fid,'mpiexec -np %i valgrind --leak-check=full %s/issm.exe %s $PBS_O_WORKDIR %s\n',cluster.np,cluster.codepath,EnumToString(solution),modelname);
+				 end
+
+				 if ~md.settings.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,md,options)% {{{1
+			 
+			 %lauch command, to be executed via ssh
+			 if ~cluster.interactive, 
+				launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
+			                ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && qsub ' md.miscellaneous.name '.queue '];
+			else
+				launchcommand=['cd ' cluster.executionpath '/Interactive' num2str(cluster.interactive) ' && tar -zxf ' md.private.runtimename '.tar.gz'];
+			end
+
+			if ~strcmpi(options.batch,'yes'),
+				
+				%compress the files into one zip.
+				compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
+				if md.qmu.isdakota,
+					compressstring=[compressstring md.miscellaneous.name '.qmu.in '];
+				end
+				if cluster.interactive,
+					compressstring=[compressstring md.miscellaneous.name '.run ' md.miscellaneous.name '.errlog ' md.miscellaneous.name '.outlog '];
+				end
+				system(compressstring);
+				
+				disp('uploading input file and queueing script');
+				if cluster.interactive,
+					directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive)];
+				else 
+					directory=cluster.executionpath;
+				end
+				
+				if ~cluster.bbftp,
+					issmscpout(cluster.name,directory,cluster.login,cluster.port,{[md.private.runtimename '.tar.gz']});
+				else
+					issmbbftpout(cluster.name,directory,cluster.login,cluster.port,cluster.numstreams,{[md.private.runtimename '.tar.gz']});
+				end
+				
+				disp('launching solution sequence on remote cluster');
+				issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+
+			else
+				disp('batch mode requested: not launching job interactively');
+				disp('launch solution sequence on remote cluster by hand');
+			end
+		 end
+		 %}}}
+		 function Download(cluster,md)% {{{1
+
+			%some check
+			if isempty(md.private.runtimename),
+				if ~cluster.interactive,
+					error('pfe Download error message: supply runtime name for results to be loaded!');
+				end
+			end
+
+			%Figure out the  directory where all the files are in: 
+			if ~cluster.interactive,
+				directory=[cluster.executionpath '/' md.private.runtimename '/'];
+			else
+				directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive) '/'];
+			end
+
+			%What packages are we picking up from remote cluster
+			if ~cluster.interactive,
+				packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
+			else
+				packages={};
+			end
+			if md.qmu.isdakota,
+				packages{end+1}=[md.miscellaneous.name '.qmu.err'];
+				packages{end+1}=[md.miscellaneous.name '.qmu.out'];
+				if isfield(md.qmu.params,'tabular_graphics_data'),
+					if md.qmu.params.tabular_graphics_data==true,
+						packages{end+1}='dakota_tabular.dat'; 
+					end
+				end
+			else
+				packages{end+1}=[md.miscellaneous.name '.outbin'];
+			end
+
+			%copy files from cluster to present directory
+			if ~cluster.bbftp,
+				issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
+			else
+				issmbbftpin(cluster.name, cluster.login, cluster.port, cluster.numstreams, directory, packages);
+			end
+
+		end %}}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/clusters/pollux.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/clusters/pollux.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/clusters/pollux.m	(revision 11330)
@@ -0,0 +1,142 @@
+%POLLUX class definition
+%
+%   Usage:
+%      cluster=pollux();
+%      cluster=pollux('np',3);
+%      cluster=pollux('np',3,'login','username');
+
+classdef pollux
+    properties (SetAccess=public) 
+		 % {{{1
+		 name='pollux'
+		 login='larour';
+		 np=128;
+		 port=0;
+		 queue='shortp';
+		 time=180;
+		 codepath='/workc/edw/larour/issm-2.0/bin'
+		 executionpath='/workc/edw/larour/Testing/Execution'
+		 %}}}
+	 end
+	 methods
+		 function cluster=pollux(varargin) % {{{1
+			 options=pairoptions(varargin{:});
+			 for i=1:size(options.list,1),
+				 fieldname=options.list{i,1};
+				 fieldvalue=options.list{i,2};
+				 if ismember(fieldname,properties('pollux')),
+					 cluster.(fieldname)=fieldvalue;
+				 else
+					 disp(['''' fieldname ''' is not a property of cluster pollux']);
+				 end
+			 end
+		 end
+		 %}}}
+		 function disp(cluster) % {{{1
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    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 checkconsistency(cluster,md,solution,analyses) % {{{1
+
+			 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,md) % {{{1
+
+			 %retrieve parameters 
+			 modelname=md.miscellaneous.name; 
+			 solution=md.private.solution;
+
+			 %open file for writing: 
+			 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);
+			 fprintf(fid,'cd $PBS_O_WORKDIR\n');
+			 fprintf(fid,'export OMP_NUM_THREADS=1\n');
+			 fprintf(fid,'dplace -s1 -c0-%i mpiexec -np %i %s/issm.exe %s %s %s',cluster.np-1,cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
+
+			 %close file
+			 fclose(fid);
+
+		 end
+		 %}}}
+		 function LaunchQueueJob(cluster,md,options)% {{{1
+			 
+			 %lauch command, to be executed via ssh
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
+			                ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && qsub ' modelname '.queue '];
+
+			if ~strcmpi(options.batch,'yes'),
+				
+				%compress the files into one zip.
+				compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
+				if md.qmu.isdakota,
+					compressstring=[compressstring md.miscellaneous.name '.qmu.in'];
+				end
+				system(compressstring);
+				
+				disp('uploading input file and queueing script');
+				issmscpout(md.cluster.name,md.cluster.executionpath,md.cluster.login,md.cluster.port,{[md.private.runtimename '.tar.gz']});
+				
+				disp('launching solution sequence on remote cluster');
+				issmssh(md.cluster.name,md.cluster.login,md.cluster.port,launchcommand);
+
+			else
+				disp('batch mode requested: not launching job interactively');
+				disp('launch solution sequence on remote cluster by hand');
+			end
+
+		 end
+		 %}}}
+		 function Download(cluster,md)% {{{1
+
+			%some check
+			if isempty(md.private.runtimename),
+				error('pfe Download error message: supply runtime name for results to be loaded!');
+			end
+
+			%Figure out the  directory where all the files are in: 
+			directory=[cluster.executionpath '/' md.private.runtimename '/'];
+
+			%What packages are we picking up from remote cluster
+			packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
+			if md.qmu.isdakota,
+				packages{end+1}=[md.miscellaneous.name '.qmu.err'];
+				packages{end+1}=[md.miscellaneous.name '.qmu.out'];
+				if isfield(md.qmu.params,'tabular_graphics_data'),
+					if md.qmu.params.tabular_graphics_data==true,
+						packages{end+1}='dakota_tabular.dat'; 
+					end
+				end
+			else
+				packages{end+1}=[md.miscellaneous.name '.outbin'];
+			end
+
+			%copy files from cluster to present directory
+			issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
+		end %}}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/constants.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/constants.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/constants.m	(revision 11330)
@@ -0,0 +1,61 @@
+%CONSTANTS class definition
+%
+%   Usage:
+%      constants=constants();
+
+classdef constants
+	properties (SetAccess=public) 
+		g                    = 0;
+		yts                  = 0;
+		referencetemperature = 0;
+	end
+	methods
+		function obj = constants(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				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 flag = checkconsistency(obj,md,solution,analyses) % {{{
+
+			checkfield(md,'constants.g','>',0,'size',[1 1]);
+			checkfield(md,'constants.yts','>',0,'size',[1 1]);
+			checkfield(md,'constants.referencetemperature','size',[1 1]);
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   constants parameters:'));
+
+			fielddisplay(obj,'g','gravitational acceleration');
+			fielddisplay(obj,'yts','number of seconds in a year');
+			fielddisplay(obj,'referencetemperature','reference temperature used in the enthalpy model');
+
+		end % }}}
+		function marshall(obj,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/trunk-jpl-damage/src/m/classes/debug.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/debug.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/debug.m	(revision 11330)
@@ -0,0 +1,38 @@
+%DEBUG class definition
+%
+%   Usage:
+%      debug=debug();
+
+classdef debug
+	properties (SetAccess=public) 
+		valgrind=false;
+		gprof   = false;
+	end
+	methods
+		function obj = debug(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				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');
+
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/diagnostic.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/diagnostic.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/diagnostic.m	(revision 11330)
@@ -0,0 +1,179 @@
+%DIAGNOSTIC class definition
+%
+%   Usage:
+%      diagnostic=diagnostic();
+
+classdef diagnostic
+	properties (SetAccess=public) 
+		spcvx                    = NaN;
+		spcvy                    = NaN;
+		spcvz                    = NaN;
+		restol                   = 0;
+		reltol                   = 0;
+		abstol                   = 0;
+		stokesreconditioning     = 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;
+		requested_outputs        = NaN;
+	end
+	methods
+		function obj = diagnostic(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					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.stokesreconditioning=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 diagnostic 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;
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(DiagnosticHorizAnalysisEnum,analyses), return; end
+			%if ~ismember(DiagnosticHorizAnalysisEnum,analyses) |  (solution==TransientSolutionEnum & md.transient.isdiagnostic==0), return; end
+
+			checkfield(md,'diagnostic.spcvx','forcing',1);
+			checkfield(md,'diagnostic.spcvy','forcing',1);
+			if md.mesh.dimension==3, checkfield(md,'diagnostic.spcvz','forcing',1); end
+			checkfield(md,'diagnostic.restol','size',[1 1],'>',0);
+			checkfield(md,'diagnostic.reltol','size',[1 1]);
+			checkfield(md,'diagnostic.abstol','size',[1 1]);
+			checkfield(md,'diagnostic.stokesreconditioning','size',[1 1],'NaN',1);
+			checkfield(md,'diagnostic.viscosity_overshoot','size',[1 1],'NaN',1);
+			if md.mesh.dimension==2,
+				checkfield(md,'diagnostic.icefront','size',[NaN 4],'NaN',1);
+			else
+				checkfield(md,'diagnostic.icefront','size',[NaN 6],'NaN',1);
+			end
+			checkfield(md,'diagnostic.icefront(:,end)','values',[0 1 2]);
+			checkfield(md,'diagnostic.maxiter','size',[1 1],'>=',1);
+			checkfield(md,'diagnostic.referential','size',[md.mesh.numberofvertices 6]);
+			if ~isempty(md.diagnostic.requested_outputs),
+				checkfield(md,'diagnostic.requested_outputs','size',[NaN 1]);
+			end
+
+			%singular solution
+			if ~any((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy))==2),
+				checkmessage(['model ' md.miscellaneous.name ' is not well posed (singular). You need at least one node with fixed velocity!'])
+			end
+			%CHECK THAT EACH LINES CONTAINS ONLY NAN VALUES OR NO NAN VALUES
+			if any(sum(isnan(md.diagnostic.referential),2)~=0 & sum(isnan(md.diagnostic.referential),2)~=6),
+				checkmessage(['model ' md.miscellaneous.name ' has problem with rotated spc. Each line of diagnostic.referential should contain either only NaN values or no NaN values']);
+			end
+			%CHECK THAT THE TWO VECTORS PROVIDED ARE ORTHOGONAL
+			if any(sum(isnan(md.diagnostic.referential),2)==0),
+				pos=find(sum(isnan(md.diagnostic.referential),2)==0);
+				if any(abs(dot(md.diagnostic.referential(pos,1:3)',md.diagnostic.referential(pos,4:6)'))>eps),
+					checkmessage(['model ' md.miscellaneous.name ' has problem with referential. Vectors in diagnostic.referential (colums 1 to 3 and 4 to 6) must be orthogonal']);
+				end
+			end
+			%CHECK THAT NO rotation specified for FS Grounded ice at base
+			if md.mesh.dimension==3 & md.flowequation.isstokes,
+				pos=find(md.mask.vertexongroundedice & md.mesh.vertexonbed);
+				if any(~isnan(md.diagnostic.referential(pos,:))),
+					checkmessage(['model ' md.miscellaneous.name ' not consistent. No referential should be specified for basal vertices of grounded ice']);
+				end
+			end
+		end % }}}
+		function disp(obj) % {{{
+
+			disp(sprintf('   Diagnostic 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,'maxiter','maximum number of nonlinear iterations');
+			fielddisplay(obj,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)');
+
+			disp(sprintf('\n      %s','boundary conditions:'));
+			fielddisplay(obj,'spcvx','x-axis velocity constraint (NaN means no constraint)');
+			fielddisplay(obj,'spcvy','y-axis velocity constraint (NaN means no constraint)');
+			fielddisplay(obj,'spcvz','z-axis velocity constraint (NaN means no constraint)');
+			fielddisplay(obj,'icefront','segments on ice front list (last column 0-> Air, 1-> Water, 2->Ice');
+
+			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 Stokes model');
+			fielddisplay(obj,'stokesreconditioning','multiplier for incompressibility equation. Only for Stokes model');
+			fielddisplay(obj,'referential','local referential');
+			fielddisplay(obj,'requested_outputs','additional outputs requested');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','spcvx','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','spcvy','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','spcvz','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','restol','format','Double');
+			WriteData(fid,'object',obj,'fieldname','reltol','format','Double');
+			WriteData(fid,'object',obj,'fieldname','abstol','format','Double');
+			WriteData(fid,'object',obj,'fieldname','stokesreconditioning','format','Double');
+			WriteData(fid,'object',obj,'fieldname','viscosity_overshoot','format','Double');
+			WriteData(fid,'object',obj,'fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','shelf_dampening','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','vertex_pairing','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
+			WriteData(fid,'object',obj,'fieldname','rift_penalty_lock','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','rift_penalty_threshold','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','referential','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
+
+			%marshall ice front
+			data=obj.icefront;
+			pos=find(data(:,end)==0); data(pos,end)=AirEnum;
+			pos=find(data(:,end)==1); data(pos,end)=WaterEnum;
+			pos=find(data(:,end)==2); data(pos,end)=IceEnum;
+			WriteData(fid,'data',data,'enum',DiagnosticIcefrontEnum,'format','DoubleMat','mattype',3);
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/flaim.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/flaim.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/flaim.m	(revision 11330)
@@ -0,0 +1,83 @@
+%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 obj = flaim(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if solution~=FlaimSolutionEnum, return; end
+
+			checkfield(md,'flaim.tracks','file',1);
+			if any(isnan(md.flaim.criterion)) || isempty(md.flaim.criterion)
+				checkfield(md,'flaim.targets','file',1);
+			else
+				checkfield(md,'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/trunk-jpl-damage/src/m/classes/flowequation.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/flowequation.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/flowequation.m	(revision 11330)
@@ -0,0 +1,107 @@
+%FLOWEQUATION class definition
+%
+%   Usage:
+%      flowequation=flowequation();
+
+classdef flowequation
+	properties (SetAccess=public) 
+		ismacayealpattyn     = 0;
+		ishutter             = 0;
+		isstokes             = 0;
+		vertex_equation      = NaN;
+		element_equation     = NaN;
+		bordermacayeal       = NaN;
+		borderpattyn         = NaN;
+		borderstokes         = NaN;
+	end
+	methods
+		function obj = flowequation(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(DiagnosticHorizAnalysisEnum,analyses),
+
+				checkfield(md,'flowequation.ismacayealpattyn','numel',1,'values',[0 1]);
+				checkfield(md,'flowequation.ishutter','numel',1,'values',[0 1]);
+				checkfield(md,'flowequation.isstokes','numel',1,'values',[0 1]);
+				checkfield(md,'flowequation.bordermacayeal','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				checkfield(md,'flowequation.borderpattyn','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				checkfield(md,'flowequation.borderstokes','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				if (md.mesh.dimension==2),
+					checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[1:2]);
+					checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[1:2]);
+				else
+					checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[0:7]);
+					checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[0:7]);
+				end
+				if (md.flowequation.ismacayealpattyn==0 && md.flowequation.ishutter==0 && md.flowequation.isstokes==0),
+					checkmessage(['no element types set for this model. At least one of ismacayealpattyn, ishutter or isstokes need to be =1']);
+				end
+			end
+			if ismember(DiagnosticHutterAnalysisEnum,analyses),
+				if any(md.flowequation.element_equation==1 & md.mask.elementonfloatingice),
+					disp(sprintf('\n !!! Warning: Hutter''s model is not consistent on ice shelves !!!\n'));
+				end
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   flow equation parameters:'));
+
+			fielddisplay(obj,'ismacayealpattyn','is the macayeal or pattyn approximation used ?');
+			fielddisplay(obj,'ishutter','is the shallow ice approximation used ?');
+			fielddisplay(obj,'isstokes','are the Full-Stokes equations used ?');
+			fielddisplay(obj,'vertex_equation','flow equation for each vertex');
+			fielddisplay(obj,'element_equation','flow equation for each element');
+			fielddisplay(obj,'bordermacayeal','vertices on MacAyeal''s border (for tiling)');
+			fielddisplay(obj,'borderpattyn','vertices on Pattyn''s border (for tiling)');
+			fielddisplay(obj,'borderstokes','vertices on Stokes'' border (for tiling)');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','ismacayealpattyn','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','ishutter','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isstokes','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','bordermacayeal','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','borderpattyn','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','borderstokes','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)=HutterApproximationEnum;
+			pos=find(data==2); data(pos,end)=MacAyealApproximationEnum;
+			pos=find(data==3); data(pos,end)=PattynApproximationEnum;
+			pos=find(data==4); data(pos,end)=StokesApproximationEnum;
+			pos=find(data==5); data(pos,end)=MacAyealPattynApproximationEnum;
+			pos=find(data==6); data(pos,end)=MacAyealStokesApproximationEnum;
+			pos=find(data==7); data(pos,end)=PattynStokesApproximationEnum;
+			WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum,'format','DoubleMat','mattype',1);
+			data=obj.element_equation;
+			pos=find(data==0); data(pos,end)=NoneApproximationEnum;
+			pos=find(data==1); data(pos,end)=HutterApproximationEnum;
+			pos=find(data==2); data(pos,end)=MacAyealApproximationEnum;
+			pos=find(data==3); data(pos,end)=PattynApproximationEnum;
+			pos=find(data==4); data(pos,end)=StokesApproximationEnum;
+			pos=find(data==5); data(pos,end)=MacAyealPattynApproximationEnum;
+			pos=find(data==6); data(pos,end)=MacAyealStokesApproximationEnum;
+			pos=find(data==7); data(pos,end)=PattynStokesApproximationEnum;
+			WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum,'format','DoubleMat','mattype',2);
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/friction.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/friction.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/friction.m	(revision 11330)
@@ -0,0 +1,52 @@
+%FRICTION class definition
+%
+%   Usage:
+%      friction=friction();
+
+classdef friction
+	properties (SetAccess=public) 
+		coefficient = NaN;
+		p           = NaN;
+		q           = NaN;
+	end
+	methods
+		function obj = friction(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(DiagnosticHorizAnalysisEnum,analyses) & ~ismember(ThermalAnalysisEnum,analyses), return; end
+
+			checkfield(md,'friction.coefficient','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			checkfield(md,'friction.q','NaN',1,'size',[md.mesh.numberofelements 1]);
+			checkfield(md,'friction.p','NaN',1,'size',[md.mesh.numberofelements 1]);
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_ice*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,fid) % {{{
+			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/trunk-jpl-damage/src/m/classes/geometry.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/geometry.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/geometry.m	(revision 11330)
@@ -0,0 +1,60 @@
+%GEOMETRY class definition
+%
+%   Usage:
+%      geometry=geometry();
+
+classdef geometry
+	properties (SetAccess=public) 
+		surface           = NaN;
+		thickness         = NaN;
+		bed               = NaN;
+		bathymetry        = NaN;
+		hydrostatic_ratio = NaN;
+	end
+	methods
+		function obj = geometry(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			checkfield(md,'geometry.surface'  ,'NaN',1,'size',[md.mesh.numberofvertices 1]);
+			checkfield(md,'geometry.bed'      ,'NaN',1,'size',[md.mesh.numberofvertices 1]);
+			checkfield(md,'geometry.thickness','NaN',1,'size',[md.mesh.numberofvertices 1],'>',0);
+			if any((obj.thickness-obj.surface+obj.bed)>10^-9),
+				checkmessage(['equality thickness=surface-bed violated']);
+			end 
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   geometry parameters:'));
+
+			fielddisplay(obj,'surface','surface elevation');
+			fielddisplay(obj,'thickness','ice thickness');
+			fielddisplay(obj,'bed','bed elevation');
+			fielddisplay(obj,'bathymetry','bathymetry elevation');
+			fielddisplay(obj,'hydrostatic_ratio','coefficient for ice shelves'' thickness correction: hydrostatic_ratio H_obs+ (1-hydrostatic_ratio) H_hydro');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'data',obj.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum);
+			WriteData(fid,'data',obj.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum);
+			WriteData(fid,'data',obj.bed,'format','DoubleMat','mattype',1,'enum',BedEnum);
+			WriteData(fid,'data',obj.bathymetry,'format','DoubleMat','mattype',1,'enum',BathymetryEnum);
+			WriteData(fid,'object',obj,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1);
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/groundingline.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/groundingline.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/groundingline.m	(revision 11330)
@@ -0,0 +1,68 @@
+%CONSTANTS class definition
+%
+%   Usage:
+%      groundingline=groundingline();
+
+classdef groundingline
+	properties (SetAccess=public) 
+		migration    = '';
+		melting_rate = NaN;
+	end
+	methods
+		function obj = groundingline(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%Type of migration
+			obj.migration='None';
+
+			%basal melting rate correction: 
+			obj.melting_rate=0; 
+
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			checkfield(md,'groundingline.migration','values',{'None' 'AgressiveMigration' 'SoftMigration'});
+
+			if ~strcmp(obj.migration,'None'),
+				if isnan(md.geometry.bathymetry),
+					checkmessage(['requesting grounding line migration, but bathymetry is absent!']);
+				end
+				pos=find(md.mask.vertexongroundedice); 
+				if any(md.geometry.bed(pos)-md.geometry.bathymetry(pos)),
+					checkmessage(['bathymetry not equal to bed on grounded ice !']);
+				end
+				pos=find(md.mask.vertexonfloatingice); 
+				if any(md.geometry.bathymetry(pos)-md.geometry.bed(pos)>10^-9),
+					checkmessage(['bathymetry superior to bed on floating ice !']);
+				end
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   balance thickness solution parameters:'));
+
+			fielddisplay(obj,'migration','type of grounding line migration: ''SoftMigration'',''AgressiveMigration'' or ''None''');
+			fielddisplay(obj,'melting_rate','melting rate applied when previously grounded parts start floating');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'data',StringToEnum(obj.migration),'enum',GroundinglineMigrationEnum,'format','Integer');
+			WriteData(fid,'object',obj,'fieldname','melting_rate','format','Double');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/hydrology.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/hydrology.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/hydrology.m	(revision 11330)
@@ -0,0 +1,74 @@
+%HYDROLOGY class definition
+%
+%   Usage:
+%      hydrology=hydrology();
+
+classdef hydrology
+	properties (SetAccess=public) 
+		spcwatercolumn = NaN;
+		n              = 0;
+		CR             = 0;
+		p              = 0;
+		q              = 0;
+		kn             = 0;
+		stabilization  = 0;
+	end
+	methods
+		function obj = hydrology(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%Parameters from Johnson's 2002 thesis, section 3.5.4			 
+			obj.n=.02;			 
+			obj.CR=.01;
+			obj.p=2;		 
+			obj.q=1;		 
+			obj.kn=0;
+
+			%Type of stabilization to use 0:nothing 1:artificial_diffusivity
+			obj.stabilization=1;
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(HydrologyAnalysisEnum,analyses), return; end
+
+			checkfield(md,'hydrology.spcwatercolumn','forcing',1);
+			checkfield(md,'hydrology.stabilization','>=',0);
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   hydrology solution parameters:'));
+
+			fielddisplay(obj,'spcwatercolumn','water thickness constraints (NaN means no constraint)');
+			fielddisplay(obj,'n','Manning roughness coefficient');
+			fielddisplay(obj,'CR','tortuosity parameter');
+			fielddisplay(obj,'p','dimensionless exponent in Manning velocity formula');
+			fielddisplay(obj,'q','dimensionless exponent in Manning velocity formula');
+			fielddisplay(obj,'kn','parameter in effective pressure formula');
+			fielddisplay(obj,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','n','format','Double'); 
+			WriteData(fid,'object',obj,'fieldname','CR','format','Double');
+			WriteData(fid,'object',obj,'fieldname','p','format','Double');
+			WriteData(fid,'object',obj,'fieldname','q','format','Double');
+			WriteData(fid,'object',obj,'fieldname','kn','format','Double');
+			WriteData(fid,'object',obj,'fieldname','stabilization','format','Double');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/initialization.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/initialization.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/initialization.m	(revision 11330)
@@ -0,0 +1,91 @@
+%INITIALIZATION class definition
+%
+%   Usage:
+%      initialization=initialization();
+
+classdef initialization
+	properties (SetAccess=public) 
+		vx            = NaN;
+		vy            = NaN;
+		vz            = NaN;
+		vel           = NaN;
+		pressure      = NaN;
+		temperature   = NaN;
+		watercolumn   = NaN;
+		waterfraction = NaN;
+	end
+	methods
+		function obj = initialization(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+			if ismember(DiagnosticHorizAnalysisEnum,analyses)
+				if ~isnan(md.initialization.vx) & ~isnan(md.initialization.vy),
+					checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
+					checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				end
+			end
+			if ismember(PrognosticAnalysisEnum,analyses),
+				checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			end
+			if ismember(HydrologyAnalysisEnum,analyses),
+				checkfield(md,'initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			end
+			if ismember(BalancethicknessAnalysisEnum,analyses),
+				checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				%Triangle with zero velocity
+				if any(sum(abs(md.initialization.vx(md.mesh.elements)),2)==0 & sum(abs(md.initialization.vy(md.mesh.elements)),2)==0)
+					checkmessage('model not consistent: at least one triangle has all its vertices with a zero velocity');
+				end
+			end
+			if ismember(ThermalAnalysisEnum,analyses),
+				checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				checkfield(md,'initialization.vz','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				checkfield(md,'initialization.pressure','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			end
+			if ismember(EnthalpyAnalysisEnum,analyses),
+				checkfield(md,'initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices 1]);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   initial field values:'));
+
+			fielddisplay(obj,'vx','x component of velocity');
+			fielddisplay(obj,'vy','y component of velocity');
+			fielddisplay(obj,'vz','z component of velocity');
+			fielddisplay(obj,'vel','velocity norm');
+			fielddisplay(obj,'pressure','pressure field');
+			fielddisplay(obj,'temperature','temperature in Kelvins');
+			fielddisplay(obj,'watercolumn','thickness of subglacial water');
+			fielddisplay(obj,'waterfraction','fraction of water in the ice');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'data',obj.vx,'format','DoubleMat','mattype',1,'enum',VxEnum);
+			WriteData(fid,'data',obj.vy,'format','DoubleMat','mattype',1,'enum',VyEnum);
+			WriteData(fid,'data',obj.vz,'format','DoubleMat','mattype',1,'enum',VzEnum);
+			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.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum);
+			WriteData(fid,'data',obj.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum);
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/inversion.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/inversion.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/inversion.m	(revision 11330)
@@ -0,0 +1,179 @@
+%CONSTANTS class definition
+%
+%   Usage:
+%      inversion=inversion();
+
+classdef inversion
+	properties (SetAccess=public) 
+		iscontrol                   = 0
+		tao                         = 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
+		gradient_only               = 0
+		vx_obs                      = NaN
+		vy_obs                      = NaN
+		vz_obs                      = NaN
+		vel_obs                     = NaN
+		thickness_obs               = NaN
+	end
+	methods
+		function obj = inversion(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			 %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*ones(obj.nsteps,1);
+
+			 %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.
+
+			 %stop control solution at the gradient computation and return it? 
+			 obj.gradient_only=0;
+
+			 %cost_function_threshold is a criteria to stop the control methods.
+			 %if J[n]-J[n-1]/J[n] < criteria, the control run stops
+			 %NaN if not applied
+			 obj.cost_function_threshold=NaN; %not activated
+
+		end % }}}
+		function 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);
+
+			checkfield(md,'inversion.iscontrol','values',[0 1]);
+			checkfield(md,'inversion.control_parameters','cell',1,'values',{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'Vx' 'Vy'});
+			checkfield(md,'inversion.nsteps','numel',1,'>=',1);
+			checkfield(md,'inversion.maxiter_per_step','size',[md.inversion.nsteps 1],'>=',0);
+			checkfield(md,'inversion.step_threshold','size',[md.inversion.nsteps 1]);
+			checkfield(md,'inversion.cost_functions','size',[md.inversion.nsteps num_costfunc],'values',[101:105 201 501:503]);
+			checkfield(md,'inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
+			checkfield(md,'inversion.gradient_only','values',[0 1]);
+			checkfield(md,'inversion.gradient_scaling','size',[md.inversion.nsteps num_controls]);
+			checkfield(md,'inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
+			checkfield(md,'inversion.max_parameters','size',[md.mesh.numberofvertices num_controls]);
+
+			if solution==BalancethicknessSolutionEnum
+				checkfield(md,'inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			else
+				checkfield(md,'inversion.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				checkfield(md,'inversion.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			fielddisplay(obj,'iscontrol','is inversion activated?');
+			fielddisplay(obj,'control_parameters','parameter where inverse control is carried out; ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
+			fielddisplay(obj,'nsteps','number of optimization searches');
+			fielddisplay(obj,'cost_functions','indicate the type of response for each optimization steps');
+			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,'gradient_only','stop control method solution at gradient');
+			fielddisplay(obj,'vx_obs','observed velocity x component [m/a]');
+			fielddisplay(obj,'vy_obs','observed velocity y component [m/a]');
+			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/a]');
+			fielddisplay(obj,'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,fid) % {{{
+
+			WriteData(fid,'object',obj,'fieldname','iscontrol','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','tao','format','Boolean');
+			if ~obj.iscontrol, return; end
+			WriteData(fid,'object',obj,'fieldname','nsteps','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','maxiter_per_step','format','DoubleMat','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','gradient_only','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','vx_obs','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','vy_obs','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','vz_obs','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','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(data==101); data(pos)=SurfaceAbsVelMisfitEnum;
+			pos=find(data==102); data(pos)=SurfaceRelVelMisfitEnum;
+			pos=find(data==103); data(pos)=SurfaceLogVelMisfitEnum;
+			pos=find(data==104); data(pos)=SurfaceLogVxVyMisfitEnum;
+			pos=find(data==105); data(pos)=SurfaceAverageVelMisfitEnum;
+			pos=find(data==201); data(pos)=ThicknessAbsMisfitEnum;
+			pos=find(data==501); data(pos)=DragCoefficientAbsGradientEnum;
+			pos=find(data==502); data(pos)=RheologyBbarAbsGradientEnum;
+			pos=find(data==503); data(pos)=ThicknessAbsGradientEnum;
+			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum,'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum,'format','Integer');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/mask.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/mask.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/mask.m	(revision 11330)
@@ -0,0 +1,60 @@
+%MASK class definition
+%
+%   Usage:
+%      mask=mask();
+
+classdef mask
+	properties (SetAccess=public) 
+		elementonfloatingice = NaN;
+		elementongroundedice = NaN;
+		elementonwater       = NaN;
+		vertexonfloatingice  = NaN;
+		vertexongroundedice  = NaN;
+		vertexonwater        = NaN;
+	end
+	methods
+		function obj = mask(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			checkfield(md,'mask.elementonfloatingice','size',[md.mesh.numberofelements 1],'values',[0 1]);
+			checkfield(md,'mask.elementongroundedice','size',[md.mesh.numberofelements 1],'values',[0 1]);
+			checkfield(md,'mask.elementonwater'      ,'size',[md.mesh.numberofelements 1],'values',[0 1]);
+			checkfield(md,'mask.vertexonfloatingice','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			checkfield(md,'mask.vertexongroundedice','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			checkfield(md,'mask.vertexonwater'      ,'size',[md.mesh.numberofvertices 1],'values',[0 1]);
+		end % }}}
+		function disp(obj) % {{{
+			fielddisplay(obj,'elementonfloatingice','element on floating ice flags list');
+			fielddisplay(obj,'vertexonfloatingice','vertex on floating ice flags list');
+			fielddisplay(obj,'elementongroundedice','element on grounded ice  list');
+			fielddisplay(obj,'vertexongroundedice','vertex on grounded ice flags list');
+			fielddisplay(obj,'elementonwater','element on water flags list');
+			fielddisplay(obj,'vertexonwater','vertex on water flags list');
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','elementonfloatingice','format','BooleanMat','mattype',2);
+			WriteData(fid,'object',obj,'fieldname','elementongroundedice','format','BooleanMat','mattype',2);
+			WriteData(fid,'object',obj,'fieldname','elementonwater','format','BooleanMat','mattype',2);
+			WriteData(fid,'object',obj,'fieldname','vertexonfloatingice','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','vertexongroundedice','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','vertexonwater','format','DoubleMat','mattype',1);
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/materials.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/materials.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/materials.m	(revision 11330)
@@ -0,0 +1,115 @@
+%MATERIALS class definition
+%
+%   Usage:
+%      materials=materials();
+
+classdef materials
+	properties (SetAccess=public) 
+		rho_ice                    = 0;
+		rho_water                  = 0;
+		mu_water                   = 0;
+		heatcapacity               = 0;
+		latentheat                 = 0;
+		thermalconductivity        = 0;
+		meltingpoint               = 0;
+		beta                       = 0;
+		mixed_layer_capacity       = 0;
+		thermal_exchange_velocity  = 0;
+		rheology_B   = NaN;
+		rheology_n   = NaN;
+		rheology_law = '';
+	end
+	methods
+		function obj = materials(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%ice density (kg/m^3)
+			obj.rho_ice=917;
+
+			%water density (kg/m^3)
+			obj.rho_water=1023;
+
+			%water viscosity (N.s/m^2)
+			obj.mu_water=0.001787;  
+
+			%ice heat capacity cp (J/kg/K)
+			obj.heatcapacity=2093;
+
+			%ice latent heat of fusion L (J/kg)
+			obj.latentheat=3.34*10^5;
+
+			%ice thermal conductivity (W/m/K)
+			obj.thermalconductivity=2.4;
+
+			%the melting point of ice at 1 atmosphere of pressure in K
+			obj.meltingpoint=273.15;
+
+			%rate of change of melting point with pressure (K/Pa)
+			obj.beta=9.8*10^-8;
+
+			%mixed layer (ice-water interface) heat capacity (J/kg/K)
+			obj.mixed_layer_capacity=3974;
+
+			%thermal exchange velocity (ice-water interface) (m/s)
+			obj.thermal_exchange_velocity=1.00*10^-4;
+
+			%Rheology law: what is the temperature dependence of B with T
+			%available: none, paterson and arrhenius
+			obj.rheology_law='Paterson';
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+			checkfield(md,'materials.rho_ice','>',0);
+			checkfield(md,'materials.rho_water','>',0);
+			checkfield(md,'materials.mu_water','>',0);
+			checkfield(md,'materials.rheology_B','>',0,'size',[md.mesh.numberofvertices 1]);
+			checkfield(md,'materials.rheology_n','>',0,'size',[md.mesh.numberofelements 1]);
+			checkfield(md,'materials.rheology_law','values',{'None' 'Paterson' 'Arrhenius'});
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Materials:\n'));
+
+			fielddisplay(obj,'rho_ice','ice density [kg/m^3]');
+			fielddisplay(obj,'rho_water','water density [kg/m^3]');
+			fielddisplay(obj,'mu_water','water viscosity [N s/m^2]');
+			fielddisplay(obj,'heatcapacity','heat capacity [J/kg/K]');
+			fielddisplay(obj,'thermalconductivity','ice thermal conductivity [W/m/K]');
+			fielddisplay(obj,'meltingpoint','melting point of ice at 1atm in K');
+			fielddisplay(obj,'latentheat','latent heat of fusion [J/m^3]');
+			fielddisplay(obj,'beta','rate of change of melting point with pressure [K/Pa]');
+			fielddisplay(obj,'mixed_layer_capacity','mixed layer capacity [W/kg/K]');
+			fielddisplay(obj,'thermal_exchange_velocity','thermal exchange velocity [m/s]');
+			fielddisplay(obj,'rheology_B','flow law parameter [Pa/s^(1/n)]');
+			fielddisplay(obj,'rheology_n','Glen''s flow law exponent');
+			fielddisplay(obj,'rheology_law','law for the temperature dependance of the rheology: ''None'', ''Paterson'' or ''Arrhenius''');
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','rho_ice','format','Double');
+			WriteData(fid,'object',obj,'fieldname','rho_water','format','Double');
+			WriteData(fid,'object',obj,'fieldname','mu_water','format','Double');
+			WriteData(fid,'object',obj,'fieldname','heatcapacity','format','Double');
+			WriteData(fid,'object',obj,'fieldname','latentheat','format','Double');
+			WriteData(fid,'object',obj,'fieldname','thermalconductivity','format','Double');
+			WriteData(fid,'object',obj,'fieldname','meltingpoint','format','Double');
+			WriteData(fid,'object',obj,'fieldname','beta','format','Double');
+			WriteData(fid,'object',obj,'fieldname','mixed_layer_capacity','format','Double');
+			WriteData(fid,'object',obj,'fieldname','thermal_exchange_velocity','format','Double');
+			WriteData(fid,'object',obj,'fieldname','rheology_B','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','rheology_n','format','DoubleMat','mattype',2);
+			WriteData(fid,'data',StringToEnum(obj.rheology_law),'enum',MaterialsRheologyLawEnum,'format','Integer');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/mesh.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/mesh.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/mesh.m	(revision 11330)
@@ -0,0 +1,202 @@
+%MESH class definition
+%
+%   Usage:
+%      mesh=mesh();
+
+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
+	methods
+		function obj = mesh(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				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 checkconsistency(obj,md,solution,analyses) % {{{
+
+			checkfield(md,'mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			checkfield(md,'mesh.y','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			checkfield(md,'mesh.z','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			checkfield(md,'mesh.elements','NaN',1,'>',0,'values',1:md.mesh.numberofvertices);
+			if(md.mesh.dimension==2),
+				checkfield(md,'mesh.elements','size',[md.mesh.numberofelements 3]);
+			else
+				checkfield(md,'mesh.elements','size',[md.mesh.numberofelements 6]);
+			end
+			if any(~ismember(1:md.mesh.numberofvertices,sort(unique(md.mesh.elements(:)))));
+				checkmessage('orphan nodes have been found. Check the mesh outline');
+			end
+			checkfield(md,'mesh.dimension','values',[2 3]);
+			checkfield(md,'mesh.numberoflayers','>=',0);
+			checkfield(md,'mesh.numberofelements','>',0);
+			checkfield(md,'mesh.numberofvertices','>',0);
+			%no checks for numberofedges lat long and hemisphere
+			checkfield(md,'mesh.elementonbed','size',[md.mesh.numberofelements 1],'values',[0 1]);
+			checkfield(md,'mesh.elementonsurface','size',[md.mesh.numberofelements 1],'values',[0 1]);
+			checkfield(md,'mesh.vertexonbed','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			checkfield(md,'mesh.vertexonsurface','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			if (md.mesh.dimension==2),
+				checkfield(md,'mesh.average_vertex_connectivity','>=',9,'message','''mesh.average_vertex_connectivity'' should be at least 9 in 2d');
+			else
+				checkfield(md,'mesh.average_vertex_connectivity','>=',24,'message','''mesh.average_vertex_connectivity'' should be at least 24 in 3d');
+			end
+
+			%Solution specific checks
+			switch(solution),
+				case PrognosticSolutionEnum,
+					if md.prognostic.stabilization==3,
+						checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
+						checkfield(md,'mesh.edges','size',[NaN 4]);
+						checkfield(md,'mesh.edges(:,1:3)','>',0);
+					end
+				case BalancethicknessSolutionEnum,
+					if md.balancethickness.stabilization==3,
+						checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
+						checkfield(md,'mesh.edges','size',[NaN 4]);
+						checkfield(md,'mesh.edges(:,1:3)','>',0);
+					end
+				case TransientSolutionEnum,
+					if md.transient.isprognostic & md.prognostic.stabilization==3,
+						checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
+						checkfield(md,'mesh.edges','size',[NaN 4]);
+						checkfield(md,'mesh.edges(:,1:3)','>',0);
+					end
+				case ThermalSolutionEnum,
+					checkfield(md,'mesh.dimension','values',3,'message','thermal solution only supported on 3d meshes');
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Mesh:')); 
+
+			if obj.dimension==3,
+				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','index into (x,y,z), coordinates of the vertices');
+				fielddisplay(obj,'x2d','vertices x coordinate');
+				fielddisplay(obj,'y2d','vertices y coordinate');
+
+				disp(sprintf('\n      Elements and vertices of the extruded 3d mesh:'));
+			else
+				disp(sprintf('\n      Elements and vertices:'));
+			end
+			fielddisplay(obj,'numberofelements','number of elements');
+			fielddisplay(obj,'numberofvertices','number of vertices');
+			fielddisplay(obj,'elements','index into (x,y,z), coordinates of the vertices');
+			fielddisplay(obj,'x','vertices x coordinate');
+			fielddisplay(obj,'y','vertices y coordinate');
+			fielddisplay(obj,'z','vertices z coordinate');
+			fielddisplay(obj,'edges','edges of the 2d mesh (vertex1 vertex2 element1 element2)');
+			fielddisplay(obj,'numberofedges','number of edges of the 2d mesh');
+
+			disp(sprintf('\n      Properties:'));
+			fielddisplay(obj,'dimension','mesh dimension (2d or 3d)');
+			fielddisplay(obj,'numberoflayers','number of extrusion layers');
+			fielddisplay(obj,'vertexonbed','lower vertices flags list');
+			fielddisplay(obj,'elementonbed','lower elements flags list');
+			fielddisplay(obj,'vertexonsurface','upper vertices flags list');
+			fielddisplay(obj,'elementonsurface','upper elements 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,'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');
+			fielddisplay(obj,'long','vertices longitude');
+			fielddisplay(obj,'hemisphere','Indicate hemisphere ''n'' or ''s'' ');
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','z','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'fieldname','dimension','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','numberoflayers','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','numberofedges','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','elementonbed','format','BooleanMat','mattype',2);
+			WriteData(fid,'object',obj,'fieldname','elementonsurface','format','BooleanMat','mattype',2);
+			WriteData(fid,'object',obj,'fieldname','vertexonbed','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','vertexonsurface','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','lowerelements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'fieldname','upperelements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'fieldname','edges','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','elementconnectivity','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','average_vertex_connectivity','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','elements2d','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','numberofvertices2d','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','numberofelements2d','format','Integer');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/miscellaneous.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/miscellaneous.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/miscellaneous.m	(revision 11330)
@@ -0,0 +1,48 @@
+%MISCELANEOUS class definition
+%
+%   Usage:
+%      miscellaneous=miscellaneous();
+
+classdef miscellaneous
+	properties (SetAccess=public) 
+		notes = '';
+		name  = '';
+		dummy = struct();
+	end
+	methods
+		function obj = miscellaneous(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			checkfield(md,'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,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','name','format','String');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/model/model.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/model/model.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/model/model.m	(revision 11330)
@@ -0,0 +1,460 @@
+%MODEL class definition
+%
+%   Usage:
+%      md = model(varargin)
+
+classdef model
+    properties (SetAccess=public) %Model fields
+		 % {{{1
+		 %Careful here: no other class should be used as default value this is a bug of matlab
+		 mesh             = 0;
+		 mask             = 0;
+
+		 geometry         = 0;
+		 constants        = 0;
+		 surfaceforcings  = 0;
+		 basalforcings    = 0;
+		 materials        = 0;
+		 friction         = 0;
+		 flowequation     = 0;
+		 timestepping     = 0;
+		 initialization   = 0;
+		 rifts            = 0;
+
+		 debug            = 0;
+		 verbose          = 0;
+		 settings         = 0;
+		 solver           = 0;
+		 cluster          = 0;
+
+		 balancethickness = 0;
+		 diagnostic       = 0;
+		 groundingline    = 0;
+		 hydrology        = 0;
+		 prognostic       = 0;
+		 thermal          = 0;
+		 steadystate      = 0;
+		 transient        = 0;
+
+		 autodiff         = 0;
+		 flaim            = 0;
+		 inversion        = 0;
+		 qmu              = 0;
+
+		 results          = 0;
+		 radaroverlay     = 0;
+		 miscellaneous    = 0;
+		 private          = 0;
+
+		 %}}}
+	 end
+	 methods (Static)
+		 function md = loadobj(md) % {{{
+			 % This function is directly called by matlab when a model object is
+			 % loaded. If the input is a struct it is an old version of model and
+			 % old fields must be recovered (make sure they are in the deprecated
+			 % model properties)
+
+			 if verLessThan('matlab','7.9'),
+				 disp('Warning: your matlab version is old and there is a risk that load does not work correctly');
+				 disp('         if the model is not loaded correctly, rename temporarily loadobj so that matlab does not use it');
+
+				 % This is a Matlab bug: all the fields of md have their default value
+				 % Example of error message:
+				 % Warning: Error loading an object of class 'model':
+				 % Undefined function or method 'exist' for input arguments of type 'cell'
+				 %
+				 % This has been fixed in MATLAB 7.9 (R2009b) and later versions
+			 end
+
+			 if isstruct(md)
+				 disp('Recovering model object from a previous version');
+				 md = structtomodel(model,md);
+			 end
+		 end% }}}
+		 function temp = template() % {{{
+
+			 %Get default fields
+			 md=model(0);
+			 modelprops=properties('model');
+
+			 %build output
+			 temp=struct();
+			 for i=1:length(modelprops),
+				 temp.(modelprops{i})=md.(modelprops{i});
+			 end
+
+		 end% }}}
+	 end
+	 methods
+		 function md = model(varargin) % {{{1
+
+			 switch nargin
+				 case 0
+					 md=setdefaultparameters(md);
+				 case 1
+					 in=varargin{1};
+					 if (isa(in,'model'))
+						 %If single argument of class model, we have a copy constructor. 
+						 md = in;
+					 elseif (isa(in,'numeric') & in==0)
+						 %requesting template
+						 %FIXME: for now recursive call
+						 md2=model;
+						 modelprops=properties('model');
+						 for i=1:length(modelprops);
+							 fieldname=modelprops{i};
+							 if md.(fieldname).marshall & isobject(md2.(fieldname)) & isempty(md.(fieldname).preprocess),
+								 eval(['md.' fieldname '=' fieldname '(0);']);
+							 end
+						 end
+					 else
+						 error('model constructor error message: unknown constructor for ''model'' class object');
+					 end 
+
+				 otherwise
+					 error('model constructor error message: 0 of 1 argument only in input.');
+				 end
+		 end
+		 %}}}
+		 function md = structtomodel(md,structmd) % {{{
+
+			 if ~isstruct(structmd) error('input model is not a structure'); end
+
+			 %loaded model is a struct, initialize output and recover all fields
+			 md = structtoobj(model,structmd);
+
+			 %Old field now classes
+			 if (isfield(structmd,'timestepping') & isnumeric(md.timestepping)), md.timestepping=timestepping(); end
+			 if (isfield(structmd,'mask') & isnumeric(md.mask)),md.mask=mask(); end
+
+			 %Field name change
+			 if isfield(structmd,'drag'), md.friction.coefficient=structmd.drag; end
+			 if isfield(structmd,'p'), md.friction.p=structmd.p; end
+			 if isfield(structmd,'q'), md.friction.q=structmd.p; end
+			 if isfield(structmd,'melting'), md.basalforcings.melting_rate=structmd.melting; end
+			 if isfield(structmd,'melting_rate'), md.basalforcings.melting_rate=structmd.melting_rate; end
+			 if isfield(structmd,'accumulation'), md.surfaceforcings.mass_balance=structmd.accumulation; end
+			 if isfield(structmd,'accumulation_rate'), md.surfaceforcings.mass_balance=structmd.accumulation_rate; end
+			 if isfield(structmd,'numberofgrids'), md.mesh.numberofvertices=structmd.numberofgrids; end
+			 if isfield(structmd,'numberofgrids2d'), md.mesh.numberofvertices2d=structmd.numberofgrids2d; end
+			 if isfield(structmd,'uppergrids'), md.mesh.uppervertex=structmd.uppergrids; end
+			 if isfield(structmd,'lowergrids'), md.mesh.lowervertex=structmd.lowergrids; end
+			 if isfield(structmd,'gridonbed'), md.mesh.vertexonbed=structmd.gridonbed; end
+			 if isfield(structmd,'gridonsurface'), md.mesh.vertexonsurface=structmd.gridonsurface; end
+			 if isfield(structmd,'extractedgrids'), md.mesh.extractedvertices=structmd.extractedgrids; end
+			 if isfield(structmd,'gridoniceshelf'), md.mask.vertexonfloatingice=structmd.gridoniceshelf; end
+			 if isfield(structmd,'gridonicesheet'), md.mask.vertexongroundedice=structmd.gridonicesheet; end
+			 if isfield(structmd,'gridonwater'), md.mask.vertexonwater=structmd.gridonwater; end
+			 if isfield(structmd,'gridonboundary'), md.mesh.vertexonboundary=structmd.gridonboundary; end
+			 if isfield(structmd,'petscoptions') & ~isempty(structmd.petscoptions), md.solver=structmd.petscoptions; end
+			 if isfield(structmd,'g'), md.constants.g=structmd.g; end
+			 if isfield(structmd,'yts'), md.constants.yts=structmd.yts; end
+			 if isfield(structmd,'surface_mass_balance'), md.surfaceforcings.mass_balance=structmd.surface_mass_balance; end
+			 if isfield(structmd,'basal_melting_rate'), md.basalforcings.melting_rate=structmd.basal_melting_rate; end
+			 if isfield(structmd,'basal_melting_rate_correction'), md.basalforcings.melting_rate_correction=structmd.basal_melting_rate_correction; end
+			 if isfield(structmd,'geothermalflux'), md.basalforcings.geothermalflux=structmd.geothermalflux; end
+			 if isfield(structmd,'drag'), md.friction.coefficient=structmd.drag; end
+			 if isfield(structmd,'drag_coefficient'), md.friction.coefficient=structmd.drag_coefficient; end
+			 if isfield(structmd,'drag_p'), md.friction.p=structmd.drag_p; end
+			 if isfield(structmd,'drag_q'), md.friction.q=structmd.drag_q; end
+			 if isfield(structmd,'riftproperties'),
+				 md.rifts=rifts;
+				 md.rifts.riftproperties=structmd.riftproperties; 
+			 end
+			 if isfield(structmd,'bamg'), md.private.bamg=structmd.bamg; end
+			 if isfield(structmd,'lowmem'), md.settings.lowmem=structmd.lowmem; end
+			 if isfield(structmd,'io_gather'), md.settings.io_gather=structmd.io_gather; end
+			 if isfield(structmd,'spcwatercolumn'), md.hydrology.spcwatercolumn=structmd.spcwatercolumn; end
+			 if isfield(structmd,'hydro_n'), md.hydrology.n=structmd.hydro_n; end
+			 if isfield(structmd,'hydro_p'), md.hydrology.p=structmd.hydro_p; end
+			 if isfield(structmd,'hydro_q'), md.hydrology.q=structmd.hydro_q; end
+			 if isfield(structmd,'hydro_CR'), md.hydrology.CR=structmd.hydro_CR; end
+			 if isfield(structmd,'hydro_kn'), md.hydrology.kn=structmd.hydro_kn; end
+			 if isfield(structmd,'spctemperature'), md.thermal.spctemperature=structmd.spctemperature; end
+			 if isfield(structmd,'min_thermal_constraints'), md.thermal.penalty_threshold=structmd.min_thermal_constraints; end
+			 if isfield(structmd,'artificial_diffusivity'), md.thermal.stabilization=structmd.artificial_diffusivity; end
+			 if isfield(structmd,'max_nonlinear_iterations'), md.thermal.maxiter=structmd.max_nonlinear_iterations; end
+			 if isfield(structmd,'stabilize_constraints'), md.thermal.penalty_lock=structmd.stabilize_constraints; end
+			 if isfield(structmd,'penalty_offset'), md.thermal.penalty_factor=structmd.penalty_offset; end
+			 if isfield(structmd,'name'), md.miscellaneous.name=structmd.name; end
+			 if isfield(structmd,'notes'), md.miscellaneous.notes=structmd.notes; end
+			 if isfield(structmd,'dummy'), md.miscellaneous.dummy=structmd.dummy; end
+			 if isfield(structmd,'dt'), md.timestepping.time_step=structmd.dt; end
+			 if isfield(structmd,'ndt'), md.timestepping.final_time=structmd.ndt; end
+			 if isfield(structmd,'time_adapt'), md.timestepping.time_adapt=structmd.time_adapt; end
+			 if isfield(structmd,'cfl_coefficient'), md.timestepping.cfl_coefficient=structmd.cfl_coefficient; end
+			 if isfield(structmd,'spcthickness'), md.prognostic.spcthickness=structmd.spcthickness; end
+			 if isfield(structmd,'artificial_diffusivity'), md.prognostic.stabilization=structmd.artificial_diffusivity; end
+			 if isfield(structmd,'hydrostatic_adjustment'), md.prognostic.hydrostatic_adjustment=structmd.hydrostatic_adjustment; end
+			 if isfield(structmd,'penalties'), md.prognostic.vertex_pairing=structmd.penalties; end
+			 if isfield(structmd,'penalty_offset'), md.prognostic.penalty_factor=structmd.penalty_offset; end
+			 if isfield(structmd,'B'), md.materials.rheology_B=structmd.B; end
+			 if isfield(structmd,'n'), md.materials.rheology_n=structmd.n; end
+			 if isfield(structmd,'rheology_B'), md.materials.rheology_B=structmd.rheology_B; end
+			 if isfield(structmd,'rheology_n'), md.materials.rheology_n=structmd.rheology_n; end
+			 if isfield(structmd,'elementoniceshelf'), md.mask.elementonfloatingice=structmd.elementoniceshelf; end
+			 if isfield(structmd,'elementonicesheet'), md.mask.elementongroundedice=structmd.elementonicesheet; end
+			 if isfield(structmd,'elementonwater'), md.mask.elementonwater=structmd.elementonwater; end
+			 if isfield(structmd,'nodeoniceshelf'), md.mask.vertexonfloatingice=structmd.nodeoniceshelf; end
+			 if isfield(structmd,'nodeonicesheet'), md.mask.vertexongroundedice=structmd.nodeonicesheet; end
+			 if isfield(structmd,'nodeonwater'), md.mask.vertexonwater=structmd.nodeonwater; end
+			 if isfield(structmd,'spcthickness'), md.balancethickness.spcthickness=structmd.spcthickness; end
+			 if isfield(structmd,'artificial_diffusivity'), md.balancethickness.stabilization=structmd.artificial_diffusivity; end
+			 if isfield(structmd,'dhdt'), md.balancethickness.thickening_rate=structmd.dhdt; end
+			 if isfield(structmd,'ismacayealpattyn'), md.flowequation.ismacayealpattyn=structmd.ismacayealpattyn; end
+			 if isfield(structmd,'ishutter'), md.flowequation.ishutter=structmd.ishutter; end
+			 if isfield(structmd,'isstokes'), md.flowequation.isstokes=structmd.isstokes; end
+			 if isfield(structmd,'elements_type'), md.flowequation.element_equation=structmd.elements_type; end
+			 if isfield(structmd,'vertices_type'), md.flowequation.vertex_equation=structmd.vertices_type; end
+			 if isfield(structmd,'eps_rel'), md.steadystate.reltol=structmd.eps_rel; end
+			 if isfield(structmd,'max_steadystate_iterations'), md.steadystate.maxiter=structmd.max_steadystate_iterations; end
+			 if isfield(structmd,'isdiagnostic'), md.transient.isdiagnostic=structmd.isdiagnostic; end
+			 if isfield(structmd,'isprognostic'), md.transient.isprognostic=structmd.isprognostic; end
+			 if isfield(structmd,'isthermal'), md.transient.isthermal=structmd.isthermal; end
+			 if isfield(structmd,'control_analysis'), md.inversion.iscontrol=structmd.control_analysis; end
+			 if isfield(structmd,'weights'), md.inversion.cost_functions_coefficients=structmd.weights; end
+			 if isfield(structmd,'nsteps'), md.inversion.nsteps=structmd.nsteps; end
+			 if isfield(structmd,'maxiter_per_step'), md.inversion.maxiter_per_step=structmd.maxiter_per_step; end
+			 if isfield(structmd,'cm_min'), md.inversion.min_parameters=structmd.cm_min; end
+			 if isfield(structmd,'cm_max'), md.inversion.max_parameters=structmd.cm_max; end
+			 if isfield(structmd,'vx_obs'), md.inversion.vx_obs=structmd.vx_obs; end
+			 if isfield(structmd,'vy_obs'), md.inversion.vy_obs=structmd.vy_obs; end
+			 if isfield(structmd,'vel_obs'), md.inversion.vel_obs=structmd.vel_obs; end
+			 if isfield(structmd,'thickness_obs'), md.inversion.thickness_obs=structmd.thickness_obs; end
+			 if isfield(structmd,'vx'), md.initialization.vx=structmd.vx; end
+			 if isfield(structmd,'vy'), md.initialization.vy=structmd.vy; end
+			 if isfield(structmd,'vz'), md.initialization.vz=structmd.vz; end
+			 if isfield(structmd,'vel'), md.initialization.vel=structmd.vel; end
+			 if isfield(structmd,'pressure'), md.initialization.pressure=structmd.pressure; end
+			 if isfield(structmd,'temperature'), md.initialization.temperature=structmd.temperature; end
+			 if isfield(structmd,'waterfraction'), md.initialization.waterfraction=structmd.waterfraction; end
+			 if isfield(structmd,'watercolumn'), md.initialization.watercolumn=structmd.watercolumn; end
+			 if isfield(structmd,'surface'), md.geometry.surface=structmd.surface; end
+			 if isfield(structmd,'bed'), md.geometry.bed=structmd.bed; end
+			 if isfield(structmd,'thickness'), md.geometry.thickness=structmd.thickness; end
+			 if isfield(structmd,'bathymetry'), md.geometry.bathymetry=structmd.bathymetry; end
+			 if isfield(structmd,'thickness_coeff'), md.geometry.hydrostatic_ratio=structmd.thickness_coeff; end
+			 if isfield(structmd,'connectivity'), md.mesh.average_vertex_connectivity=structmd.connectivity; end
+			 if isfield(structmd,'extractednodes'), md.mesh.extractedvertices=structmd.extractednodes; end
+			 if isfield(structmd,'extractedelements'), md.mesh.extractedelements=structmd.extractedelements; end
+			 if isfield(structmd,'nodeonboundary'), md.mesh.vertexonboundary=structmd.nodeonboundary; end
+			 if isfield(structmd,'hemisphere'), md.mesh.hemisphere=structmd.hemisphere; end
+			 if isfield(structmd,'lat'), md.mesh.lat=structmd.lat; end
+			 if isfield(structmd,'long'), md.mesh.long=structmd.long; end
+			 if isfield(structmd,'segments'), md.mesh.segments=structmd.segments; end
+			 if isfield(structmd,'segmentmarkers'), md.mesh.segmentmarkers=structmd.segmentmarkers; end
+			 if isfield(structmd,'dim'), md.mesh.dimension=structmd.dim; end
+			 if isfield(structmd,'numlayers'), md.mesh.numberoflayers=structmd.numlayers; end
+			 if isfield(structmd,'numberofelements'), md.mesh.numberofelements=structmd.numberofelements; end
+			 if isfield(structmd,'numberofvertices'), md.mesh.numberofvertices=structmd.numberofvertices; end
+			 if isfield(structmd,'numberofnodes'), md.mesh.numberofvertices=structmd.numberofnodes; end
+			 if isfield(structmd,'numberofedges'), md.mesh.numberofedges=structmd.numberofedges; end
+			 if isfield(structmd,'numberofelements2d'), md.mesh.numberofelements2d=structmd.numberofelements2d; end
+			 if isfield(structmd,'numberofnodes2d'), md.mesh.numberofvertices2d=structmd.numberofnodes2d; end
+			 if isfield(structmd,'nodeconnectivity'), md.mesh.vertexconnectivity=structmd.nodeconnectivity; end
+			 if isfield(structmd,'elementconnectivity'), md.mesh.elementconnectivity=structmd.elementconnectivity; end
+			 if isfield(structmd,'uppernodes'), md.mesh.uppervertex=structmd.uppernodes; end
+			 if isfield(structmd,'lowernodes'), md.mesh.lowervertex=structmd.lowernodes; end
+			 if isfield(structmd,'upperelements'), md.mesh.upperelements=structmd.upperelements; end
+			 if isfield(structmd,'lowerelements'), md.mesh.lowerelements=structmd.lowerelements; end
+			 if isfield(structmd,'elementonbed'), md.mesh.elementonbed=structmd.elementonbed; end
+			 if isfield(structmd,'elementonsurface'), md.mesh.elementonsurface=structmd.elementonsurface; end
+			 if isfield(structmd,'nodeonsurface'), md.mesh.vertexonsurface=structmd.nodeonsurface; end
+			 if isfield(structmd,'nodeonbed'), md.mesh.vertexonbed=structmd.nodeonbed; end
+			 if isfield(structmd,'elements2d'), md.mesh.elements2d=structmd.elements2d; end
+			 if isfield(structmd,'y2d'), md.mesh.y2d=structmd.y2d; end
+			 if isfield(structmd,'x2d'), md.mesh.x2d=structmd.x2d; end
+			 if isfield(structmd,'elements'), md.mesh.elements=structmd.elements; end
+			 if isfield(structmd,'edges'), md.mesh.edges=structmd.edges; end
+			 if isfield(structmd,'y'), md.mesh.y=structmd.y; end
+			 if isfield(structmd,'x'), md.mesh.x=structmd.x; end
+			 if isfield(structmd,'z'), md.mesh.z=structmd.z; end
+			 if isfield(structmd,'mask'), md.flaim.criterion=structmd.mask; end
+          if isfield(structmd,'pressureload'), md.diagnostic.icefront=structmd.pressureload; end
+			 if isfield(structmd,'diagnostic_ref'), md.diagnostic.referential=structmd.diagnostic_ref; end
+
+			 %Field changes
+			 if (isfield(structmd,'type') & ischar(structmd.type)), 
+				 if strcmpi(structmd.type,'2d'), md.mesh.dimension=2; end
+				 if strcmpi(structmd.type,'3d'), md.mesh.dimension=3; end
+			 end
+			 if isnumeric(md.verbose),
+				 md.verbose=verbose;
+			 end
+			 if size(md.diagnostic.icefront,2)==3 || size(md.diagnostic.icefront,2)==5,
+				 front=md.diagnostic.icefront;
+				 md.diagnostic.icefront=[front 1*md.mask.elementonfloatingice(front(:,end))];
+			 end
+			 if isfield(structmd,'spcvelocity'), 
+				 md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+				 md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+				 md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+				 pos=find(structmd.spcvelocity(:,1)); md.diagnostic.spcvx(pos)=structmd.spcvelocity(pos,4); 
+				 pos=find(structmd.spcvelocity(:,2)); md.diagnostic.spcvy(pos)=structmd.spcvelocity(pos,5); 
+				 pos=find(structmd.spcvelocity(:,3)); md.diagnostic.spcvz(pos)=structmd.spcvelocity(pos,6); 
+			 end
+			 if isfield(structmd,'spcvx'), 
+				 md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+				 pos=find(~isnan(structmd.spcvx)); md.diagnostic.spcvx(pos)=structmd.spcvx(pos); 
+			 end
+			 if isfield(structmd,'spcvy'),
+				 md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+				 pos=find(~isnan(structmd.spcvy)); md.diagnostic.spcvy(pos)=structmd.spcvy(pos);     
+			 end
+			 if isfield(structmd,'spcvz'),
+				 md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+				 pos=find(~isnan(structmd.spcvz)); md.diagnostic.spcvz(pos)=structmd.spcvz(pos);     
+			 end
+			 if ~isempty(structmd.pressureload) & ismember(structmd.pressureload(end,end),[118 119 120]),
+				 pos=find(structmd.pressureload(:,end)==120); md.diagnostic.icefront(pos,end)=0;
+				 pos=find(structmd.pressureload(:,end)==118); md.diagnostic.icefront(pos,end)=1;
+				 pos=find(structmd.pressureload(:,end)==119); md.diagnostic.icefront(pos,end)=2;
+			 end
+			 if isfield(structmd,'elements_type') & structmd.elements_type(end,end)>50,
+				 pos=find(structmd.elements_type==59); md.flowequation.element_equation(pos,end)=0;
+				 pos=find(structmd.elements_type==55); md.flowequation.element_equation(pos,end)=1;
+				 pos=find(structmd.elements_type==56); md.flowequation.element_equation(pos,end)=2;
+				 pos=find(structmd.elements_type==60); md.flowequation.element_equation(pos,end)=3;
+				 pos=find(structmd.elements_type==62); md.flowequation.element_equation(pos,end)=4;
+				 pos=find(structmd.elements_type==57); md.flowequation.element_equation(pos,end)=5;
+				 pos=find(structmd.elements_type==58); md.flowequation.element_equation(pos,end)=6;
+				 pos=find(structmd.elements_type==61); md.flowequation.element_equation(pos,end)=7;
+			 end
+			 if isfield(structmd,'vertices_type') & structmd.vertices_type(end,end)>50,
+				 pos=find(structmd.vertices_type==59); md.flowequation.vertex_equation(pos,end)=0;
+				 pos=find(structmd.vertices_type==55); md.flowequation.vertex_equation(pos,end)=1;
+				 pos=find(structmd.vertices_type==56); md.flowequation.vertex_equation(pos,end)=2;
+				 pos=find(structmd.vertices_type==60); md.flowequation.vertex_equation(pos,end)=3;
+				 pos=find(structmd.vertices_type==62); md.flowequation.vertex_equation(pos,end)=4;
+				 pos=find(structmd.vertices_type==57); md.flowequation.vertex_equation(pos,end)=5;
+				 pos=find(structmd.vertices_type==58); md.flowequation.vertex_equation(pos,end)=6;
+				 pos=find(structmd.vertices_type==61); md.flowequation.vertex_equation(pos,end)=7;
+			 end
+			 if isfield(structmd,'rheology_law') & isnumeric(structmd.rheology_law),
+				 if (structmd.rheology_law==272), md.materials.rheology_law='None';      end
+				 if (structmd.rheology_law==368), md.materials.rheology_law='Paterson';  end
+				 if (structmd.rheology_law==369), md.materials.rheology_law='Arrhenius'; end
+			 end
+			 if isfield(structmd,'groundingline_migration') & isnumeric(structmd.groundingline_migration),
+				 if (structmd.groundingline_migration==272), md.groundingline.migration='None';      end
+				 if (structmd.groundingline_migration==273), md.groundingline.migration='AgressiveMigration';  end
+				 if (structmd.groundingline_migration==274), md.groundingline.migration='SoftMigration'; end
+			 end
+			 if isfield(structmd,'control_type') & isnumeric(structmd.control_type),
+				 if (structmd.control_type==143), md.inversion.control_parameters={'FrictionCoefficient'}; end
+				 if (structmd.control_type==190), md.inversion.control_parameters={'RheologyBbar'}; end
+				 if (structmd.control_type==147), md.inversion.control_parameters={'Thickeningrate'}; end
+			 end
+			 if isfield(structmd,'cm_responses') & ismember(structmd.cm_responses(end,end),[165:170 383 388 389]),
+				 pos=find(structmd.cm_responses==166); md.inversion.cost_functions(pos)=101;
+				 pos=find(structmd.cm_responses==167); md.inversion.cost_functions(pos)=102;
+				 pos=find(structmd.cm_responses==168); md.inversion.cost_functions(pos)=103;
+				 pos=find(structmd.cm_responses==169); md.inversion.cost_functions(pos)=104;
+				 pos=find(structmd.cm_responses==170); md.inversion.cost_functions(pos)=105;
+				 pos=find(structmd.cm_responses==165); md.inversion.cost_functions(pos)=201;
+				 pos=find(structmd.cm_responses==389); md.inversion.cost_functions(pos)=501;
+				 pos=find(structmd.cm_responses==388); md.inversion.cost_functions(pos)=502;
+				 pos=find(structmd.cm_responses==382); md.inversion.cost_functions(pos)=503;
+			 end
+			 if isfield(structmd,'artificial_diffusivity') & structmd.artificial_diffusivity==2,
+					 md.thermal.stabilization=2;
+					 md.prognostic.stabilization=1;
+					 md.balancethickness.stabilization=1;
+			 end
+			 if isnumeric(md.prognostic.hydrostatic_adjustment)
+				 if md.prognostic.hydrostatic_adjustment==269,
+					 md.prognostic.hydrostatic_adjustment='Incremental';
+				 else
+					 md.prognostic.hydrostatic_adjustment='Absolute';
+				 end
+			 end
+
+			 %New fields
+			 if ~isfield(structmd,'upperelements');
+				 md.mesh.upperelements=transpose(1:md.mesh.numberofelements)+md.mesh.numberofelements2d;
+				 md.mesh.upperelements(end-md.mesh.numberofelements2d+1:end)=NaN;
+			 end
+			 if ~isfield(structmd,'lowerelements');
+				 md.mesh.lowerelements=transpose(1:md.mesh.numberofelements)-md.mesh.numberofelements2d;
+				 md.mesh.lowerelements(1:md.mesh.numberofelements2d)=NaN;
+			 end
+			 if ~isfield(structmd,'diagnostic_ref');
+				 md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+			 end
+		 end% }}}
+		 function md = setdefaultparameters(md) % {{{1
+
+			 %initialize subclasses
+			 md.mesh             = mesh();
+			 md.mask             = mask();
+			 md.constants        = constants();
+			 md.geometry         = geometry();
+			 md.initialization   = initialization();
+			 md.surfaceforcings  = surfaceforcings();
+			 md.basalforcings    = basalforcings();
+			 md.friction         = friction();
+			 md.rifts            = rifts();
+			 md.timestepping     = timestepping();
+			 md.groundingline    = groundingline();
+			 md.materials        = materials();
+			 md.flowequation     = flowequation();
+			 md.debug            = debug();
+			 md.verbose          = verbose('solution',true,'qmu',true,'control',true);
+			 md.settings         = settings();
+			 md.solver           = solver();
+			 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum,mumpsoptions);
+			 md.cluster          = none();
+			 md.balancethickness = balancethickness();
+			 md.diagnostic       = diagnostic();
+			 md.hydrology        = hydrology();
+			 md.prognostic       = prognostic();
+			 md.thermal          = thermal();
+			 md.steadystate      = steadystate();
+			 md.transient        = transient();
+			 md.autodiff         = autodiff();
+			 md.flaim            = flaim();
+			 md.inversion        = inversion();
+			 md.qmu              = qmu();
+			 md.radaroverlay     = radaroverlay();
+			 md.results          = struct();
+			 md.miscellaneous    = miscellaneous();
+			 md.private          = private();
+		 end
+		 %}}}
+		 function disp(obj) % {{{
+			 disp(sprintf('%19s: %-22s -- %s','mesh'            ,['[1x1 ' class(obj.mesh) ']'],'mesh properties'));
+			 disp(sprintf('%19s: %-22s -- %s','mask'            ,['[1x1 ' class(obj.mask) ']'],'defines grounded and floating elements'));
+			 disp(sprintf('%19s: %-22s -- %s','geometry'        ,['[1x1 ' class(obj.geometry) ']'],'surface elevation, bedrock topography, ice thickness,...'));
+			 disp(sprintf('%19s: %-22s -- %s','constants'       ,['[1x1 ' class(obj.constants) ']'],'physical constants'));
+			 disp(sprintf('%19s: %-22s -- %s','surfaceforcings' ,['[1x1 ' class(obj.surfaceforcings) ']'],'surface forcings'));
+			 disp(sprintf('%19s: %-22s -- %s','basalforcings'   ,['[1x1 ' class(obj.basalforcings) ']'],'bed forcings'));
+			 disp(sprintf('%19s: %-22s -- %s','materials'       ,['[1x1 ' class(obj.materials) ']'],'material properties'));
+			 disp(sprintf('%19s: %-22s -- %s','friction'        ,['[1x1 ' class(obj.friction) ']'],'basal friction/drag properties'));
+			 disp(sprintf('%19s: %-22s -- %s','flowequation'    ,['[1x1 ' class(obj.flowequation) ']'],'flow equations'));
+			 disp(sprintf('%19s: %-22s -- %s','timestepping'    ,['[1x1 ' class(obj.timestepping) ']'],'time stepping for transient models'));
+			 disp(sprintf('%19s: %-22s -- %s','initialization'  ,['[1x1 ' class(obj.initialization) ']'],'initial guess/state'));
+			 disp(sprintf('%19s: %-22s -- %s','rifts'           ,['[1x1 ' class(obj.rifts) ']'],'rifts properties'));
+			 disp(sprintf('%19s: %-22s -- %s','debug'           ,['[1x1 ' class(obj.debug) ']'],'debugging tools (valgrind, gprof)'));
+			 disp(sprintf('%19s: %-22s -- %s','verbose'         ,['[1x1 ' class(obj.verbose) ']'],'verbosity level in solve'));
+			 disp(sprintf('%19s: %-22s -- %s','settings'        ,['[1x1 ' class(obj.settings) ']'],'settings properties'));
+			 disp(sprintf('%19s: %-22s -- %s','solver'          ,['[1x1 ' class(obj.solver) ']'],'PETSc options for each solution'));
+			 disp(sprintf('%19s: %-22s -- %s','cluster'         ,['[1x1 ' class(obj.cluster) ']'],'cluster parameters (number of cpus...)'));
+			 disp(sprintf('%19s: %-22s -- %s','balancethickness',['[1x1 ' class(obj.balancethickness) ']'],'parameters for balancethickness solution'));
+			 disp(sprintf('%19s: %-22s -- %s','diagnostic'      ,['[1x1 ' class(obj.diagnostic) ']'],'parameters for diagnostic solution'));
+			 disp(sprintf('%19s: %-22s -- %s','groundingline'   ,['[1x1 ' class(obj.groundingline) ']'],'parameters for groundingline solution'));
+			 disp(sprintf('%19s: %-22s -- %s','hydrology'       ,['[1x1 ' class(obj.hydrology) ']'],'parameters for hydrology solution'));
+			 disp(sprintf('%19s: %-22s -- %s','prognostic'      ,['[1x1 ' class(obj.prognostic) ']'],'parameters for prognostic solution'));
+			 disp(sprintf('%19s: %-22s -- %s','thermal'         ,['[1x1 ' class(obj.thermal) ']'],'parameters for thermal solution'));
+			 disp(sprintf('%19s: %-22s -- %s','steadystate'     ,['[1x1 ' class(obj.steadystate) ']'],'parameters for steadystate solution'));
+			 disp(sprintf('%19s: %-22s -- %s','transient'       ,['[1x1 ' class(obj.transient) ']'],'parameters for transient solution'));
+			 disp(sprintf('%19s: %-22s -- %s','autodiff'        ,['[1x1 ' class(obj.autodiff) ']'],'automatic differentiation parameters'));
+			 disp(sprintf('%19s: %-22s -- %s','flaim'           ,['[1x1 ' class(obj.flaim) ']'],'flaim parameters'));
+			 disp(sprintf('%19s: %-22s -- %s','inversion'       ,['[1x1 ' class(obj.inversion) ']'],'parameters for inverse methods'));
+			 disp(sprintf('%19s: %-22s -- %s','qmu'             ,['[1x1 ' class(obj.qmu) ']'],'dakota properties'));
+			 disp(sprintf('%19s: %-22s -- %s','results'         ,['[1x1 ' class(obj.results) ']'],'model results'));
+			 disp(sprintf('%19s: %-22s -- %s','radaroverlay'    ,['[1x1 ' class(obj.radaroverlay) ']'],'radar image for plot overlay'));
+			 disp(sprintf('%19s: %-22s -- %s','miscellaneous'   ,['[1x1 ' class(obj.miscellaneous) ']'],'miscellaneous fields'));
+		 end % }}}
+	 end
+ end
Index: /issm/trunk-jpl-damage/src/m/classes/model/planet.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/model/planet.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/model/planet.m	(revision 11330)
@@ -0,0 +1,48 @@
+%PLANET class definition
+%
+%   Usage:
+%      md = planet(varargin)
+
+classdef planet < model
+    properties (SetAccess=public) %Planet fields
+		 % {{{1
+		 %Planet specific fields
+		 r=NaN;
+		 theta=NaN;
+		 phi=NaN;
+		 %}}}
+	 end
+	 methods
+		function md=planetmesh(md,varargin) % {{{1
+		%PLANETMESH: build 2d shell mesh
+		%
+		% Usage: md=planetmesh(md,'method','mixed','radius',6378000,'angleresol',1);
+		%        md=planetmesh(md,'method','tria','shape','iso','radius',6378000,'refinement',5);
+		%
+
+		%recover options
+		options=pairoptions(varargin{:});
+
+		method=getfieldvalue(options,'method','mixed');
+		
+		if strcmpi(method,'mixed'),
+			%recover radius and angleresol: 
+			radius=getfieldvalue(options,'radius',6378000); %earth radius as default
+			angleresol=getfieldvalue(options,'angleresol',10); %10 degree resolution
+			
+			%call mixed mesh 
+			md=planetmixedmesh(md,radius,angleresol);
+		else
+			%recover radius, shape and level of refinmenet
+			radius=getfieldvalue(options,'radius',6378000); %earth radius as default
+			refinement=getfieldvalue(options,'refinement',5); %refine 5 times
+			shape=getfieldvalue(options,'shape','ico'); 
+			
+			%call triangular mesh
+			md=planettrimesh(md,shape,radius,refinement);
+		end
+
+		end
+		% }}}
+	 end
+ end
Index: /issm/trunk-jpl-damage/src/m/classes/organizer.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/organizer.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/organizer.m	(revision 11330)
@@ -0,0 +1,148 @@
+%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
+    properties (SetAccess=private) 
+		 % {{{1
+		 currentstep   =0;
+	 end
+    properties (SetAccess=public) 
+		 repository    ='./';
+		 prefix        ='model.';
+		 trunkprefix   ='';
+		 steps         =[];
+		 requestedsteps=[0];
+		 %}}}
+	 end
+	 methods
+		 function org=organizer(varargin) % {{{1
+
+			 %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 repository
+			 org.requestedsteps=getfieldvalue(options,'steps',0);
+
+			 %Get trunk prefix (only if provided by user)
+			 if exist(options,'trunkprefix'),
+				 trunkprefix=getfieldvalue(options,'trunkprefix','');
+				 if ~ischar(trunkprefix),                                 error('trunkprefix is not a string'); end
+				 if ~strcmp(regexprep(trunkprefix,'\s+',''),trunkprefix), error('trunkprefix should not have any white space'); end
+				 org.trunkprefix=trunkprefix;
+			 end
+		 end
+		 %}}}
+		 function disp(org) % {{{1
+			 disp(sprintf('   Repository: ''%s''',org.repository));
+			 disp(sprintf('   Prefix:     ''%s''',org.prefix));
+			 if isempty(org.steps)
+				 disp('   no step');
+			 else
+				 for i=1:length(org.steps),
+					 disp(sprintf('   step #%2i: ''%s''',org.steps(i).id,org.steps(i).string));
+				 end
+			 end
+		 end
+		 %}}}
+		 function md=loadmodel(org,string),% {{{1
+
+			 %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'),
+				 md=loadmodel(path);
+				 return;
+			 end
+
+			 %If we are here, the model has not been found. Try trunk prefix if provided
+			 if ~isempty(org.trunkprefix),
+				 path2=[org.repository '/' org.trunkprefix string];
+				 if ~exist(path2,'file'),
+					 error(['Could neither find ' path ', nor ' path2]);
+				 else
+					 disp(['--> Branching ' org.prefix ' from trunk ' org.trunkprefix]);
+					 md=loadmodel(path2);
+					 return;
+				 end
+			 else
+				 error(['Could not find ' path ]);
+			 end
+		 end%}}}
+		 function bool=perform(org,string) % {{{1
+			 
+			 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
+
+			 %assign org back to calling workspace
+			 assignin('caller',inputname(1),org);
+
+		 end%}}}
+		 function savemodel(org,md) % {{{1
+
+			 %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'),       error('savemodel error message: third argument is not a model'); end
+			 if (org.currentstep>length(org.steps)), error(['organizer error message: element with id ' num2str(org.currentstep) ' not found']); end
+
+			 %save model
+			 save(name,'md','-v7.3');
+		 end%}}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/plotoptions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/plotoptions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/plotoptions.m	(revision 11330)
@@ -0,0 +1,154 @@
+%PLOTOPTIONS class definition
+%
+%   Usage:
+%      plotoptions = plotoptions(varargin)
+
+classdef plotoptions
+    properties (SetAccess=public) 
+		 % {{{1
+		 numberofplots = 0;
+		 figurenumber  = 1;
+		 list          = cell(0,0);
+		 %}}}
+	 end
+	 methods
+		 function opt=plotoptions(varargin) % {{{1
+			 opt=buildlist(opt,varargin{:});
+		 end
+		 %}}}
+		 function disp(opt) % {{{1
+			 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) % {{{1
+
+			 %check length of input
+			 if mod((nargin-1),2),
+				 error('buildlist error message: an even number of plotoptions is required')
+			 end
+
+			 %first: build a pairoptions out of varargin:
+			 rawoptions=pairoptions(varargin{:});
+
+			 %get figure number
+			 opt.figurenumber=getfieldvalue(rawoptions,'figure',1);
+
+			 %get number of data to be plotted
+			 numberofplots=fieldoccurences(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(rawoptions.list,1),
+
+				 %If alloptions flag has is on, apply to all plots
+				 if (allflag & ~strcmpi(rawoptions.list{i,1},'data') & ~ismember('#',rawoptions.list{i,1})),
+					 for j=1:numberofplots,
+						 opt.list{j}=addfield(opt.list{j},rawoptions.list{i,1},rawoptions.list{i,2});
+					 end
+
+					 %option contains '#'
+				 elseif ismember('#',rawoptions.list{i,1}),
+
+					 %get suplot(s) associated
+					 string=strsplit(rawoptions.list{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;
+
+							 %#all
+						 elseif strcmpi(plotnum,'all');
+							 for j=1:numberofplots,
+								 opt.list{j}=addfield(opt.list{j},field,rawoptions.list{i,2});
+							 end
+
+							 %#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,rawoptions.list{i,2});
+							 end
+
+							 %#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,rawoptions.list{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},rawoptions.list{i,1});
+							 opt.list{j}=addfield(opt.list{j},rawoptions.list{i,1},rawoptions.list{i,2});
+							 break
+						 else
+							 j=j+1;
+						 end
+					 end
+					 if j>numberofplots,
+						 disp(['plot info message: too many ''' rawoptions.list{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
+		 end
+		 %}}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/private.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/private.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/private.m	(revision 11330)
@@ -0,0 +1,43 @@
+%PRIVATE class definition
+%
+%   Usage:
+%      private=private();
+
+classdef private
+	properties (SetAccess=public) 
+		 runtimename = '';
+		 bamg        = struct();
+		 solution    = '';
+	end
+	methods
+		function obj = private(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   private parameters: do not change'));
+
+			fielddisplay(obj,'runtimename','name of the run launched');
+			fielddisplay(obj,'bamg','structure with mesh properties construced if bamg is used to mesh the domain');
+			fielddisplay(obj,'solution','type of solution launched');
+
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/prognostic.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/prognostic.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/prognostic.m	(revision 11330)
@@ -0,0 +1,77 @@
+%PROGNOSTIC 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;
+	end
+	methods
+		function obj = prognostic(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		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';
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return,
+			if ~ismember(PrognosticAnalysisEnum,analyses) |  (solution==TransientSolutionEnum & md.transient.isprognostic==0), return; end
+
+			checkfield(md,'prognostic.spcthickness','forcing',1);
+			checkfield(md,'prognostic.hydrostatic_adjustment','values',{'Absolute' 'Incremental'});
+			checkfield(md,'prognostic.stabilization','values',[0 1 3]);
+			checkfield(md,'prognostic.min_thickness','>',0);
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Prognostic solution parameters:'));
+			fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint)');
+			fielddisplay(obj,'min_thickness','minimum ice thickness allowed');
+			fielddisplay(obj,'hydrostatic_adjustment','adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute'' ');
+			fielddisplay(obj,'stabilization','0->no, 1->artificial_diffusivity, 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');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','spcthickness','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','min_thickness','format','Double');
+			WriteData(fid,'data',StringToEnum(obj.hydrostatic_adjustment),'format','Integer','enum',PrognosticHydrostaticAdjustmentEnum);
+			WriteData(fid,'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');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/qmu.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu.m	(revision 11330)
@@ -0,0 +1,172 @@
+%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 obj = qmu(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+	
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~md.qmu.isdakota, return; end
+
+			if md.qmu.params.evaluation_concurrency~=1,
+				checkmessage(['model not consistent: concurrency should be set to 1 when running dakota in library mode']);
+			end
+			if ~isempty(md.qmu.partition),
+				if numel(md.qmu.partition)~=md.mesh.numberofvertices,
+					checkmessage(['model not consistent: user supplied partition for qmu analysis should have size md.mesh.numberofvertices x 1 ']);
+				end
+				if find(md.qmu.partition)>=md.mesh.numberofvertices,
+					checkmessage(['model not consistent: user supplied partition should be indexed from 0 (c-convention)']);
+				end
+				if min(md.qmu.partition)~=0,
+					checkmessage(['model not consistent: partition vector not indexed from 0 on']);
+				end
+				if max(md.qmu.partition)>=md.mesh.numberofvertices,
+					checkmessage(['model not consistent: partition vector cannot have maximum index larger than number of nodes']);
+				end
+				if ~isempty(find(md.qmu.partition<0)),
+					checkmessage(['model not consistent: partition vector cannot have values less than 0']);
+				end
+				if ~isempty(find(md.qmu.partition>=md.qmu.numberofpartitions)),
+					checkmessage(['model not consistent: partition vector cannot have values more than md.qmu.numberofpartitions-1']);
+				end
+				if max(md.qmu.partition)>=md.qmu.numberofpartitions,
+					checkmessage(['model not consistent: 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,
+					checkmessage(['model is not correctly configured: 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 partitionition, defaults to metis if not specified') 
+			fielddisplay(obj,'numberofpartitions','number of partitions for semi-descrete 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,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','isdakota','format','Boolean');
+			if ~obj.isdakota, 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');
+			WriteData(fid,'object',obj,'fieldname','mass_flux_segments','format','MatArray');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/qmu/@dakota_method/dakota_method.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/@dakota_method/dakota_method.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/@dakota_method/dakota_method.m	(revision 11330)
@@ -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_diagnostics=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.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/trunk-jpl-damage/src/m/classes/qmu/@dakota_method/dmeth_params_merge.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/@dakota_method/dmeth_params_merge.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/@dakota_method/dmeth_params_merge.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/classes/qmu/@dakota_method/dmeth_params_set.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/@dakota_method/dmeth_params_set.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/@dakota_method/dmeth_params_set.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/classes/qmu/@dakota_method/dmeth_params_write.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/@dakota_method/dmeth_params_write.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/@dakota_method/dmeth_params_write.m	(revision 11330)
@@ -0,0 +1,578 @@
+%
+%  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_diagnostics','','\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);
+                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/trunk-jpl-damage/src/m/classes/qmu/continuous_design.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/continuous_design.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/continuous_design.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/classes/qmu/continuous_state.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/continuous_state.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/continuous_state.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/classes/qmu/least_squares_term.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/least_squares_term.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/least_squares_term.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/classes/qmu/linear_equality_constraint.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/linear_equality_constraint.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/linear_equality_constraint.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/classes/qmu/linear_inequality_constraint.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/linear_inequality_constraint.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/linear_inequality_constraint.m	(revision 11330)
@@ -0,0 +1,205 @@
+%
+%  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/trunk-jpl-damage/src/m/classes/qmu/nonlinear_equality_constraint.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/nonlinear_equality_constraint.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/nonlinear_equality_constraint.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/classes/qmu/nonlinear_inequality_constraint.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/nonlinear_inequality_constraint.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/nonlinear_inequality_constraint.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/classes/qmu/normal_uncertain.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/normal_uncertain.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/normal_uncertain.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/classes/qmu/objective_function.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/objective_function.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/objective_function.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/classes/qmu/response_function.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/response_function.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/response_function.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/classes/qmu/uniform_uncertain.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/qmu/uniform_uncertain.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/qmu/uniform_uncertain.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/classes/radaroverlay.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/radaroverlay.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/radaroverlay.m	(revision 11330)
@@ -0,0 +1,40 @@
+%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);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				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');
+			fielddisplay(obj,'y','corresponding y coordinates');
+
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/rifts.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/rifts.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/rifts.m	(revision 11330)
@@ -0,0 +1,92 @@
+%RIFTS class definition
+%
+%   Usage:
+%      rifts=rifts();
+
+classdef rifts
+	properties (SetAccess=public) 
+		riftstruct     = NaN;
+		riftproperties = NaN;
+	end
+	methods
+		function obj = rifts(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+			if isempty(obj.riftstruct) | isnans(obj.riftstruct),
+				numrifts=0;
+			else
+				numrifts=numel(obj.riftstruct);
+			end
+			if numrifts,
+				if ~(md.mesh.dimension==2),
+					checkmessage(['model not consistent: models with rifts are only supported in 2d for now!']);
+				end
+				if ~isstruct(obj.riftstruct),
+					checkmessage(['rifts.riftstruct should be a structure!']);
+				end
+				if ~isempty(find(md.mesh.segmentmarkers>=2)),
+					%We have segments with rift markers, but no rift structure!
+					checkmessage(['model should be processed for rifts (run meshprocessrifts)!']);
+				end
+				checkfield(md,'rifts.riftstruct.fill','values',[WaterEnum() AirEnum() IceEnum() MelangeEnum()]);
+			else
+				if ~isnans(obj.riftstruct),
+					checkmessage(['riftstruct shoud 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,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/trunk-jpl-damage/src/m/classes/settings.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/settings.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/settings.m	(revision 11330)
@@ -0,0 +1,77 @@
+%SETTINGS class definition
+%
+%   Usage:
+%      settings=settings();
+
+classdef settings
+	properties (SetAccess=public) 
+		io_gather           = 0;
+		lowmem              = 0;
+		results_as_patches  = 0;
+		output_frequency    = 0;
+		waitonlock          = 0;
+	end
+	methods
+		function obj = settings(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				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;
+
+			%do not use patches by default (difficult to plot)
+			obj.results_as_patches=0;
+
+			%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 desactivate
+			obj.waitonlock=Inf;
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			checkfield(md,'settings.io_gather','numel',1,'values',[0 1]);
+			checkfield(md,'settings.lowmem','numel',1,'values',[0 1]);
+			checkfield(md,'settings.results_as_patches','numel',1,'values',[0 1]);
+			checkfield(md,'settings.output_frequency','numel',1,'>=',1);
+			checkfield(md,'settings.waitonlock','numel',1);
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   general settings parameters:'));
+
+			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,'results_as_patches','provide results as patches for each element (0 or 1)');
+			fielddisplay(obj,'output_frequency','frequency at which results are saved in all solutions with multiple time_steps');
+			fielddisplay(obj,'waitonlock','maximum number of minutes to wait for batch results, or return 0');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','io_gather','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','lowmem','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','results_as_patches','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','output_frequency','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','waitonlock','format','Boolean');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/solver.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/solver.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/solver.m	(revision 11330)
@@ -0,0 +1,133 @@
+%SOLVER class definition
+%
+%   Usage:
+%      obj=solver();
+
+classdef solver
+    properties (SetAccess=public) 
+		 options={NoneAnalysisEnum,mumpsoptions};
+	 end
+	 methods
+		 function obj = solver(varargin) % {{{
+			 switch nargin
+				 case 0
+					 obj=setdefaultparameters(obj);
+				 case 1
+					 in=varargin{1};
+					 if (isa(in,'numeric') & in==0),
+						 % requesting templates do nothing
+					 else
+						 error('constructor not supported');
+					 end 
+				 otherwise
+					 error('constructor not supported');
+				 end
+			 end % }}}
+		 function obj = setdefaultparameters(obj) % {{{
+
+		 end % }}}
+		 function obj=addoptions(obj,analysis,solveroptions) % {{{1
+			 %first, find out if analysis has already been supplied
+			 found=false;
+			 for i=1:size(obj.options,1),
+				 inanalysis=obj.options{i,1};
+				 if inanalysis==analysis,
+					 found=true;
+					 obj.options{i,1}=analysis;
+					 obj.options{i,2}=solveroptions;
+					 break;
+				 end
+			 end
+			 if ~found,
+				 obj.options{end+1,1}=analysis;
+				 obj.options{end,2}=solveroptions;
+			 end
+		 end
+		 %}}}
+		 function checkconsistency(obj,md,solution,analyses) % {{{
+
+		 end % }}}
+		 function PetscFile(solver,filename) % {{{
+			 %PETSCFILE - build petsc file
+			 %
+			 %   Build a Petsc compatible options file, from the solver model field  + return options string
+			 %
+			 %   Usage:     PetscFile(solver,filename);
+
+			 %open file for writing
+			 fid=fopen(filename,'w');
+			 if fid==-1,
+				 error(['PetscFile error: could not open ' filename ' for writing']);
+			 end
+
+			 %write header
+			 fprintf(fid,'%s%s%s\n','%Petsc options file: ',filename,' written from Matlab solver array');
+
+			 %start writing options
+			 for i=1:size(solver.options,1),
+				 analysis=solver.options{i,1};
+				 options=solver.options{i,2};
+
+				 %first write analysis:
+				 fprintf(fid,'\n+%s\n',EnumToString(analysis)); %append a + to recognize it's an analysis enum
+
+				 %now, write options
+				 for j=1:size(options,2),
+					 option=options{j};
+					 if isempty(option),
+						 %do nothing
+					 elseif length(option)==1,
+						 %this option has only one argument
+						 fprintf(fid,'-%s\n',option{1});
+					 elseif length(option)==2,
+						 %option with value. value can be string or scalar
+						 if isscalar(option{2}),
+							 fprintf(fid,'-%s %g\n',option{1},option{2});
+						 elseif ischar(option{2}),
+							 fprintf(fid,'-%s %s\n',option{1},option{2});
+						 else
+							 error(['PetscFile error: option #' num2str(j) ' is not well formatted']);
+						 end
+					 else 
+						 error(['PetscFile error: option #' num2str(j) ' is not well formatted']);
+					 end
+				 end
+			 end
+
+			 fclose(fid);
+		 end %}}}
+		 function disp(obj) % {{{1
+			disp(sprintf('   solver parameters:'));
+
+			for i=1:size(obj.options,1),
+				analysis=obj.options{i,1};
+				ioptions=obj.options{i,2};
+
+				string='';
+				for i=1:length(ioptions),
+					option=ioptions{i};
+					if isempty(option),
+						%do nothing
+					elseif length(option)==1,
+						%this option has only one argument
+						string=[string ' -' option{1}];
+					elseif length(option)==2,
+						%option with value. value can be string or scalar
+						if isscalar(option{2}),
+							string=[string ' -' option{1} ' ' num2str(option{2})];
+						elseif ischar(option{2}),
+							string=[string ' -' option{1} ' ' option{2}];
+						else
+							error(['PetscString error: option #' num2str(i) ' is not well formatted']);
+						end
+					else 
+						error(['PetscString error: option #' num2str(i) ' is not well formatted']);
+					end
+				end
+
+				disp(sprintf('   %s -> ''%s''',EnumToString(analysis),string));
+			end
+		 end
+		 %}}}
+	 end
+ end
Index: /issm/trunk-jpl-damage/src/m/classes/steadystate.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/steadystate.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/steadystate.m	(revision 11330)
@@ -0,0 +1,62 @@
+%STEADYSTATE class definition
+%
+%   Usage:
+%      steadystate=steadystate();
+
+classdef steadystate
+	properties (SetAccess=public) 
+		reltol            = 0;
+		maxiter           = 0;
+		requested_outputs = NaN;
+	end
+	methods
+		function obj = steadystate(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				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;
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if solution~=SteadystateSolutionEnum, return; end;
+
+			if md.timestepping.time_step~=0,
+				checkmessage(['model not consistent: for a steadystate computation, timestepping.time_step must be zero.']);
+			end
+
+			if isnan(md.diagnostic.reltol),
+				checkmessage(['model not consistent: for a steadystate computation, diagnostic.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,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','reltol','format','Double');
+			WriteData(fid,'object',obj,'fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/surfaceforcings.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/surfaceforcings.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/surfaceforcings.m	(revision 11330)
@@ -0,0 +1,54 @@
+%SURFACEFORCING Class definition
+%
+%   Usage:
+%      surfaceforcings=surfaceforcings();
+
+classdef surfaceforcings
+	properties (SetAccess=public) 
+		accumulation_rate = NaN;
+		ablation_rate     = NaN;
+		mass_balance      = NaN;
+	end
+	methods
+		function obj = surfaceforcings(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			if ismember(PrognosticAnalysisEnum,analyses),
+				checkfield(md,'surfaceforcings.mass_balance','forcing',1,'NaN',1);
+			end
+			if ismember(BalancethicknessAnalysisEnum,analyses),
+				checkfield(md,'surfaceforcings.mass_balance','size',[md.mesh.numberofvertices 1],'NaN',1);
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   surface forcings parameters:'));
+
+			fielddisplay(obj,'accumulation_rate','surface accumulation rate [m]');
+			fielddisplay(obj,'ablation_rate','surface ablation rate [m]');
+			fielddisplay(obj,'mass_balance','surface mass balance [m]');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','accumulation_rate','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','ablation_rate','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','mass_balance','format','DoubleMat','mattype',1);
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/thermal.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/thermal.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/thermal.m	(revision 11330)
@@ -0,0 +1,75 @@
+%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;
+	end
+	methods
+		function obj = thermal(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			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;
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if (~ismember(ThermalAnalysisEnum,analyses) & ~ismember(EnthalpyAnalysisEnum,analyses)) | (solution==TransientSolutionEnum & md.transient.isthermal==0), return; end
+
+			checkfield(md,'thermal.stabilization','numel',1,'values',[0 1 2]);
+			checkfield(md,'thermal.spctemperature','forcing',1);
+			if ismember(EnthalpyAnalysisEnum,analyses),
+			checkfield(md,'thermal.spctemperature','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*md.geometry.thickness,'message','spctemperature should be below the adjusted melting point');
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Thermal solution parameters:'));
+
+			fielddisplay(obj,'spctemperature','temperature constraints (NaN means no constraint)');
+			fielddisplay(obj,'stabilization','0->no, 1->artificial_diffusivity, 2->SUPG');
+			fielddisplay(obj,'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)');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','spctemperature','format','DoubleMat','mattype',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');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/timestepping.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/timestepping.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/timestepping.m	(revision 11330)
@@ -0,0 +1,62 @@
+%TIMESTEPPING Class definition
+%
+%   Usage:
+%      timestepping=timestepping();
+
+classdef timestepping
+	properties (SetAccess=public) 
+		time_step       = 0;
+		final_time      = 0;
+		time_adapt      = 0;
+		cfl_coefficient = 0;
+	end
+	methods
+		function obj = timestepping(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				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=.5;
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			checkfield(md,'timestepping.time_adapt','numel',1,'values',[0 1]);
+			checkfield(md,'timestepping.cfl_coefficient','numel',1,'>',0,'<=',1);
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   timestepping parameters:'));
+
+			fielddisplay(obj,'time_step','length of time steps [yrs]');
+			fielddisplay(obj,'final_time','final time to stop the simulation [yrs]');
+			fielddisplay(obj,'time_adapt','use cfl condition to define time step ? (0 or 1) ');
+			fielddisplay(obj,'cfl_coefficient','coefficient applied to cfl condition');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','time_step','format','Double');
+			WriteData(fid,'object',obj,'fieldname','final_time','format','Double');
+			WriteData(fid,'object',obj,'fieldname','time_adapt','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','cfl_coefficient','format','Double');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/transient.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/transient.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/transient.m	(revision 11330)
@@ -0,0 +1,68 @@
+%TRANSIENT class definition
+%
+%   Usage:
+%      transient=transient();
+
+classdef transient
+	properties (SetAccess=public) 
+		isprognostic      = 0;
+		isdiagnostic      = 0;
+		isthermal         = 0;
+		isgroundingline   = 0;
+		requested_outputs = NaN;
+	end
+	methods
+		function obj = transient(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					in=varargin{1};
+					if (isa(in,'numeric') & in==0),
+						% requesting templates do nothing
+					else
+						error('constructor not supported');
+					end 
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%full analysis: Diagnostic, Prognostic and Thermal but no groundingline migration for now
+			obj.isprognostic=1;
+			obj.isdiagnostic=1;
+			obj.isthermal=1;
+			obj.isgroundingline=0;
+
+		end % }}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if solution~=TransientSolutionEnum, return; end
+
+			checkfield(md,'transient.isprognostic','numel',1,'values',[0 1]);
+			checkfield(md,'transient.isdiagnostic','numel',1,'values',[0 1]);
+			checkfield(md,'transient.isthermal','numel',1,'values',[0 1]);
+			checkfield(md,'transient.isgroundingline','numel',1,'values',[0 1]);
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   transient solution parameters:'));
+
+			fielddisplay(obj,'isprognostic','indicates if a prognostic solution is used in the transient');
+			fielddisplay(obj,'isthermal','indicates if a thermal solution is used in the transient');
+			fielddisplay(obj,'isdiagnostic','indicates if a diagnostic solution is used in the transient');
+			fielddisplay(obj,'isgroundingline','indicates if a groundingline migration is used in the transient');
+			fielddisplay(obj,'requested_outputs','list of additional outputs requested');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','isprognostic','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isdiagnostic','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isthermal','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isgroundingline','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/classes/verbose.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/classes/verbose.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/classes/verbose.m	(revision 11330)
@@ -0,0 +1,123 @@
+%VERBOSE class definition
+%
+%   Available verbosity levels:
+%      mprocessor  : model processing 
+%      module      : modules
+%      solution    : solution sequence
+%      solver      : solver info (extensive)
+%      convergence : convergence criteria
+%      control     : control method
+%      qmu         : sensitivity analysis
+%
+%   Usage:
+%      verbose=verbose();
+%      verbose=verbose(3);
+%      verbose=verbose('001100');
+%      verbose=verbose('module',true,'solver',false);
+
+%WARNING: some parts of this file are Synchronized with src/c/shared/Numerics/Verbosity.h
+%         Do not modify these sections. See src/c/shared/Numerics/README for more info
+
+classdef verbose
+	properties (SetAccess=public) 
+		% {{{1
+		%BEGINFIELDS
+		mprocessor  = false;
+		module      = false;
+		solution    = false;
+		solver      = false;
+		convergence = false;
+		control     = false;
+		qmu         = false;
+		%ENDFIELDS
+		% }}}
+	end
+	%}}}
+	methods
+		function verbose=verbose(varargin) % {{{1
+
+			if nargin==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
+				end 
+			else
+
+				options=pairoptions(varargin{:});
+				for i=1:size(options.list,1),
+					fieldname=options.list{i,1};
+					fieldvalue=options.list{i,2};
+					if ismember(fieldname,properties('verbose')),
+						if islogical(fieldvalue) | isnumeric(fieldvalue),
+							verbose.(fieldname)=logical(fieldvalue);
+						else
+							error('verbose supported field values are logicals only (true or false)');
+						end
+					else
+						disp(['''' fieldname ''' is not a property of verbose verbose']);
+					end
+				end
+
+			end
+		end
+		%}}}
+		function binary=VerboseToBinary(verbose) % {{{1
+
+		%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
+		%ENDVERB2BIN
+
+		end
+		%}}}
+		function verbose=BinaryToVerbose(verbose,binary) % {{{1
+
+		%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
+		%ENDBIN2VERB
+
+		end
+		%}}}
+		function checkconsistency(obj,md,solution,analyses) % {{{
+
+		end % }}}
+		function disp(verbose) % {{{1
+			
+		%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)));
+		%ENDDISP
+
+		end
+		%}}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'data',VerboseToBinary(obj),'enum',VerboseEnum,'format','Integer');
+		end % }}}
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/enum/AbsoluteEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AbsoluteEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AbsoluteEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AbsoluteEnum()
+
+macro=StringToEnum('Absolute');
Index: /issm/trunk-jpl-damage/src/m/enum/AdjointBalancethicknessAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AdjointBalancethicknessAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AdjointBalancethicknessAnalysisEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AdjointBalancethicknessAnalysisEnum()
+
+macro=StringToEnum('AdjointBalancethicknessAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/AdjointEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AdjointEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AdjointEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AdjointEnum()
+
+macro=StringToEnum('Adjoint');
Index: /issm/trunk-jpl-damage/src/m/enum/AdjointHorizAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AdjointHorizAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AdjointHorizAnalysisEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AdjointHorizAnalysisEnum()
+
+macro=StringToEnum('AdjointHorizAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/AdjointSolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AdjointSolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AdjointSolutionEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=AdjointSolutionEnum()
+%ADJOINTSOLUTIONENUM - Enum of AdjointSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AdjointSolutionEnum()
+
+macro=StringToEnum('AdjointSolution');
Index: /issm/trunk-jpl-damage/src/m/enum/AdjointpEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AdjointpEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AdjointpEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AdjointpEnum()
+
+macro=StringToEnum('Adjointp');
Index: /issm/trunk-jpl-damage/src/m/enum/AdjointxEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AdjointxEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AdjointxEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AdjointxEnum()
+
+macro=StringToEnum('Adjointx');
Index: /issm/trunk-jpl-damage/src/m/enum/AdjointyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AdjointyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AdjointyEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AdjointyEnum()
+
+macro=StringToEnum('Adjointy');
Index: /issm/trunk-jpl-damage/src/m/enum/AdjointzEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AdjointzEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AdjointzEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AdjointzEnum()
+
+macro=StringToEnum('Adjointz');
Index: /issm/trunk-jpl-damage/src/m/enum/AgressiveMigrationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AgressiveMigrationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AgressiveMigrationEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=AgressiveMigrationEnum()
+%AGRESSIVEMIGRATIONENUM - Enum of AgressiveMigration
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AgressiveMigrationEnum()
+
+macro=StringToEnum('AgressiveMigration');
Index: /issm/trunk-jpl-damage/src/m/enum/AirEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AirEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AirEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AirEnum()
+
+macro=StringToEnum('Air');
Index: /issm/trunk-jpl-damage/src/m/enum/AnalysisCounterEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AnalysisCounterEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AnalysisCounterEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AnalysisCounterEnum()
+
+macro=StringToEnum('AnalysisCounter');
Index: /issm/trunk-jpl-damage/src/m/enum/AnalysisTypeEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AnalysisTypeEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AnalysisTypeEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AnalysisTypeEnum()
+
+macro=StringToEnum('AnalysisType');
Index: /issm/trunk-jpl-damage/src/m/enum/ApproximationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ApproximationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ApproximationEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ApproximationEnum()
+
+macro=StringToEnum('Approximation');
Index: /issm/trunk-jpl-damage/src/m/enum/ArrheniusEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ArrheniusEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ArrheniusEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ArrheniusEnum()
+
+macro=StringToEnum('Arrhenius');
Index: /issm/trunk-jpl-damage/src/m/enum/AutodiffForwardEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AutodiffForwardEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AutodiffForwardEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=AutodiffForwardEnum()
+%AUTODIFFFORWARDENUM - Enum of AutodiffForward
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AutodiffForwardEnum()
+
+macro=StringToEnum('AutodiffForward');
Index: /issm/trunk-jpl-damage/src/m/enum/AutodiffIsautodiffEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AutodiffIsautodiffEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AutodiffIsautodiffEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AutodiffIsautodiffEnum()
+
+macro=StringToEnum('AutodiffIsautodiff');
Index: /issm/trunk-jpl-damage/src/m/enum/AutodiffReverseEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/AutodiffReverseEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/AutodiffReverseEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=AutodiffReverseEnum()
+%AUTODIFFREVERSEENUM - Enum of AutodiffReverse
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=AutodiffReverseEnum()
+
+macro=StringToEnum('AutodiffReverse');
Index: /issm/trunk-jpl-damage/src/m/enum/BalancethicknessAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BalancethicknessAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BalancethicknessAnalysisEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessAnalysisEnum()
+
+macro=StringToEnum('BalancethicknessAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/BalancethicknessSolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BalancethicknessSolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BalancethicknessSolutionEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessSolutionEnum()
+
+macro=StringToEnum('BalancethicknessSolution');
Index: /issm/trunk-jpl-damage/src/m/enum/BalancethicknessSpcthicknessEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BalancethicknessSpcthicknessEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BalancethicknessSpcthicknessEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessSpcthicknessEnum()
+
+macro=StringToEnum('BalancethicknessSpcthickness');
Index: /issm/trunk-jpl-damage/src/m/enum/BalancethicknessStabilizationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BalancethicknessStabilizationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BalancethicknessStabilizationEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessStabilizationEnum()
+
+macro=StringToEnum('BalancethicknessStabilization');
Index: /issm/trunk-jpl-damage/src/m/enum/BalancethicknessThickeningRateEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BalancethicknessThickeningRateEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BalancethicknessThickeningRateEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessThickeningRateEnum()
+
+macro=StringToEnum('BalancethicknessThickeningRate');
Index: /issm/trunk-jpl-damage/src/m/enum/BasalFrictionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BasalFrictionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BasalFrictionEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BasalFrictionEnum()
+
+macro=StringToEnum('BasalFriction');
Index: /issm/trunk-jpl-damage/src/m/enum/BasalforcingsGeothermalfluxEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BasalforcingsGeothermalfluxEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BasalforcingsGeothermalfluxEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsGeothermalfluxEnum()
+
+macro=StringToEnum('BasalforcingsGeothermalflux');
Index: /issm/trunk-jpl-damage/src/m/enum/BasalforcingsMeltingRateCorrectionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BasalforcingsMeltingRateCorrectionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BasalforcingsMeltingRateCorrectionEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsMeltingRateCorrectionEnum()
+%BASALFORCINGSMELTINGRATECORRECTIONENUM - Enum of BasalforcingsMeltingRateCorrection
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsMeltingRateCorrectionEnum()
+
+macro=StringToEnum('BasalforcingsMeltingRateCorrection');
Index: /issm/trunk-jpl-damage/src/m/enum/BasalforcingsMeltingRateEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BasalforcingsMeltingRateEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BasalforcingsMeltingRateEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=BasalforcingsMeltingRateEnum()
+%BASALFORCINGSMELTINGRATEENUM - Enum of BasalforcingsMeltingRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BasalforcingsMeltingRateEnum()
+
+macro=StringToEnum('BasalforcingsMeltingRate');
Index: /issm/trunk-jpl-damage/src/m/enum/BathymetryEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BathymetryEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BathymetryEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=BathymetryEnum()
+%BATHYMETRYENUM - Enum of Bathymetry
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BathymetryEnum()
+
+macro=StringToEnum('Bathymetry');
Index: /issm/trunk-jpl-damage/src/m/enum/BedEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BedEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BedEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BedEnum()
+
+macro=StringToEnum('Bed');
Index: /issm/trunk-jpl-damage/src/m/enum/BedSlopeAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BedSlopeAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BedSlopeAnalysisEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=BedSlopeAnalysisEnum()
+%BEDSLOPEANALYSISENUM - Enum of BedSlopeAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BedSlopeAnalysisEnum()
+
+macro=StringToEnum('BedSlopeAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/BedSlopeSolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BedSlopeSolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BedSlopeSolutionEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BedSlopeSolutionEnum()
+
+macro=StringToEnum('BedSlopeSolution');
Index: /issm/trunk-jpl-damage/src/m/enum/BedSlopeXAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BedSlopeXAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BedSlopeXAnalysisEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=BedSlopeXAnalysisEnum()
+%BEDSLOPEXANALYSISENUM - Enum of BedSlopeXAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BedSlopeXAnalysisEnum()
+
+macro=StringToEnum('BedSlopeXAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/BedSlopeXEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BedSlopeXEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BedSlopeXEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BedSlopeXEnum()
+
+macro=StringToEnum('BedSlopeX');
Index: /issm/trunk-jpl-damage/src/m/enum/BedSlopeYAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BedSlopeYAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BedSlopeYAnalysisEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=BedSlopeYAnalysisEnum()
+%BEDSLOPEYANALYSISENUM - Enum of BedSlopeYAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BedSlopeYAnalysisEnum()
+
+macro=StringToEnum('BedSlopeYAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/BedSlopeYEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BedSlopeYEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BedSlopeYEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BedSlopeYEnum()
+
+macro=StringToEnum('BedSlopeY');
Index: /issm/trunk-jpl-damage/src/m/enum/BilinearInterpEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BilinearInterpEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BilinearInterpEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BilinearInterpEnum()
+
+macro=StringToEnum('BilinearInterp');
Index: /issm/trunk-jpl-damage/src/m/enum/BoolElementResultEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BoolElementResultEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BoolElementResultEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=BoolElementResultEnum()
+%BOOLELEMENTRESULTENUM - Enum of BoolElementResult
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BoolElementResultEnum()
+
+macro=StringToEnum('BoolElementResult');
Index: /issm/trunk-jpl-damage/src/m/enum/BoolExternalResultEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BoolExternalResultEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BoolExternalResultEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BoolExternalResultEnum()
+
+macro=StringToEnum('BoolExternalResult');
Index: /issm/trunk-jpl-damage/src/m/enum/BoolInputEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BoolInputEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BoolInputEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BoolInputEnum()
+
+macro=StringToEnum('BoolInput');
Index: /issm/trunk-jpl-damage/src/m/enum/BoolParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BoolParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BoolParamEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BoolParamEnum()
+
+macro=StringToEnum('BoolParam');
Index: /issm/trunk-jpl-damage/src/m/enum/BoundaryEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/BoundaryEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/BoundaryEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=BoundaryEnum()
+
+macro=StringToEnum('Boundary');
Index: /issm/trunk-jpl-damage/src/m/enum/ClosedEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ClosedEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ClosedEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ClosedEnum()
+
+macro=StringToEnum('Closed');
Index: /issm/trunk-jpl-damage/src/m/enum/ColinearEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ColinearEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ColinearEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ColinearEnum()
+
+macro=StringToEnum('Colinear');
Index: /issm/trunk-jpl-damage/src/m/enum/ConfigurationTypeEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ConfigurationTypeEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ConfigurationTypeEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ConfigurationTypeEnum()
+
+macro=StringToEnum('ConfigurationType');
Index: /issm/trunk-jpl-damage/src/m/enum/ConstantEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ConstantEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ConstantEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=ConstantEnum()
+%CONSTANTENUM - Enum of Constant
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ConstantEnum()
+
+macro=StringToEnum('Constant');
Index: /issm/trunk-jpl-damage/src/m/enum/ConstantsGEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ConstantsGEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ConstantsGEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ConstantsGEnum()
+
+macro=StringToEnum('ConstantsG');
Index: /issm/trunk-jpl-damage/src/m/enum/ConstantsReferencetemperatureEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ConstantsReferencetemperatureEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ConstantsReferencetemperatureEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ConstantsReferencetemperatureEnum()
+
+macro=StringToEnum('ConstantsReferencetemperature');
Index: /issm/trunk-jpl-damage/src/m/enum/ConstantsYtsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ConstantsYtsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ConstantsYtsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ConstantsYtsEnum()
+
+macro=StringToEnum('ConstantsYts');
Index: /issm/trunk-jpl-damage/src/m/enum/ConstraintsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ConstraintsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ConstraintsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ConstraintsEnum()
+
+macro=StringToEnum('Constraints');
Index: /issm/trunk-jpl-damage/src/m/enum/ControlInputEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ControlInputEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ControlInputEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ControlInputEnum()
+
+macro=StringToEnum('ControlInput');
Index: /issm/trunk-jpl-damage/src/m/enum/ControlSteadyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ControlSteadyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ControlSteadyEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ControlSteadyEnum()
+
+macro=StringToEnum('ControlSteady');
Index: /issm/trunk-jpl-damage/src/m/enum/ConvergedEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ConvergedEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ConvergedEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ConvergedEnum()
+
+macro=StringToEnum('Converged');
Index: /issm/trunk-jpl-damage/src/m/enum/DatasetInputEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DatasetInputEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DatasetInputEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DatasetInputEnum()
+
+macro=StringToEnum('DatasetInput');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticAbstolEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticAbstolEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticAbstolEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticAbstolEnum()
+%DIAGNOSTICABSTOLENUM - Enum of DiagnosticAbstol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticAbstolEnum()
+
+macro=StringToEnum('DiagnosticAbstol');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticHorizAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticHorizAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticHorizAnalysisEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticHorizAnalysisEnum()
+%DIAGNOSTICHORIZANALYSISENUM - Enum of DiagnosticHorizAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticHorizAnalysisEnum()
+
+macro=StringToEnum('DiagnosticHorizAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticHutterAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticHutterAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticHutterAnalysisEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticHutterAnalysisEnum()
+%DIAGNOSTICHUTTERANALYSISENUM - Enum of DiagnosticHutterAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticHutterAnalysisEnum()
+
+macro=StringToEnum('DiagnosticHutterAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticIcefrontEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticIcefrontEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticIcefrontEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticIcefrontEnum()
+%DIAGNOSTICICEFRONTENUM - Enum of DiagnosticIcefront
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticIcefrontEnum()
+
+macro=StringToEnum('DiagnosticIcefront');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticMaxiterEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticMaxiterEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticMaxiterEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticMaxiterEnum()
+%DIAGNOSTICMAXITERENUM - Enum of DiagnosticMaxiter
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticMaxiterEnum()
+
+macro=StringToEnum('DiagnosticMaxiter');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticNumRequestedOutputsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticNumRequestedOutputsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticNumRequestedOutputsEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticNumRequestedOutputsEnum()
+%DIAGNOSTICNUMREQUESTEDOUTPUTSENUM - Enum of DiagnosticNumRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticNumRequestedOutputsEnum()
+
+macro=StringToEnum('DiagnosticNumRequestedOutputs');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticPenaltyFactorEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticPenaltyFactorEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticPenaltyFactorEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticPenaltyFactorEnum()
+%DIAGNOSTICPENALTYFACTORENUM - Enum of DiagnosticPenaltyFactor
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticPenaltyFactorEnum()
+
+macro=StringToEnum('DiagnosticPenaltyFactor');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticReferentialEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticReferentialEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticReferentialEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticReferentialEnum()
+%DIAGNOSTICREFERENTIALENUM - Enum of DiagnosticReferential
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticReferentialEnum()
+
+macro=StringToEnum('DiagnosticReferential');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticReltolEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticReltolEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticReltolEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticReltolEnum()
+%DIAGNOSTICRELTOLENUM - Enum of DiagnosticReltol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticReltolEnum()
+
+macro=StringToEnum('DiagnosticReltol');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticRequestedOutputsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticRequestedOutputsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticRequestedOutputsEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticRequestedOutputsEnum()
+%DIAGNOSTICREQUESTEDOUTPUTSENUM - Enum of DiagnosticRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticRequestedOutputsEnum()
+
+macro=StringToEnum('DiagnosticRequestedOutputs');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticRestolEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticRestolEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticRestolEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticRestolEnum()
+%DIAGNOSTICRESTOLENUM - Enum of DiagnosticRestol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticRestolEnum()
+
+macro=StringToEnum('DiagnosticRestol');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticRiftPenaltyLockEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticRiftPenaltyLockEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticRiftPenaltyLockEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticRiftPenaltyLockEnum()
+%DIAGNOSTICRIFTPENALTYLOCKENUM - Enum of DiagnosticRiftPenaltyLock
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticRiftPenaltyLockEnum()
+
+macro=StringToEnum('DiagnosticRiftPenaltyLock');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticRiftPenaltyThresholdEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticRiftPenaltyThresholdEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticRiftPenaltyThresholdEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticRiftPenaltyThresholdEnum()
+%DIAGNOSTICRIFTPENALTYTHRESHOLDENUM - Enum of DiagnosticRiftPenaltyThreshold
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticRiftPenaltyThresholdEnum()
+
+macro=StringToEnum('DiagnosticRiftPenaltyThreshold');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticShelfDampeningEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticShelfDampeningEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticShelfDampeningEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticShelfDampeningEnum()
+%DIAGNOSTICSHELFDAMPENINGENUM - Enum of DiagnosticShelfDampening
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticShelfDampeningEnum()
+
+macro=StringToEnum('DiagnosticShelfDampening');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticSolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticSolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticSolutionEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticSolutionEnum()
+%DIAGNOSTICSOLUTIONENUM - Enum of DiagnosticSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticSolutionEnum()
+
+macro=StringToEnum('DiagnosticSolution');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticSpcvxEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticSpcvxEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticSpcvxEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticSpcvxEnum()
+%DIAGNOSTICSPCVXENUM - Enum of DiagnosticSpcvx
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticSpcvxEnum()
+
+macro=StringToEnum('DiagnosticSpcvx');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticSpcvyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticSpcvyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticSpcvyEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticSpcvyEnum()
+%DIAGNOSTICSPCVYENUM - Enum of DiagnosticSpcvy
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticSpcvyEnum()
+
+macro=StringToEnum('DiagnosticSpcvy');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticSpcvzEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticSpcvzEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticSpcvzEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticSpcvzEnum()
+%DIAGNOSTICSPCVZENUM - Enum of DiagnosticSpcvz
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticSpcvzEnum()
+
+macro=StringToEnum('DiagnosticSpcvz');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticStokesreconditioningEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticStokesreconditioningEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticStokesreconditioningEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticStokesreconditioningEnum()
+%DIAGNOSTICSTOKESRECONDITIONINGENUM - Enum of DiagnosticStokesreconditioning
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticStokesreconditioningEnum()
+
+macro=StringToEnum('DiagnosticStokesreconditioning');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticVertAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticVertAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticVertAnalysisEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticVertAnalysisEnum()
+%DIAGNOSTICVERTANALYSISENUM - Enum of DiagnosticVertAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticVertAnalysisEnum()
+
+macro=StringToEnum('DiagnosticVertAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticVertexPairingEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticVertexPairingEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticVertexPairingEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticVertexPairingEnum()
+%DIAGNOSTICVERTEXPAIRINGENUM - Enum of DiagnosticVertexPairing
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticVertexPairingEnum()
+
+macro=StringToEnum('DiagnosticVertexPairing');
Index: /issm/trunk-jpl-damage/src/m/enum/DiagnosticViscosityOvershootEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DiagnosticViscosityOvershootEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DiagnosticViscosityOvershootEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DiagnosticViscosityOvershootEnum()
+%DIAGNOSTICVISCOSITYOVERSHOOTENUM - Enum of DiagnosticViscosityOvershoot
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DiagnosticViscosityOvershootEnum()
+
+macro=StringToEnum('DiagnosticViscosityOvershoot');
Index: /issm/trunk-jpl-damage/src/m/enum/DofIndexingEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DofIndexingEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DofIndexingEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DofIndexingEnum()
+%DOFINDEXINGENUM - Enum of DofIndexing
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DofIndexingEnum()
+
+macro=StringToEnum('DofIndexing');
Index: /issm/trunk-jpl-damage/src/m/enum/DoubleElementResultEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DoubleElementResultEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DoubleElementResultEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DoubleElementResultEnum()
+%DOUBLEELEMENTRESULTENUM - Enum of DoubleElementResult
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DoubleElementResultEnum()
+
+macro=StringToEnum('DoubleElementResult');
Index: /issm/trunk-jpl-damage/src/m/enum/DoubleExternalResultEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DoubleExternalResultEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DoubleExternalResultEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DoubleExternalResultEnum()
+
+macro=StringToEnum('DoubleExternalResult');
Index: /issm/trunk-jpl-damage/src/m/enum/DoubleInputEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DoubleInputEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DoubleInputEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DoubleInputEnum()
+
+macro=StringToEnum('DoubleInput');
Index: /issm/trunk-jpl-damage/src/m/enum/DoubleMatArrayParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DoubleMatArrayParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DoubleMatArrayParamEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DoubleMatArrayParamEnum()
+
+macro=StringToEnum('DoubleMatArrayParam');
Index: /issm/trunk-jpl-damage/src/m/enum/DoubleMatExternalResultEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DoubleMatExternalResultEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DoubleMatExternalResultEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DoubleMatExternalResultEnum()
+
+macro=StringToEnum('DoubleMatExternalResult');
Index: /issm/trunk-jpl-damage/src/m/enum/DoubleMatParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DoubleMatParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DoubleMatParamEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DoubleMatParamEnum()
+
+macro=StringToEnum('DoubleMatParam');
Index: /issm/trunk-jpl-damage/src/m/enum/DoubleParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DoubleParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DoubleParamEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DoubleParamEnum()
+
+macro=StringToEnum('DoubleParam');
Index: /issm/trunk-jpl-damage/src/m/enum/DoubleVecExternalResultEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DoubleVecExternalResultEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DoubleVecExternalResultEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=DoubleVecExternalResultEnum()
+%DOUBLEVECEXTERNALRESULTENUM - Enum of DoubleVecExternalResult
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DoubleVecExternalResultEnum()
+
+macro=StringToEnum('DoubleVecExternalResult');
Index: /issm/trunk-jpl-damage/src/m/enum/DoubleVecParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DoubleVecParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DoubleVecParamEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DoubleVecParamEnum()
+
+macro=StringToEnum('DoubleVecParam');
Index: /issm/trunk-jpl-damage/src/m/enum/DragCoefficientAbsGradientEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/DragCoefficientAbsGradientEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/DragCoefficientAbsGradientEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=DragCoefficientAbsGradientEnum()
+
+macro=StringToEnum('DragCoefficientAbsGradient');
Index: /issm/trunk-jpl-damage/src/m/enum/ElementEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ElementEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ElementEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ElementEnum()
+
+macro=StringToEnum('Element');
Index: /issm/trunk-jpl-damage/src/m/enum/ElementResultEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ElementResultEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ElementResultEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=ElementResultEnum()
+%ELEMENTRESULTENUM - Enum of ElementResult
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ElementResultEnum()
+
+macro=StringToEnum('ElementResult');
Index: /issm/trunk-jpl-damage/src/m/enum/EnthalpyAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/EnthalpyAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/EnthalpyAnalysisEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=EnthalpyAnalysisEnum()
+
+macro=StringToEnum('EnthalpyAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/EnthalpyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/EnthalpyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/EnthalpyEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=EnthalpyEnum()
+
+macro=StringToEnum('Enthalpy');
Index: /issm/trunk-jpl-damage/src/m/enum/EnthalpyPicardEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/EnthalpyPicardEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/EnthalpyPicardEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=EnthalpyPicardEnum()
+
+macro=StringToEnum('EnthalpyPicard');
Index: /issm/trunk-jpl-damage/src/m/enum/EnthalpySolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/EnthalpySolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/EnthalpySolutionEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=EnthalpySolutionEnum()
+%ENTHALPYSOLUTIONENUM - Enum of EnthalpySolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=EnthalpySolutionEnum()
+
+macro=StringToEnum('EnthalpySolution');
Index: /issm/trunk-jpl-damage/src/m/enum/EnumToModelField.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/EnumToModelField.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/EnumToModelField.m	(revision 11330)
@@ -0,0 +1,28 @@
+function string=EnumToModelField(enum)
+%ENUMTOMODELFIELD - output string of model field associated to enum
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      string=EnumToModelField(enum)
+
+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 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
Index: /issm/trunk-jpl-damage/src/m/enum/ExtToIuEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ExtToIuEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ExtToIuEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=ExtToIuEnum()
+%EXTTOIUENUM - Enum of ExtToIu
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ExtToIuEnum()
+
+macro=StringToEnum('ExtToIu');
Index: /issm/trunk-jpl-damage/src/m/enum/ExternalResultEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ExternalResultEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ExternalResultEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ExternalResultEnum()
+
+macro=StringToEnum('ExternalResult');
Index: /issm/trunk-jpl-damage/src/m/enum/FileParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FileParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FileParamEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FileParamEnum()
+
+macro=StringToEnum('FileParam');
Index: /issm/trunk-jpl-damage/src/m/enum/FillEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FillEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FillEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FillEnum()
+
+macro=StringToEnum('Fill');
Index: /issm/trunk-jpl-damage/src/m/enum/FlaimAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FlaimAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FlaimAnalysisEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FlaimAnalysisEnum()
+
+macro=StringToEnum('FlaimAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/FlaimSolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FlaimSolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FlaimSolutionEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FlaimSolutionEnum()
+
+macro=StringToEnum('FlaimSolution');
Index: /issm/trunk-jpl-damage/src/m/enum/FlowequationBordermacayealEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FlowequationBordermacayealEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FlowequationBordermacayealEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=FlowequationBordermacayealEnum()
+%FLOWEQUATIONBORDERMACAYEALENUM - Enum of FlowequationBordermacayeal
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FlowequationBordermacayealEnum()
+
+macro=StringToEnum('FlowequationBordermacayeal');
Index: /issm/trunk-jpl-damage/src/m/enum/FlowequationBorderpattynEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FlowequationBorderpattynEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FlowequationBorderpattynEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=FlowequationBorderpattynEnum()
+%FLOWEQUATIONBORDERPATTYNENUM - Enum of FlowequationBorderpattyn
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FlowequationBorderpattynEnum()
+
+macro=StringToEnum('FlowequationBorderpattyn');
Index: /issm/trunk-jpl-damage/src/m/enum/FlowequationBorderstokesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FlowequationBorderstokesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FlowequationBorderstokesEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=FlowequationBorderstokesEnum()
+%FLOWEQUATIONBORDERSTOKESENUM - Enum of FlowequationBorderstokes
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FlowequationBorderstokesEnum()
+
+macro=StringToEnum('FlowequationBorderstokes');
Index: /issm/trunk-jpl-damage/src/m/enum/FlowequationElementEquationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FlowequationElementEquationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FlowequationElementEquationEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FlowequationElementEquationEnum()
+
+macro=StringToEnum('FlowequationElementEquation');
Index: /issm/trunk-jpl-damage/src/m/enum/FlowequationIshutterEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FlowequationIshutterEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FlowequationIshutterEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=FlowequationIshutterEnum()
+%FLOWEQUATIONISHUTTERENUM - Enum of FlowequationIshutter
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FlowequationIshutterEnum()
+
+macro=StringToEnum('FlowequationIshutter');
Index: /issm/trunk-jpl-damage/src/m/enum/FlowequationIsmacayealpattynEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FlowequationIsmacayealpattynEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FlowequationIsmacayealpattynEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsmacayealpattynEnum()
+%FLOWEQUATIONISMACAYEALPATTYNENUM - Enum of FlowequationIsmacayealpattyn
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FlowequationIsmacayealpattynEnum()
+
+macro=StringToEnum('FlowequationIsmacayealpattyn');
Index: /issm/trunk-jpl-damage/src/m/enum/FlowequationIsstokesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FlowequationIsstokesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FlowequationIsstokesEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsstokesEnum()
+%FLOWEQUATIONISSTOKESENUM - Enum of FlowequationIsstokes
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FlowequationIsstokesEnum()
+
+macro=StringToEnum('FlowequationIsstokes');
Index: /issm/trunk-jpl-damage/src/m/enum/FlowequationVertexEquationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FlowequationVertexEquationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FlowequationVertexEquationEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FlowequationVertexEquationEnum()
+
+macro=StringToEnum('FlowequationVertexEquation');
Index: /issm/trunk-jpl-damage/src/m/enum/FractionIncrementEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FractionIncrementEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FractionIncrementEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FractionIncrementEnum()
+
+macro=StringToEnum('FractionIncrement');
Index: /issm/trunk-jpl-damage/src/m/enum/FreeEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FreeEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FreeEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FreeEnum()
+
+macro=StringToEnum('Free');
Index: /issm/trunk-jpl-damage/src/m/enum/FrictionCoefficientEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FrictionCoefficientEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FrictionCoefficientEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FrictionCoefficientEnum()
+
+macro=StringToEnum('FrictionCoefficient');
Index: /issm/trunk-jpl-damage/src/m/enum/FrictionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FrictionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FrictionEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FrictionEnum()
+
+macro=StringToEnum('Friction');
Index: /issm/trunk-jpl-damage/src/m/enum/FrictionPEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FrictionPEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FrictionPEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FrictionPEnum()
+
+macro=StringToEnum('FrictionP');
Index: /issm/trunk-jpl-damage/src/m/enum/FrictionQEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FrictionQEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FrictionQEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FrictionQEnum()
+
+macro=StringToEnum('FrictionQ');
Index: /issm/trunk-jpl-damage/src/m/enum/FsetEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/FsetEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/FsetEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FsetEnum()
+
+macro=StringToEnum('Fset');
Index: /issm/trunk-jpl-damage/src/m/enum/GeometryHydrostaticRatioEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/GeometryHydrostaticRatioEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/GeometryHydrostaticRatioEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=GeometryHydrostaticRatioEnum()
+
+macro=StringToEnum('GeometryHydrostaticRatio');
Index: /issm/trunk-jpl-damage/src/m/enum/Gradient1Enum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/Gradient1Enum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/Gradient1Enum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=Gradient1Enum()
+
+macro=StringToEnum('Gradient1');
Index: /issm/trunk-jpl-damage/src/m/enum/Gradient2Enum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/Gradient2Enum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/Gradient2Enum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=Gradient2Enum()
+
+macro=StringToEnum('Gradient2');
Index: /issm/trunk-jpl-damage/src/m/enum/Gradient3Enum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/Gradient3Enum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/Gradient3Enum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=Gradient3Enum()
+
+macro=StringToEnum('Gradient3');
Index: /issm/trunk-jpl-damage/src/m/enum/GradientEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/GradientEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/GradientEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=GradientEnum()
+
+macro=StringToEnum('Gradient');
Index: /issm/trunk-jpl-damage/src/m/enum/GroundinglineMeltingRateEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/GroundinglineMeltingRateEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/GroundinglineMeltingRateEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=GroundinglineMeltingRateEnum()
+%GROUNDINGLINEMELTINGRATEENUM - Enum of GroundinglineMeltingRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=GroundinglineMeltingRateEnum()
+
+macro=StringToEnum('GroundinglineMeltingRate');
Index: /issm/trunk-jpl-damage/src/m/enum/GroundinglineMigrationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/GroundinglineMigrationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/GroundinglineMigrationEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=GroundinglineMigrationEnum()
+
+macro=StringToEnum('GroundinglineMigration');
Index: /issm/trunk-jpl-damage/src/m/enum/GsetEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/GsetEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/GsetEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=GsetEnum()
+
+macro=StringToEnum('Gset');
Index: /issm/trunk-jpl-damage/src/m/enum/HookEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/HookEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/HookEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=HookEnum()
+%HOOKENUM - Enum of Hook
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=HookEnum()
+
+macro=StringToEnum('Hook');
Index: /issm/trunk-jpl-damage/src/m/enum/HutterApproximationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/HutterApproximationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/HutterApproximationEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=HutterApproximationEnum()
+%HUTTERAPPROXIMATIONENUM - Enum of HutterApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=HutterApproximationEnum()
+
+macro=StringToEnum('HutterApproximation');
Index: /issm/trunk-jpl-damage/src/m/enum/HydrologyAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/HydrologyAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/HydrologyAnalysisEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=HydrologyAnalysisEnum()
+%HYDROLOGYANALYSISENUM - Enum of HydrologyAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=HydrologyAnalysisEnum()
+
+macro=StringToEnum('HydrologyAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/HydrologyCREnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/HydrologyCREnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/HydrologyCREnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=HydrologyCREnum()
+%HYDROLOGYCRENUM - Enum of HydrologyCR
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=HydrologyCREnum()
+
+macro=StringToEnum('HydrologyCR');
Index: /issm/trunk-jpl-damage/src/m/enum/HydrologyKnEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/HydrologyKnEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/HydrologyKnEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=HydrologyKnEnum()
+%HYDROLOGYKNENUM - Enum of HydrologyKn
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=HydrologyKnEnum()
+
+macro=StringToEnum('HydrologyKn');
Index: /issm/trunk-jpl-damage/src/m/enum/HydrologyNEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/HydrologyNEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/HydrologyNEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=HydrologyNEnum()
+%HYDROLOGYNENUM - Enum of HydrologyN
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=HydrologyNEnum()
+
+macro=StringToEnum('HydrologyN');
Index: /issm/trunk-jpl-damage/src/m/enum/HydrologyPEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/HydrologyPEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/HydrologyPEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=HydrologyPEnum()
+%HYDROLOGYPENUM - Enum of HydrologyP
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=HydrologyPEnum()
+
+macro=StringToEnum('HydrologyP');
Index: /issm/trunk-jpl-damage/src/m/enum/HydrologyQEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/HydrologyQEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/HydrologyQEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=HydrologyQEnum()
+%HYDROLOGYQENUM - Enum of HydrologyQ
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=HydrologyQEnum()
+
+macro=StringToEnum('HydrologyQ');
Index: /issm/trunk-jpl-damage/src/m/enum/HydrologySolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/HydrologySolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/HydrologySolutionEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=HydrologySolutionEnum()
+
+macro=StringToEnum('HydrologySolution');
Index: /issm/trunk-jpl-damage/src/m/enum/HydrologySpcwatercolumnEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/HydrologySpcwatercolumnEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/HydrologySpcwatercolumnEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=HydrologySpcwatercolumnEnum()
+%HYDROLOGYSPCWATERCOLUMNENUM - Enum of HydrologySpcwatercolumn
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=HydrologySpcwatercolumnEnum()
+
+macro=StringToEnum('HydrologySpcwatercolumn');
Index: /issm/trunk-jpl-damage/src/m/enum/HydrologyStabilizationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/HydrologyStabilizationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/HydrologyStabilizationEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=HydrologyStabilizationEnum()
+%HYDROLOGYSTABILIZATIONENUM - Enum of HydrologyStabilization
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=HydrologyStabilizationEnum()
+
+macro=StringToEnum('HydrologyStabilization');
Index: /issm/trunk-jpl-damage/src/m/enum/HydrologyWaterVxEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/HydrologyWaterVxEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/HydrologyWaterVxEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=HydrologyWaterVxEnum()
+
+macro=StringToEnum('HydrologyWaterVx');
Index: /issm/trunk-jpl-damage/src/m/enum/HydrologyWaterVyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/HydrologyWaterVyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/HydrologyWaterVyEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=HydrologyWaterVyEnum()
+
+macro=StringToEnum('HydrologyWaterVy');
Index: /issm/trunk-jpl-damage/src/m/enum/IceEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/IceEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/IceEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=IceEnum()
+
+macro=StringToEnum('Ice');
Index: /issm/trunk-jpl-damage/src/m/enum/IceVolumeEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/IceVolumeEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/IceVolumeEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=IceVolumeEnum()
+
+macro=StringToEnum('IceVolume');
Index: /issm/trunk-jpl-damage/src/m/enum/IcefrontEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/IcefrontEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/IcefrontEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=IcefrontEnum()
+%ICEFRONTENUM - Enum of Icefront
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=IcefrontEnum()
+
+macro=StringToEnum('Icefront');
Index: /issm/trunk-jpl-damage/src/m/enum/IncrementalEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/IncrementalEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/IncrementalEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=IncrementalEnum()
+
+macro=StringToEnum('Incremental');
Index: /issm/trunk-jpl-damage/src/m/enum/IndexEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/IndexEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/IndexEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=IndexEnum()
+
+macro=StringToEnum('Index');
Index: /issm/trunk-jpl-damage/src/m/enum/IndexedEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/IndexedEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/IndexedEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=IndexedEnum()
+
+macro=StringToEnum('Indexed');
Index: /issm/trunk-jpl-damage/src/m/enum/InputEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InputEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InputEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InputEnum()
+
+macro=StringToEnum('Input');
Index: /issm/trunk-jpl-damage/src/m/enum/IntExternalResultEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/IntExternalResultEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/IntExternalResultEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=IntExternalResultEnum()
+
+macro=StringToEnum('IntExternalResult');
Index: /issm/trunk-jpl-damage/src/m/enum/IntInputEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/IntInputEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/IntInputEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=IntInputEnum()
+
+macro=StringToEnum('IntInput');
Index: /issm/trunk-jpl-damage/src/m/enum/IntMatParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/IntMatParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/IntMatParamEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=IntMatParamEnum()
+
+macro=StringToEnum('IntMatParam');
Index: /issm/trunk-jpl-damage/src/m/enum/IntParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/IntParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/IntParamEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=IntParamEnum()
+
+macro=StringToEnum('IntParam');
Index: /issm/trunk-jpl-damage/src/m/enum/IntVecParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/IntVecParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/IntVecParamEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=IntVecParamEnum()
+
+macro=StringToEnum('IntVecParam');
Index: /issm/trunk-jpl-damage/src/m/enum/InternalEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InternalEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InternalEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InternalEnum()
+
+macro=StringToEnum('Internal');
Index: /issm/trunk-jpl-damage/src/m/enum/IntersectEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/IntersectEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/IntersectEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=IntersectEnum()
+
+macro=StringToEnum('Intersect');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionControlParametersEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionControlParametersEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionControlParametersEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionControlParametersEnum()
+
+macro=StringToEnum('InversionControlParameters');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionCostFunctionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionCostFunctionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionCostFunctionEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=InversionCostFunctionEnum()
+%INVERSIONCOSTFUNCTIONENUM - Enum of InversionCostFunction
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionCostFunctionEnum()
+
+macro=StringToEnum('InversionCostFunction');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionCostFunctionThresholdEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionCostFunctionThresholdEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionCostFunctionThresholdEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionCostFunctionThresholdEnum()
+
+macro=StringToEnum('InversionCostFunctionThreshold');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionCostFunctionsCoefficientsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionCostFunctionsCoefficientsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionCostFunctionsCoefficientsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionCostFunctionsCoefficientsEnum()
+
+macro=StringToEnum('InversionCostFunctionsCoefficients');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionCostFunctionsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionCostFunctionsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionCostFunctionsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionCostFunctionsEnum()
+
+macro=StringToEnum('InversionCostFunctions');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionGradientOnlyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionGradientOnlyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionGradientOnlyEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=InversionGradientOnlyEnum()
+%INVERSIONGRADIENTONLYENUM - Enum of InversionGradientOnly
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionGradientOnlyEnum()
+
+macro=StringToEnum('InversionGradientOnly');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionGradientScalingEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionGradientScalingEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionGradientScalingEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionGradientScalingEnum()
+
+macro=StringToEnum('InversionGradientScaling');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionIscontrolEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionIscontrolEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionIscontrolEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionIscontrolEnum()
+
+macro=StringToEnum('InversionIscontrol');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionMaxParametersEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionMaxParametersEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionMaxParametersEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionMaxParametersEnum()
+
+macro=StringToEnum('InversionMaxParameters');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionMaxiterPerStepEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionMaxiterPerStepEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionMaxiterPerStepEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionMaxiterPerStepEnum()
+
+macro=StringToEnum('InversionMaxiterPerStep');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionMinParametersEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionMinParametersEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionMinParametersEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionMinParametersEnum()
+
+macro=StringToEnum('InversionMinParameters');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionNstepsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionNstepsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionNstepsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionNstepsEnum()
+
+macro=StringToEnum('InversionNsteps');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionNumControlParametersEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionNumControlParametersEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionNumControlParametersEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionNumControlParametersEnum()
+
+macro=StringToEnum('InversionNumControlParameters');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionNumCostFunctionsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionNumCostFunctionsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionNumCostFunctionsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionNumCostFunctionsEnum()
+
+macro=StringToEnum('InversionNumCostFunctions');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionStepThresholdEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionStepThresholdEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionStepThresholdEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionStepThresholdEnum()
+
+macro=StringToEnum('InversionStepThreshold');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionTaoEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionTaoEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionTaoEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=InversionTaoEnum()
+%INVERSIONTAOENUM - Enum of InversionTao
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionTaoEnum()
+
+macro=StringToEnum('InversionTao');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionThicknessObsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionThicknessObsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionThicknessObsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionThicknessObsEnum()
+
+macro=StringToEnum('InversionThicknessObs');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionVelObsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionVelObsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionVelObsEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=InversionVelObsEnum()
+%INVERSIONVELOBSENUM - Enum of InversionVelObs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionVelObsEnum()
+
+macro=StringToEnum('InversionVelObs');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionVxObsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionVxObsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionVxObsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionVxObsEnum()
+
+macro=StringToEnum('InversionVxObs');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionVyObsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionVyObsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionVyObsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionVyObsEnum()
+
+macro=StringToEnum('InversionVyObs');
Index: /issm/trunk-jpl-damage/src/m/enum/InversionVzObsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/InversionVzObsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/InversionVzObsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=InversionVzObsEnum()
+
+macro=StringToEnum('InversionVzObs');
Index: /issm/trunk-jpl-damage/src/m/enum/IuToExtEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/IuToExtEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/IuToExtEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=IuToExtEnum()
+%IUTOEXTENUM - Enum of IuToExt
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=IuToExtEnum()
+
+macro=StringToEnum('IuToExt');
Index: /issm/trunk-jpl-damage/src/m/enum/JEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/JEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/JEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=JEnum()
+
+macro=StringToEnum('J');
Index: /issm/trunk-jpl-damage/src/m/enum/LoadsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/LoadsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/LoadsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=LoadsEnum()
+
+macro=StringToEnum('Loads');
Index: /issm/trunk-jpl-damage/src/m/enum/MacAyeal2dIceFrontEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MacAyeal2dIceFrontEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MacAyeal2dIceFrontEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MacAyeal2dIceFrontEnum()
+%MACAYEAL2DICEFRONTENUM - Enum of MacAyeal2dIceFront
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MacAyeal2dIceFrontEnum()
+
+macro=StringToEnum('MacAyeal2dIceFront');
Index: /issm/trunk-jpl-damage/src/m/enum/MacAyeal3dIceFrontEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MacAyeal3dIceFrontEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MacAyeal3dIceFrontEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MacAyeal3dIceFrontEnum()
+%MACAYEAL3DICEFRONTENUM - Enum of MacAyeal3dIceFront
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MacAyeal3dIceFrontEnum()
+
+macro=StringToEnum('MacAyeal3dIceFront');
Index: /issm/trunk-jpl-damage/src/m/enum/MacAyealApproximationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MacAyealApproximationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MacAyealApproximationEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MacAyealApproximationEnum()
+%MACAYEALAPPROXIMATIONENUM - Enum of MacAyealApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MacAyealApproximationEnum()
+
+macro=StringToEnum('MacAyealApproximation');
Index: /issm/trunk-jpl-damage/src/m/enum/MacAyealPattynApproximationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MacAyealPattynApproximationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MacAyealPattynApproximationEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MacAyealPattynApproximationEnum()
+%MACAYEALPATTYNAPPROXIMATIONENUM - Enum of MacAyealPattynApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MacAyealPattynApproximationEnum()
+
+macro=StringToEnum('MacAyealPattynApproximation');
Index: /issm/trunk-jpl-damage/src/m/enum/MacAyealStokesApproximationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MacAyealStokesApproximationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MacAyealStokesApproximationEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MacAyealStokesApproximationEnum()
+%MACAYEALSTOKESAPPROXIMATIONENUM - Enum of MacAyealStokesApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MacAyealStokesApproximationEnum()
+
+macro=StringToEnum('MacAyealStokesApproximation');
Index: /issm/trunk-jpl-damage/src/m/enum/MaskElementonfloatingiceEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaskElementonfloatingiceEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaskElementonfloatingiceEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MaskElementonfloatingiceEnum()
+%MASKELEMENTONFLOATINGICEENUM - Enum of MaskElementonfloatingice
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaskElementonfloatingiceEnum()
+
+macro=StringToEnum('MaskElementonfloatingice');
Index: /issm/trunk-jpl-damage/src/m/enum/MaskElementongroundediceEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaskElementongroundediceEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaskElementongroundediceEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MaskElementongroundediceEnum()
+%MASKELEMENTONGROUNDEDICEENUM - Enum of MaskElementongroundedice
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaskElementongroundediceEnum()
+
+macro=StringToEnum('MaskElementongroundedice');
Index: /issm/trunk-jpl-damage/src/m/enum/MaskElementonwaterEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaskElementonwaterEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaskElementonwaterEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MaskElementonwaterEnum()
+%MASKELEMENTONWATERENUM - Enum of MaskElementonwater
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaskElementonwaterEnum()
+
+macro=StringToEnum('MaskElementonwater');
Index: /issm/trunk-jpl-damage/src/m/enum/MaskVertexonfloatingiceEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaskVertexonfloatingiceEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaskVertexonfloatingiceEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MaskVertexonfloatingiceEnum()
+%MASKVERTEXONFLOATINGICEENUM - Enum of MaskVertexonfloatingice
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaskVertexonfloatingiceEnum()
+
+macro=StringToEnum('MaskVertexonfloatingice');
Index: /issm/trunk-jpl-damage/src/m/enum/MaskVertexongroundediceEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaskVertexongroundediceEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaskVertexongroundediceEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MaskVertexongroundediceEnum()
+%MASKVERTEXONGROUNDEDICEENUM - Enum of MaskVertexongroundedice
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaskVertexongroundediceEnum()
+
+macro=StringToEnum('MaskVertexongroundedice');
Index: /issm/trunk-jpl-damage/src/m/enum/MaskVertexonwaterEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaskVertexonwaterEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaskVertexonwaterEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MaskVertexonwaterEnum()
+%MASKVERTEXONWATERENUM - Enum of MaskVertexonwater
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaskVertexonwaterEnum()
+
+macro=StringToEnum('MaskVertexonwater');
Index: /issm/trunk-jpl-damage/src/m/enum/MassFluxEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MassFluxEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MassFluxEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MassFluxEnum()
+
+macro=StringToEnum('MassFlux');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsBetaEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsBetaEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsBetaEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsBetaEnum()
+
+macro=StringToEnum('MaterialsBeta');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsEnum()
+
+macro=StringToEnum('Materials');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsHeatcapacityEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsHeatcapacityEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsHeatcapacityEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsHeatcapacityEnum()
+
+macro=StringToEnum('MaterialsHeatcapacity');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsLatentheatEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsLatentheatEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsLatentheatEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsLatentheatEnum()
+
+macro=StringToEnum('MaterialsLatentheat');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsMeltingpointEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsMeltingpointEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsMeltingpointEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsMeltingpointEnum()
+
+macro=StringToEnum('MaterialsMeltingpoint');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsMixedLayerCapacityEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsMixedLayerCapacityEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsMixedLayerCapacityEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsMixedLayerCapacityEnum()
+
+macro=StringToEnum('MaterialsMixedLayerCapacity');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsMuWaterEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsMuWaterEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsMuWaterEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsMuWaterEnum()
+
+macro=StringToEnum('MaterialsMuWater');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsRheologyBEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsRheologyBEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsRheologyBEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsRheologyBEnum()
+
+macro=StringToEnum('MaterialsRheologyB');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsRheologyBbarEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsRheologyBbarEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsRheologyBbarEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsRheologyBbarEnum()
+
+macro=StringToEnum('MaterialsRheologyBbar');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsRheologyLawEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsRheologyLawEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsRheologyLawEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsRheologyLawEnum()
+
+macro=StringToEnum('MaterialsRheologyLaw');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsRheologyNEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsRheologyNEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsRheologyNEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsRheologyNEnum()
+
+macro=StringToEnum('MaterialsRheologyN');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsRhoIceEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsRhoIceEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsRhoIceEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsRhoIceEnum()
+
+macro=StringToEnum('MaterialsRhoIce');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsRhoWaterEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsRhoWaterEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsRhoWaterEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MaterialsRhoWaterEnum()
+%MATERIALSRHOWATERENUM - Enum of MaterialsRhoWater
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsRhoWaterEnum()
+
+macro=StringToEnum('MaterialsRhoWater');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsThermalExchangeVelocityEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsThermalExchangeVelocityEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsThermalExchangeVelocityEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsThermalExchangeVelocityEnum()
+
+macro=StringToEnum('MaterialsThermalExchangeVelocity');
Index: /issm/trunk-jpl-damage/src/m/enum/MaterialsThermalconductivityEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaterialsThermalconductivityEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaterialsThermalconductivityEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaterialsThermalconductivityEnum()
+
+macro=StringToEnum('MaterialsThermalconductivity');
Index: /issm/trunk-jpl-damage/src/m/enum/MaticeEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaticeEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaticeEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaticeEnum()
+
+macro=StringToEnum('Matice');
Index: /issm/trunk-jpl-damage/src/m/enum/MatparEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MatparEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MatparEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MatparEnum()
+
+macro=StringToEnum('Matpar');
Index: /issm/trunk-jpl-damage/src/m/enum/MaxAbsVxEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaxAbsVxEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaxAbsVxEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaxAbsVxEnum()
+
+macro=StringToEnum('MaxAbsVx');
Index: /issm/trunk-jpl-damage/src/m/enum/MaxAbsVyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaxAbsVyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaxAbsVyEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaxAbsVyEnum()
+
+macro=StringToEnum('MaxAbsVy');
Index: /issm/trunk-jpl-damage/src/m/enum/MaxAbsVzEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaxAbsVzEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaxAbsVzEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaxAbsVzEnum()
+
+macro=StringToEnum('MaxAbsVz');
Index: /issm/trunk-jpl-damage/src/m/enum/MaxPenetrationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaxPenetrationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaxPenetrationEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MaxPenetrationEnum()
+%MAXPENETRATIONENUM - Enum of MaxPenetration
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaxPenetrationEnum()
+
+macro=StringToEnum('MaxPenetration');
Index: /issm/trunk-jpl-damage/src/m/enum/MaxVelEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaxVelEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaxVelEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaxVelEnum()
+
+macro=StringToEnum('MaxVel');
Index: /issm/trunk-jpl-damage/src/m/enum/MaxVxEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaxVxEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaxVxEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaxVxEnum()
+
+macro=StringToEnum('MaxVx');
Index: /issm/trunk-jpl-damage/src/m/enum/MaxVyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaxVyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaxVyEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaxVyEnum()
+
+macro=StringToEnum('MaxVy');
Index: /issm/trunk-jpl-damage/src/m/enum/MaxVzEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MaxVzEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MaxVzEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MaxVzEnum()
+
+macro=StringToEnum('MaxVz');
Index: /issm/trunk-jpl-damage/src/m/enum/MelangeEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MelangeEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MelangeEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MelangeEnum()
+
+macro=StringToEnum('Melange');
Index: /issm/trunk-jpl-damage/src/m/enum/MeltingAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeltingAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeltingAnalysisEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeltingAnalysisEnum()
+
+macro=StringToEnum('MeltingAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/MeltingOffsetEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeltingOffsetEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeltingOffsetEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeltingOffsetEnum()
+
+macro=StringToEnum('MeltingOffset');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshAverageVertexConnectivityEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshAverageVertexConnectivityEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshAverageVertexConnectivityEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshAverageVertexConnectivityEnum()
+
+macro=StringToEnum('MeshAverageVertexConnectivity');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshDimensionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshDimensionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshDimensionEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MeshDimensionEnum()
+%MESHDIMENSIONENUM - Enum of MeshDimension
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshDimensionEnum()
+
+macro=StringToEnum('MeshDimension');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshEdgesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshEdgesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshEdgesEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MeshEdgesEnum()
+%MESHEDGESENUM - Enum of MeshEdges
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshEdgesEnum()
+
+macro=StringToEnum('MeshEdges');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshElementconnectivityEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshElementconnectivityEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshElementconnectivityEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MeshElementconnectivityEnum()
+%MESHELEMENTCONNECTIVITYENUM - Enum of MeshElementconnectivity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshElementconnectivityEnum()
+
+macro=StringToEnum('MeshElementconnectivity');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshElementonbedEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshElementonbedEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshElementonbedEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MeshElementonbedEnum()
+%MESHELEMENTONBEDENUM - Enum of MeshElementonbed
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshElementonbedEnum()
+
+macro=StringToEnum('MeshElementonbed');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshElementonsurfaceEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshElementonsurfaceEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshElementonsurfaceEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MeshElementonsurfaceEnum()
+%MESHELEMENTONSURFACEENUM - Enum of MeshElementonsurface
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshElementonsurfaceEnum()
+
+macro=StringToEnum('MeshElementonsurface');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshElements2dEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshElements2dEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshElements2dEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshElements2dEnum()
+
+macro=StringToEnum('MeshElements2d');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshElementsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshElementsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshElementsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshElementsEnum()
+
+macro=StringToEnum('MeshElements');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshLowerelementsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshLowerelementsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshLowerelementsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshLowerelementsEnum()
+
+macro=StringToEnum('MeshLowerelements');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshNumberofedgesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshNumberofedgesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshNumberofedgesEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MeshNumberofedgesEnum()
+%MESHNUMBEROFEDGESENUM - Enum of MeshNumberofedges
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshNumberofedgesEnum()
+
+macro=StringToEnum('MeshNumberofedges');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshNumberofelements2dEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshNumberofelements2dEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshNumberofelements2dEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshNumberofelements2dEnum()
+
+macro=StringToEnum('MeshNumberofelements2d');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshNumberofelementsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshNumberofelementsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshNumberofelementsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshNumberofelementsEnum()
+
+macro=StringToEnum('MeshNumberofelements');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshNumberoflayersEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshNumberoflayersEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshNumberoflayersEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshNumberoflayersEnum()
+
+macro=StringToEnum('MeshNumberoflayers');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshNumberofvertices2dEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshNumberofvertices2dEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshNumberofvertices2dEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshNumberofvertices2dEnum()
+
+macro=StringToEnum('MeshNumberofvertices2d');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshNumberofverticesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshNumberofverticesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshNumberofverticesEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshNumberofverticesEnum()
+
+macro=StringToEnum('MeshNumberofvertices');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshUpperelementsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshUpperelementsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshUpperelementsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshUpperelementsEnum()
+
+macro=StringToEnum('MeshUpperelements');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshVertexonbedEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshVertexonbedEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshVertexonbedEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=MeshVertexonbedEnum()
+%MESHVERTEXONBEDENUM - Enum of MeshVertexonbed
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshVertexonbedEnum()
+
+macro=StringToEnum('MeshVertexonbed');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshVertexonsurfaceEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshVertexonsurfaceEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshVertexonsurfaceEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshVertexonsurfaceEnum()
+
+macro=StringToEnum('MeshVertexonsurface');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshXEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshXEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshXEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshXEnum()
+
+macro=StringToEnum('MeshX');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshYEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshYEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshYEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshYEnum()
+
+macro=StringToEnum('MeshY');
Index: /issm/trunk-jpl-damage/src/m/enum/MeshZEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MeshZEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MeshZEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MeshZEnum()
+
+macro=StringToEnum('MeshZ');
Index: /issm/trunk-jpl-damage/src/m/enum/MinVelEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MinVelEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MinVelEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MinVelEnum()
+
+macro=StringToEnum('MinVel');
Index: /issm/trunk-jpl-damage/src/m/enum/MinVxEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MinVxEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MinVxEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MinVxEnum()
+
+macro=StringToEnum('MinVx');
Index: /issm/trunk-jpl-damage/src/m/enum/MinVyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MinVyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MinVyEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MinVyEnum()
+
+macro=StringToEnum('MinVy');
Index: /issm/trunk-jpl-damage/src/m/enum/MinVzEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MinVzEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MinVzEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MinVzEnum()
+
+macro=StringToEnum('MinVz');
Index: /issm/trunk-jpl-damage/src/m/enum/MiscellaneousNameEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MiscellaneousNameEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MiscellaneousNameEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MiscellaneousNameEnum()
+
+macro=StringToEnum('MiscellaneousName');
Index: /issm/trunk-jpl-damage/src/m/enum/MisfitEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/MisfitEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/MisfitEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=MisfitEnum()
+
+macro=StringToEnum('Misfit');
Index: /issm/trunk-jpl-damage/src/m/enum/NearestInterpEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/NearestInterpEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/NearestInterpEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=NearestInterpEnum()
+
+macro=StringToEnum('NearestInterp');
Index: /issm/trunk-jpl-damage/src/m/enum/NodalEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/NodalEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/NodalEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=NodalEnum()
+
+macro=StringToEnum('Nodal');
Index: /issm/trunk-jpl-damage/src/m/enum/NodeEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/NodeEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/NodeEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=NodeEnum()
+
+macro=StringToEnum('Node');
Index: /issm/trunk-jpl-damage/src/m/enum/NodesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/NodesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/NodesEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=NodesEnum()
+
+macro=StringToEnum('Nodes');
Index: /issm/trunk-jpl-damage/src/m/enum/NoneAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/NoneAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/NoneAnalysisEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=NoneAnalysisEnum()
+%NONEANALYSISENUM - Enum of NoneAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=NoneAnalysisEnum()
+
+macro=StringToEnum('NoneAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/NoneApproximationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/NoneApproximationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/NoneApproximationEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=NoneApproximationEnum()
+
+macro=StringToEnum('NoneApproximation');
Index: /issm/trunk-jpl-damage/src/m/enum/NoneEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/NoneEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/NoneEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=NoneEnum()
+
+macro=StringToEnum('None');
Index: /issm/trunk-jpl-damage/src/m/enum/NumberNodeToElementConnectivityEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/NumberNodeToElementConnectivityEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/NumberNodeToElementConnectivityEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=NumberNodeToElementConnectivityEnum()
+%NUMBERNODETOELEMENTCONNECTIVITYENUM - Enum of NumberNodeToElementConnectivity
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=NumberNodeToElementConnectivityEnum()
+
+macro=StringToEnum('NumberNodeToElementConnectivity');
Index: /issm/trunk-jpl-damage/src/m/enum/NumericalfluxEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/NumericalfluxEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/NumericalfluxEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=NumericalfluxEnum()
+
+macro=StringToEnum('Numericalflux');
Index: /issm/trunk-jpl-damage/src/m/enum/OldGradientEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/OldGradientEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/OldGradientEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=OldGradientEnum()
+
+macro=StringToEnum('OldGradient');
Index: /issm/trunk-jpl-damage/src/m/enum/OpenEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/OpenEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/OpenEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=OpenEnum()
+
+macro=StringToEnum('Open');
Index: /issm/trunk-jpl-damage/src/m/enum/OptionCellEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/OptionCellEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/OptionCellEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=OptionCellEnum()
+
+macro=StringToEnum('OptionCell');
Index: /issm/trunk-jpl-damage/src/m/enum/OptionCharEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/OptionCharEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/OptionCharEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=OptionCharEnum()
+%OPTIONCHARENUM - Enum of OptionChar
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=OptionCharEnum()
+
+macro=StringToEnum('OptionChar');
Index: /issm/trunk-jpl-damage/src/m/enum/OptionDoubleEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/OptionDoubleEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/OptionDoubleEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=OptionDoubleEnum()
+%OPTIONDOUBLEENUM - Enum of OptionDouble
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=OptionDoubleEnum()
+
+macro=StringToEnum('OptionDouble');
Index: /issm/trunk-jpl-damage/src/m/enum/OptionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/OptionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/OptionEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=OptionEnum()
+
+macro=StringToEnum('Option');
Index: /issm/trunk-jpl-damage/src/m/enum/OptionLogicalEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/OptionLogicalEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/OptionLogicalEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=OptionLogicalEnum()
+%OPTIONLOGICALENUM - Enum of OptionLogical
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=OptionLogicalEnum()
+
+macro=StringToEnum('OptionLogical');
Index: /issm/trunk-jpl-damage/src/m/enum/OptionStructEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/OptionStructEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/OptionStructEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=OptionStructEnum()
+
+macro=StringToEnum('OptionStruct');
Index: /issm/trunk-jpl-damage/src/m/enum/OutputFilePointerEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/OutputFilePointerEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/OutputFilePointerEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=OutputFilePointerEnum()
+
+macro=StringToEnum('OutputFilePointer');
Index: /issm/trunk-jpl-damage/src/m/enum/OutputfilenameEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/OutputfilenameEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/OutputfilenameEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=OutputfilenameEnum()
+
+macro=StringToEnum('Outputfilename');
Index: /issm/trunk-jpl-damage/src/m/enum/P0Enum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/P0Enum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/P0Enum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=P0Enum()
+
+macro=StringToEnum('P0');
Index: /issm/trunk-jpl-damage/src/m/enum/P1DGEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/P1DGEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/P1DGEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=P1DGEnum()
+
+macro=StringToEnum('P1DG');
Index: /issm/trunk-jpl-damage/src/m/enum/P1Enum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/P1Enum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/P1Enum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=P1Enum()
+
+macro=StringToEnum('P1');
Index: /issm/trunk-jpl-damage/src/m/enum/ParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ParamEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ParamEnum()
+
+macro=StringToEnum('Param');
Index: /issm/trunk-jpl-damage/src/m/enum/ParametersEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ParametersEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ParametersEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ParametersEnum()
+
+macro=StringToEnum('Parameters');
Index: /issm/trunk-jpl-damage/src/m/enum/PatchEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PatchEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PatchEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PatchEnum()
+%PATCHENUM - Enum of Patch
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PatchEnum()
+
+macro=StringToEnum('Patch');
Index: /issm/trunk-jpl-damage/src/m/enum/PatchNodesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PatchNodesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PatchNodesEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PatchNodesEnum()
+%PATCHNODESENUM - Enum of PatchNodes
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PatchNodesEnum()
+
+macro=StringToEnum('PatchNodes');
Index: /issm/trunk-jpl-damage/src/m/enum/PatchVerticesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PatchVerticesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PatchVerticesEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PatchVerticesEnum()
+%PATCHVERTICESENUM - Enum of PatchVertices
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PatchVerticesEnum()
+
+macro=StringToEnum('PatchVertices');
Index: /issm/trunk-jpl-damage/src/m/enum/PatersonEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PatersonEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PatersonEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PatersonEnum()
+
+macro=StringToEnum('Paterson');
Index: /issm/trunk-jpl-damage/src/m/enum/PattynApproximationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PattynApproximationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PattynApproximationEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PattynApproximationEnum()
+%PATTYNAPPROXIMATIONENUM - Enum of PattynApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PattynApproximationEnum()
+
+macro=StringToEnum('PattynApproximation');
Index: /issm/trunk-jpl-damage/src/m/enum/PattynIceFrontEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PattynIceFrontEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PattynIceFrontEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PattynIceFrontEnum()
+%PATTYNICEFRONTENUM - Enum of PattynIceFront
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PattynIceFrontEnum()
+
+macro=StringToEnum('PattynIceFront');
Index: /issm/trunk-jpl-damage/src/m/enum/PattynStokesApproximationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PattynStokesApproximationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PattynStokesApproximationEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PattynStokesApproximationEnum()
+%PATTYNSTOKESAPPROXIMATIONENUM - Enum of PattynStokesApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PattynStokesApproximationEnum()
+
+macro=StringToEnum('PattynStokesApproximation');
Index: /issm/trunk-jpl-damage/src/m/enum/PengridEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PengridEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PengridEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PengridEnum()
+
+macro=StringToEnum('Pengrid');
Index: /issm/trunk-jpl-damage/src/m/enum/PenpairEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PenpairEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PenpairEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PenpairEnum()
+
+macro=StringToEnum('Penpair');
Index: /issm/trunk-jpl-damage/src/m/enum/PentaEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PentaEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PentaEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PentaEnum()
+
+macro=StringToEnum('Penta');
Index: /issm/trunk-jpl-damage/src/m/enum/PentaVertexElementResultEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PentaVertexElementResultEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PentaVertexElementResultEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PentaVertexElementResultEnum()
+%PENTAVERTEXELEMENTRESULTENUM - Enum of PentaVertexElementResult
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PentaVertexElementResultEnum()
+
+macro=StringToEnum('PentaVertexElementResult');
Index: /issm/trunk-jpl-damage/src/m/enum/PentaVertexInputEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PentaVertexInputEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PentaVertexInputEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PentaVertexInputEnum()
+%PENTAVERTEXINPUTENUM - Enum of PentaVertexInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PentaVertexInputEnum()
+
+macro=StringToEnum('PentaVertexInput');
Index: /issm/trunk-jpl-damage/src/m/enum/PetscMatParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PetscMatParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PetscMatParamEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PetscMatParamEnum()
+%PETSCMATPARAMENUM - Enum of PetscMatParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PetscMatParamEnum()
+
+macro=StringToEnum('PetscMatParam');
Index: /issm/trunk-jpl-damage/src/m/enum/PetscOptionsAnalysesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PetscOptionsAnalysesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PetscOptionsAnalysesEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PetscOptionsAnalysesEnum()
+%PETSCOPTIONSANALYSESENUM - Enum of PetscOptionsAnalyses
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PetscOptionsAnalysesEnum()
+
+macro=StringToEnum('PetscOptionsAnalyses');
Index: /issm/trunk-jpl-damage/src/m/enum/PetscOptionsStringsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PetscOptionsStringsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PetscOptionsStringsEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PetscOptionsStringsEnum()
+%PETSCOPTIONSSTRINGSENUM - Enum of PetscOptionsStrings
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PetscOptionsStringsEnum()
+
+macro=StringToEnum('PetscOptionsStrings');
Index: /issm/trunk-jpl-damage/src/m/enum/PetscVecExternalResultEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PetscVecExternalResultEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PetscVecExternalResultEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PetscVecExternalResultEnum()
+%PETSCVECEXTERNALRESULTENUM - Enum of PetscVecExternalResult
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PetscVecExternalResultEnum()
+
+macro=StringToEnum('PetscVecExternalResult');
Index: /issm/trunk-jpl-damage/src/m/enum/PetscVecParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PetscVecParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PetscVecParamEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PetscVecParamEnum()
+%PETSCVECPARAMENUM - Enum of PetscVecParam
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PetscVecParamEnum()
+
+macro=StringToEnum('PetscVecParam');
Index: /issm/trunk-jpl-damage/src/m/enum/PressureEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PressureEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PressureEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PressureEnum()
+
+macro=StringToEnum('Pressure');
Index: /issm/trunk-jpl-damage/src/m/enum/PressurePicardEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PressurePicardEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PressurePicardEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PressurePicardEnum()
+
+macro=StringToEnum('PressurePicard');
Index: /issm/trunk-jpl-damage/src/m/enum/PrognosticAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PrognosticAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PrognosticAnalysisEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PrognosticAnalysisEnum()
+%PROGNOSTICANALYSISENUM - Enum of PrognosticAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PrognosticAnalysisEnum()
+
+macro=StringToEnum('PrognosticAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/PrognosticHydrostaticAdjustmentEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PrognosticHydrostaticAdjustmentEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PrognosticHydrostaticAdjustmentEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PrognosticHydrostaticAdjustmentEnum()
+%PROGNOSTICHYDROSTATICADJUSTMENTENUM - Enum of PrognosticHydrostaticAdjustment
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PrognosticHydrostaticAdjustmentEnum()
+
+macro=StringToEnum('PrognosticHydrostaticAdjustment');
Index: /issm/trunk-jpl-damage/src/m/enum/PrognosticMinThicknessEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PrognosticMinThicknessEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PrognosticMinThicknessEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PrognosticMinThicknessEnum()
+%PROGNOSTICMINTHICKNESSENUM - Enum of PrognosticMinThickness
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PrognosticMinThicknessEnum()
+
+macro=StringToEnum('PrognosticMinThickness');
Index: /issm/trunk-jpl-damage/src/m/enum/PrognosticPenaltyFactorEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PrognosticPenaltyFactorEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PrognosticPenaltyFactorEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PrognosticPenaltyFactorEnum()
+%PROGNOSTICPENALTYFACTORENUM - Enum of PrognosticPenaltyFactor
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PrognosticPenaltyFactorEnum()
+
+macro=StringToEnum('PrognosticPenaltyFactor');
Index: /issm/trunk-jpl-damage/src/m/enum/PrognosticSolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PrognosticSolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PrognosticSolutionEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PrognosticSolutionEnum()
+%PROGNOSTICSOLUTIONENUM - Enum of PrognosticSolution
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PrognosticSolutionEnum()
+
+macro=StringToEnum('PrognosticSolution');
Index: /issm/trunk-jpl-damage/src/m/enum/PrognosticSpcthicknessEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PrognosticSpcthicknessEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PrognosticSpcthicknessEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PrognosticSpcthicknessEnum()
+%PROGNOSTICSPCTHICKNESSENUM - Enum of PrognosticSpcthickness
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PrognosticSpcthicknessEnum()
+
+macro=StringToEnum('PrognosticSpcthickness');
Index: /issm/trunk-jpl-damage/src/m/enum/PrognosticStabilizationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PrognosticStabilizationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PrognosticStabilizationEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PrognosticStabilizationEnum()
+%PROGNOSTICSTABILIZATIONENUM - Enum of PrognosticStabilization
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PrognosticStabilizationEnum()
+
+macro=StringToEnum('PrognosticStabilization');
Index: /issm/trunk-jpl-damage/src/m/enum/PrognosticVertexPairingEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/PrognosticVertexPairingEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/PrognosticVertexPairingEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=PrognosticVertexPairingEnum()
+%PROGNOSTICVERTEXPAIRINGENUM - Enum of PrognosticVertexPairing
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=PrognosticVertexPairingEnum()
+
+macro=StringToEnum('PrognosticVertexPairing');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuBedEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuBedEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuBedEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=QmuBedEnum()
+%QMUBEDENUM - Enum of QmuBed
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuBedEnum()
+
+macro=StringToEnum('QmuBed');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuErrNameEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuErrNameEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuErrNameEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuErrNameEnum()
+
+macro=StringToEnum('QmuErrName');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuInNameEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuInNameEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuInNameEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuInNameEnum()
+
+macro=StringToEnum('QmuInName');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuIsdakotaEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuIsdakotaEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuIsdakotaEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuIsdakotaEnum()
+
+macro=StringToEnum('QmuIsdakota');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuMassFluxSegmentsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuMassFluxSegmentsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuMassFluxSegmentsEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=QmuMassFluxSegmentsEnum()
+%QMUMASSFLUXSEGMENTSENUM - Enum of QmuMassFluxSegments
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuMassFluxSegmentsEnum()
+
+macro=StringToEnum('QmuMassFluxSegments');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuMeltingEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuMeltingEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuMeltingEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuMeltingEnum()
+
+macro=StringToEnum('QmuMelting');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuNumberofpartitionsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuNumberofpartitionsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuNumberofpartitionsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuNumberofpartitionsEnum()
+
+macro=StringToEnum('QmuNumberofpartitions');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuNumberofresponsesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuNumberofresponsesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuNumberofresponsesEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuNumberofresponsesEnum()
+
+macro=StringToEnum('QmuNumberofresponses');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuOutNameEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuOutNameEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuOutNameEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuOutNameEnum()
+
+macro=StringToEnum('QmuOutName');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuPartitionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuPartitionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuPartitionEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuPartitionEnum()
+
+macro=StringToEnum('QmuPartition');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuPressureEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuPressureEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuPressureEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuPressureEnum()
+
+macro=StringToEnum('QmuPressure');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuResponsedescriptorsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuResponsedescriptorsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuResponsedescriptorsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuResponsedescriptorsEnum()
+
+macro=StringToEnum('QmuResponsedescriptors');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuSurfaceEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuSurfaceEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuSurfaceEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuSurfaceEnum()
+
+macro=StringToEnum('QmuSurface');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuTemperatureEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuTemperatureEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuTemperatureEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuTemperatureEnum()
+
+macro=StringToEnum('QmuTemperature');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuThicknessEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuThicknessEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuThicknessEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuThicknessEnum()
+
+macro=StringToEnum('QmuThickness');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuVariabledescriptorsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuVariabledescriptorsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuVariabledescriptorsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuVariabledescriptorsEnum()
+
+macro=StringToEnum('QmuVariabledescriptors');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuVxEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuVxEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuVxEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuVxEnum()
+
+macro=StringToEnum('QmuVx');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuVyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuVyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuVyEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuVyEnum()
+
+macro=StringToEnum('QmuVy');
Index: /issm/trunk-jpl-damage/src/m/enum/QmuVzEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/QmuVzEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/QmuVzEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=QmuVzEnum()
+
+macro=StringToEnum('QmuVz');
Index: /issm/trunk-jpl-damage/src/m/enum/RegularEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/RegularEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/RegularEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=RegularEnum()
+
+macro=StringToEnum('Regular');
Index: /issm/trunk-jpl-damage/src/m/enum/RelativeEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/RelativeEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/RelativeEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=RelativeEnum()
+%RELATIVEENUM - Enum of Relative
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=RelativeEnum()
+
+macro=StringToEnum('Relative');
Index: /issm/trunk-jpl-damage/src/m/enum/ResetPenaltiesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ResetPenaltiesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ResetPenaltiesEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ResetPenaltiesEnum()
+
+macro=StringToEnum('ResetPenalties');
Index: /issm/trunk-jpl-damage/src/m/enum/ResultsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ResultsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ResultsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ResultsEnum()
+
+macro=StringToEnum('Results');
Index: /issm/trunk-jpl-damage/src/m/enum/RheologyBbarAbsGradientEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/RheologyBbarAbsGradientEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/RheologyBbarAbsGradientEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=RheologyBbarAbsGradientEnum()
+
+macro=StringToEnum('RheologyBbarAbsGradient');
Index: /issm/trunk-jpl-damage/src/m/enum/RiftfrontEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/RiftfrontEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/RiftfrontEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=RiftfrontEnum()
+
+macro=StringToEnum('Riftfront');
Index: /issm/trunk-jpl-damage/src/m/enum/RiftsNumriftsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/RiftsNumriftsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/RiftsNumriftsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=RiftsNumriftsEnum()
+
+macro=StringToEnum('RiftsNumrifts');
Index: /issm/trunk-jpl-damage/src/m/enum/RiftsRiftstructEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/RiftsRiftstructEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/RiftsRiftstructEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=RiftsRiftstructEnum()
+
+macro=StringToEnum('RiftsRiftstruct');
Index: /issm/trunk-jpl-damage/src/m/enum/ScaledEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ScaledEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ScaledEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ScaledEnum()
+
+macro=StringToEnum('Scaled');
Index: /issm/trunk-jpl-damage/src/m/enum/SegmentEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SegmentEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SegmentEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SegmentEnum()
+
+macro=StringToEnum('Segment');
Index: /issm/trunk-jpl-damage/src/m/enum/SegmentOnIceShelfEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SegmentOnIceShelfEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SegmentOnIceShelfEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SegmentOnIceShelfEnum()
+
+macro=StringToEnum('SegmentOnIceShelf');
Index: /issm/trunk-jpl-damage/src/m/enum/SegmentRiftfrontEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SegmentRiftfrontEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SegmentRiftfrontEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SegmentRiftfrontEnum()
+
+macro=StringToEnum('SegmentRiftfront');
Index: /issm/trunk-jpl-damage/src/m/enum/SeparateEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SeparateEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SeparateEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SeparateEnum()
+
+macro=StringToEnum('Separate');
Index: /issm/trunk-jpl-damage/src/m/enum/SettingsIoGatherEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SettingsIoGatherEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SettingsIoGatherEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SettingsIoGatherEnum()
+
+macro=StringToEnum('SettingsIoGather');
Index: /issm/trunk-jpl-damage/src/m/enum/SettingsLowmemEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SettingsLowmemEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SettingsLowmemEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SettingsLowmemEnum()
+
+macro=StringToEnum('SettingsLowmem');
Index: /issm/trunk-jpl-damage/src/m/enum/SettingsOutputFrequencyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SettingsOutputFrequencyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SettingsOutputFrequencyEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SettingsOutputFrequencyEnum()
+
+macro=StringToEnum('SettingsOutputFrequency');
Index: /issm/trunk-jpl-damage/src/m/enum/SettingsResultsAsPatchesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SettingsResultsAsPatchesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SettingsResultsAsPatchesEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=SettingsResultsAsPatchesEnum()
+%SETTINGSRESULTSASPATCHESENUM - Enum of SettingsResultsAsPatches
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SettingsResultsAsPatchesEnum()
+
+macro=StringToEnum('SettingsResultsAsPatches');
Index: /issm/trunk-jpl-damage/src/m/enum/SettingsWaitonlockEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SettingsWaitonlockEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SettingsWaitonlockEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SettingsWaitonlockEnum()
+
+macro=StringToEnum('SettingsWaitonlock');
Index: /issm/trunk-jpl-damage/src/m/enum/SoftMigrationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SoftMigrationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SoftMigrationEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SoftMigrationEnum()
+
+macro=StringToEnum('SoftMigration');
Index: /issm/trunk-jpl-damage/src/m/enum/SolutionTypeEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SolutionTypeEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SolutionTypeEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SolutionTypeEnum()
+
+macro=StringToEnum('SolutionType');
Index: /issm/trunk-jpl-damage/src/m/enum/SpcDynamicEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SpcDynamicEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SpcDynamicEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SpcDynamicEnum()
+
+macro=StringToEnum('SpcDynamic');
Index: /issm/trunk-jpl-damage/src/m/enum/SpcStaticEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SpcStaticEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SpcStaticEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SpcStaticEnum()
+
+macro=StringToEnum('SpcStatic');
Index: /issm/trunk-jpl-damage/src/m/enum/SpcTransientEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SpcTransientEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SpcTransientEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SpcTransientEnum()
+
+macro=StringToEnum('SpcTransient');
Index: /issm/trunk-jpl-damage/src/m/enum/SsetEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SsetEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SsetEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SsetEnum()
+
+macro=StringToEnum('Sset');
Index: /issm/trunk-jpl-damage/src/m/enum/SteadystateMaxiterEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SteadystateMaxiterEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SteadystateMaxiterEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SteadystateMaxiterEnum()
+
+macro=StringToEnum('SteadystateMaxiter');
Index: /issm/trunk-jpl-damage/src/m/enum/SteadystateNumRequestedOutputsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SteadystateNumRequestedOutputsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SteadystateNumRequestedOutputsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SteadystateNumRequestedOutputsEnum()
+
+macro=StringToEnum('SteadystateNumRequestedOutputs');
Index: /issm/trunk-jpl-damage/src/m/enum/SteadystateReltolEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SteadystateReltolEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SteadystateReltolEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SteadystateReltolEnum()
+
+macro=StringToEnum('SteadystateReltol');
Index: /issm/trunk-jpl-damage/src/m/enum/SteadystateRequestedOutputsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SteadystateRequestedOutputsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SteadystateRequestedOutputsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SteadystateRequestedOutputsEnum()
+
+macro=StringToEnum('SteadystateRequestedOutputs');
Index: /issm/trunk-jpl-damage/src/m/enum/SteadystateSolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SteadystateSolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SteadystateSolutionEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SteadystateSolutionEnum()
+
+macro=StringToEnum('SteadystateSolution');
Index: /issm/trunk-jpl-damage/src/m/enum/StepResponsesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StepResponsesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StepResponsesEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=StepResponsesEnum()
+%STEPRESPONSESENUM - Enum of StepResponses
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StepResponsesEnum()
+
+macro=StringToEnum('StepResponses');
Index: /issm/trunk-jpl-damage/src/m/enum/StokesApproximationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StokesApproximationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StokesApproximationEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=StokesApproximationEnum()
+%STOKESAPPROXIMATIONENUM - Enum of StokesApproximation
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StokesApproximationEnum()
+
+macro=StringToEnum('StokesApproximation');
Index: /issm/trunk-jpl-damage/src/m/enum/StokesIceFrontEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StokesIceFrontEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StokesIceFrontEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=StokesIceFrontEnum()
+%STOKESICEFRONTENUM - Enum of StokesIceFront
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StokesIceFrontEnum()
+
+macro=StringToEnum('StokesIceFront');
Index: /issm/trunk-jpl-damage/src/m/enum/StokesSolverEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StokesSolverEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StokesSolverEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=StokesSolverEnum()
+%STOKESSOLVERENUM - Enum of StokesSolver
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StokesSolverEnum()
+
+macro=StringToEnum('StokesSolver');
Index: /issm/trunk-jpl-damage/src/m/enum/StressTensorEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StressTensorEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StressTensorEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StressTensorEnum()
+
+macro=StringToEnum('StressTensor');
Index: /issm/trunk-jpl-damage/src/m/enum/StressTensorxxEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StressTensorxxEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StressTensorxxEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StressTensorxxEnum()
+
+macro=StringToEnum('StressTensorxx');
Index: /issm/trunk-jpl-damage/src/m/enum/StressTensorxyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StressTensorxyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StressTensorxyEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StressTensorxyEnum()
+
+macro=StringToEnum('StressTensorxy');
Index: /issm/trunk-jpl-damage/src/m/enum/StressTensorxzEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StressTensorxzEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StressTensorxzEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StressTensorxzEnum()
+
+macro=StringToEnum('StressTensorxz');
Index: /issm/trunk-jpl-damage/src/m/enum/StressTensoryyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StressTensoryyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StressTensoryyEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StressTensoryyEnum()
+
+macro=StringToEnum('StressTensoryy');
Index: /issm/trunk-jpl-damage/src/m/enum/StressTensoryzEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StressTensoryzEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StressTensoryzEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StressTensoryzEnum()
+
+macro=StringToEnum('StressTensoryz');
Index: /issm/trunk-jpl-damage/src/m/enum/StressTensorzzEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StressTensorzzEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StressTensorzzEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StressTensorzzEnum()
+
+macro=StringToEnum('StressTensorzz');
Index: /issm/trunk-jpl-damage/src/m/enum/StringArrayParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StringArrayParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StringArrayParamEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StringArrayParamEnum()
+
+macro=StringToEnum('StringArrayParam');
Index: /issm/trunk-jpl-damage/src/m/enum/StringExternalResultEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StringExternalResultEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StringExternalResultEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StringExternalResultEnum()
+
+macro=StringToEnum('StringExternalResult');
Index: /issm/trunk-jpl-damage/src/m/enum/StringParamEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/StringParamEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/StringParamEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=StringParamEnum()
+
+macro=StringToEnum('StringParam');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceAbsVelMisfitEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceAbsVelMisfitEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceAbsVelMisfitEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceAbsVelMisfitEnum()
+
+macro=StringToEnum('SurfaceAbsVelMisfit');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceAreaEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceAreaEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceAreaEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceAreaEnum()
+
+macro=StringToEnum('SurfaceArea');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceAverageVelMisfitEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceAverageVelMisfitEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceAverageVelMisfitEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceAverageVelMisfitEnum()
+
+macro=StringToEnum('SurfaceAverageVelMisfit');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceEnum()
+
+macro=StringToEnum('Surface');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceLogVelMisfitEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceLogVelMisfitEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceLogVelMisfitEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceLogVelMisfitEnum()
+
+macro=StringToEnum('SurfaceLogVelMisfit');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceLogVxVyMisfitEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceLogVxVyMisfitEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceLogVxVyMisfitEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceLogVxVyMisfitEnum()
+
+macro=StringToEnum('SurfaceLogVxVyMisfit');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceRelVelMisfitEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceRelVelMisfitEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceRelVelMisfitEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceRelVelMisfitEnum()
+
+macro=StringToEnum('SurfaceRelVelMisfit');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeAnalysisEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=SurfaceSlopeAnalysisEnum()
+%SURFACESLOPEANALYSISENUM - Enum of SurfaceSlopeAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceSlopeAnalysisEnum()
+
+macro=StringToEnum('SurfaceSlopeAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeSolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeSolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeSolutionEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceSlopeSolutionEnum()
+
+macro=StringToEnum('SurfaceSlopeSolution');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeXAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeXAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeXAnalysisEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=SurfaceSlopeXAnalysisEnum()
+%SURFACESLOPEXANALYSISENUM - Enum of SurfaceSlopeXAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceSlopeXAnalysisEnum()
+
+macro=StringToEnum('SurfaceSlopeXAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeXEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeXEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeXEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceSlopeXEnum()
+
+macro=StringToEnum('SurfaceSlopeX');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeYAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeYAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeYAnalysisEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=SurfaceSlopeYAnalysisEnum()
+%SURFACESLOPEYANALYSISENUM - Enum of SurfaceSlopeYAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceSlopeYAnalysisEnum()
+
+macro=StringToEnum('SurfaceSlopeYAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeYEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeYEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceSlopeYEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceSlopeYEnum()
+
+macro=StringToEnum('SurfaceSlopeY');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceforcingsAblationRateEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceforcingsAblationRateEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceforcingsAblationRateEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsAblationRateEnum()
+%SURFACEFORCINGSABLATIONRATEENUM - Enum of SurfaceforcingsAblationRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsAblationRateEnum()
+
+macro=StringToEnum('SurfaceforcingsAblationRate');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceforcingsAccumulationRateEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceforcingsAccumulationRateEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceforcingsAccumulationRateEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsAccumulationRateEnum()
+%SURFACEFORCINGSACCUMULATIONRATEENUM - Enum of SurfaceforcingsAccumulationRate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsAccumulationRateEnum()
+
+macro=StringToEnum('SurfaceforcingsAccumulationRate');
Index: /issm/trunk-jpl-damage/src/m/enum/SurfaceforcingsMassBalanceEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/SurfaceforcingsMassBalanceEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/SurfaceforcingsMassBalanceEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsMassBalanceEnum()
+
+macro=StringToEnum('SurfaceforcingsMassBalance');
Index: /issm/trunk-jpl-damage/src/m/enum/TemperatureEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TemperatureEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TemperatureEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TemperatureEnum()
+
+macro=StringToEnum('Temperature');
Index: /issm/trunk-jpl-damage/src/m/enum/TemperatureOldEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TemperatureOldEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TemperatureOldEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=TemperatureOldEnum()
+%TEMPERATUREOLDENUM - Enum of TemperatureOld
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TemperatureOldEnum()
+
+macro=StringToEnum('TemperatureOld');
Index: /issm/trunk-jpl-damage/src/m/enum/TemperaturePicardEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TemperaturePicardEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TemperaturePicardEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TemperaturePicardEnum()
+
+macro=StringToEnum('TemperaturePicard');
Index: /issm/trunk-jpl-damage/src/m/enum/ThermalAnalysisEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ThermalAnalysisEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ThermalAnalysisEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ThermalAnalysisEnum()
+
+macro=StringToEnum('ThermalAnalysis');
Index: /issm/trunk-jpl-damage/src/m/enum/ThermalMaxiterEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ThermalMaxiterEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ThermalMaxiterEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ThermalMaxiterEnum()
+
+macro=StringToEnum('ThermalMaxiter');
Index: /issm/trunk-jpl-damage/src/m/enum/ThermalPenaltyFactorEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ThermalPenaltyFactorEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ThermalPenaltyFactorEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ThermalPenaltyFactorEnum()
+
+macro=StringToEnum('ThermalPenaltyFactor');
Index: /issm/trunk-jpl-damage/src/m/enum/ThermalPenaltyLockEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ThermalPenaltyLockEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ThermalPenaltyLockEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ThermalPenaltyLockEnum()
+
+macro=StringToEnum('ThermalPenaltyLock');
Index: /issm/trunk-jpl-damage/src/m/enum/ThermalPenaltyThresholdEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ThermalPenaltyThresholdEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ThermalPenaltyThresholdEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ThermalPenaltyThresholdEnum()
+
+macro=StringToEnum('ThermalPenaltyThreshold');
Index: /issm/trunk-jpl-damage/src/m/enum/ThermalSolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ThermalSolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ThermalSolutionEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ThermalSolutionEnum()
+
+macro=StringToEnum('ThermalSolution');
Index: /issm/trunk-jpl-damage/src/m/enum/ThermalSpctemperatureEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ThermalSpctemperatureEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ThermalSpctemperatureEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ThermalSpctemperatureEnum()
+
+macro=StringToEnum('ThermalSpctemperature');
Index: /issm/trunk-jpl-damage/src/m/enum/ThermalStabilizationEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ThermalStabilizationEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ThermalStabilizationEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ThermalStabilizationEnum()
+
+macro=StringToEnum('ThermalStabilization');
Index: /issm/trunk-jpl-damage/src/m/enum/ThicknessAbsGradientEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ThicknessAbsGradientEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ThicknessAbsGradientEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ThicknessAbsGradientEnum()
+
+macro=StringToEnum('ThicknessAbsGradient');
Index: /issm/trunk-jpl-damage/src/m/enum/ThicknessAbsMisfitEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ThicknessAbsMisfitEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ThicknessAbsMisfitEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ThicknessAbsMisfitEnum()
+
+macro=StringToEnum('ThicknessAbsMisfit');
Index: /issm/trunk-jpl-damage/src/m/enum/ThicknessEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ThicknessEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ThicknessEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ThicknessEnum()
+
+macro=StringToEnum('Thickness');
Index: /issm/trunk-jpl-damage/src/m/enum/TimeEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TimeEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TimeEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TimeEnum()
+
+macro=StringToEnum('Time');
Index: /issm/trunk-jpl-damage/src/m/enum/TimesteppingCflCoefficientEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TimesteppingCflCoefficientEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TimesteppingCflCoefficientEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TimesteppingCflCoefficientEnum()
+
+macro=StringToEnum('TimesteppingCflCoefficient');
Index: /issm/trunk-jpl-damage/src/m/enum/TimesteppingFinalTimeEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TimesteppingFinalTimeEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TimesteppingFinalTimeEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TimesteppingFinalTimeEnum()
+
+macro=StringToEnum('TimesteppingFinalTime');
Index: /issm/trunk-jpl-damage/src/m/enum/TimesteppingTimeAdaptEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TimesteppingTimeAdaptEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TimesteppingTimeAdaptEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TimesteppingTimeAdaptEnum()
+
+macro=StringToEnum('TimesteppingTimeAdapt');
Index: /issm/trunk-jpl-damage/src/m/enum/TimesteppingTimeStepEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TimesteppingTimeStepEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TimesteppingTimeStepEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TimesteppingTimeStepEnum()
+
+macro=StringToEnum('TimesteppingTimeStep');
Index: /issm/trunk-jpl-damage/src/m/enum/TransientInputEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TransientInputEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TransientInputEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TransientInputEnum()
+
+macro=StringToEnum('TransientInput');
Index: /issm/trunk-jpl-damage/src/m/enum/TransientIsdiagnosticEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TransientIsdiagnosticEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TransientIsdiagnosticEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=TransientIsdiagnosticEnum()
+%TRANSIENTISDIAGNOSTICENUM - Enum of TransientIsdiagnostic
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TransientIsdiagnosticEnum()
+
+macro=StringToEnum('TransientIsdiagnostic');
Index: /issm/trunk-jpl-damage/src/m/enum/TransientIsgroundinglineEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TransientIsgroundinglineEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TransientIsgroundinglineEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TransientIsgroundinglineEnum()
+
+macro=StringToEnum('TransientIsgroundingline');
Index: /issm/trunk-jpl-damage/src/m/enum/TransientIsprognosticEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TransientIsprognosticEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TransientIsprognosticEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=TransientIsprognosticEnum()
+%TRANSIENTISPROGNOSTICENUM - Enum of TransientIsprognostic
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TransientIsprognosticEnum()
+
+macro=StringToEnum('TransientIsprognostic');
Index: /issm/trunk-jpl-damage/src/m/enum/TransientIsthermalEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TransientIsthermalEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TransientIsthermalEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TransientIsthermalEnum()
+
+macro=StringToEnum('TransientIsthermal');
Index: /issm/trunk-jpl-damage/src/m/enum/TransientNumRequestedOutputsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TransientNumRequestedOutputsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TransientNumRequestedOutputsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TransientNumRequestedOutputsEnum()
+
+macro=StringToEnum('TransientNumRequestedOutputs');
Index: /issm/trunk-jpl-damage/src/m/enum/TransientRequestedOutputsEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TransientRequestedOutputsEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TransientRequestedOutputsEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TransientRequestedOutputsEnum()
+
+macro=StringToEnum('TransientRequestedOutputs');
Index: /issm/trunk-jpl-damage/src/m/enum/TransientSolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TransientSolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TransientSolutionEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TransientSolutionEnum()
+
+macro=StringToEnum('TransientSolution');
Index: /issm/trunk-jpl-damage/src/m/enum/TriaEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TriaEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TriaEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TriaEnum()
+
+macro=StringToEnum('Tria');
Index: /issm/trunk-jpl-damage/src/m/enum/TriaVertexElementResultEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TriaVertexElementResultEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TriaVertexElementResultEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=TriaVertexElementResultEnum()
+%TRIAVERTEXELEMENTRESULTENUM - Enum of TriaVertexElementResult
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TriaVertexElementResultEnum()
+
+macro=StringToEnum('TriaVertexElementResult');
Index: /issm/trunk-jpl-damage/src/m/enum/TriaVertexInputEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TriaVertexInputEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TriaVertexInputEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=TriaVertexInputEnum()
+%TRIAVERTEXINPUTENUM - Enum of TriaVertexInput
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TriaVertexInputEnum()
+
+macro=StringToEnum('TriaVertexInput');
Index: /issm/trunk-jpl-damage/src/m/enum/TriangleInterpEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TriangleInterpEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TriangleInterpEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TriangleInterpEnum()
+
+macro=StringToEnum('TriangleInterp');
Index: /issm/trunk-jpl-damage/src/m/enum/TypeEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/TypeEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/TypeEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=TypeEnum()
+%TYPEENUM - Enum of Type
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TypeEnum()
+
+macro=StringToEnum('Type');
Index: /issm/trunk-jpl-damage/src/m/enum/VelEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VelEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VelEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VelEnum()
+
+macro=StringToEnum('Vel');
Index: /issm/trunk-jpl-damage/src/m/enum/VelocityEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VelocityEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VelocityEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VelocityEnum()
+
+macro=StringToEnum('Velocity');
Index: /issm/trunk-jpl-damage/src/m/enum/VerboseEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VerboseEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VerboseEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VerboseEnum()
+
+macro=StringToEnum('Verbose');
Index: /issm/trunk-jpl-damage/src/m/enum/VertexEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VertexEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VertexEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VertexEnum()
+
+macro=StringToEnum('Vertex');
Index: /issm/trunk-jpl-damage/src/m/enum/VerticesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VerticesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VerticesEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VerticesEnum()
+
+macro=StringToEnum('Vertices');
Index: /issm/trunk-jpl-damage/src/m/enum/ViscousHeatingEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/ViscousHeatingEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/ViscousHeatingEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=ViscousHeatingEnum()
+
+macro=StringToEnum('ViscousHeating');
Index: /issm/trunk-jpl-damage/src/m/enum/VxAverageEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VxAverageEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VxAverageEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VxAverageEnum()
+
+macro=StringToEnum('VxAverage');
Index: /issm/trunk-jpl-damage/src/m/enum/VxEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VxEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VxEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VxEnum()
+
+macro=StringToEnum('Vx');
Index: /issm/trunk-jpl-damage/src/m/enum/VxMeshEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VxMeshEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VxMeshEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VxMeshEnum()
+
+macro=StringToEnum('VxMesh');
Index: /issm/trunk-jpl-damage/src/m/enum/VxPicardEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VxPicardEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VxPicardEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VxPicardEnum()
+
+macro=StringToEnum('VxPicard');
Index: /issm/trunk-jpl-damage/src/m/enum/VyAverageEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VyAverageEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VyAverageEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VyAverageEnum()
+
+macro=StringToEnum('VyAverage');
Index: /issm/trunk-jpl-damage/src/m/enum/VyEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VyEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VyEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VyEnum()
+
+macro=StringToEnum('Vy');
Index: /issm/trunk-jpl-damage/src/m/enum/VyMeshEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VyMeshEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VyMeshEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VyMeshEnum()
+
+macro=StringToEnum('VyMesh');
Index: /issm/trunk-jpl-damage/src/m/enum/VyPicardEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VyPicardEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VyPicardEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VyPicardEnum()
+
+macro=StringToEnum('VyPicard');
Index: /issm/trunk-jpl-damage/src/m/enum/VzEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VzEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VzEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VzEnum()
+
+macro=StringToEnum('Vz');
Index: /issm/trunk-jpl-damage/src/m/enum/VzMacAyealEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VzMacAyealEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VzMacAyealEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=VzMacAyealEnum()
+%VZMACAYEALENUM - Enum of VzMacAyeal
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VzMacAyealEnum()
+
+macro=StringToEnum('VzMacAyeal');
Index: /issm/trunk-jpl-damage/src/m/enum/VzMeshEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VzMeshEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VzMeshEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VzMeshEnum()
+
+macro=StringToEnum('VzMesh');
Index: /issm/trunk-jpl-damage/src/m/enum/VzPattynEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VzPattynEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VzPattynEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=VzPattynEnum()
+%VZPATTYNENUM - Enum of VzPattyn
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VzPattynEnum()
+
+macro=StringToEnum('VzPattyn');
Index: /issm/trunk-jpl-damage/src/m/enum/VzPicardEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VzPicardEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VzPicardEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VzPicardEnum()
+
+macro=StringToEnum('VzPicard');
Index: /issm/trunk-jpl-damage/src/m/enum/VzStokesEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/VzStokesEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/VzStokesEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=VzStokesEnum()
+%VZSTOKESENUM - Enum of VzStokes
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=VzStokesEnum()
+
+macro=StringToEnum('VzStokes');
Index: /issm/trunk-jpl-damage/src/m/enum/WaterColumnOldEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/WaterColumnOldEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/WaterColumnOldEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=WaterColumnOldEnum()
+
+macro=StringToEnum('WaterColumnOld');
Index: /issm/trunk-jpl-damage/src/m/enum/WaterEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/WaterEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/WaterEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=WaterEnum()
+
+macro=StringToEnum('Water');
Index: /issm/trunk-jpl-damage/src/m/enum/WatercolumnEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/WatercolumnEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/WatercolumnEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=WatercolumnEnum()
+
+macro=StringToEnum('Watercolumn');
Index: /issm/trunk-jpl-damage/src/m/enum/WaterfractionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/WaterfractionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/WaterfractionEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=WaterfractionEnum()
+
+macro=StringToEnum('Waterfraction');
Index: /issm/trunk-jpl-damage/src/m/enum/XYEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/XYEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/XYEnum.m	(revision 11330)
@@ -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/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=XYEnum()
+
+macro=StringToEnum('XY');
Index: /issm/trunk-jpl-damage/src/m/enum/XYZPEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/enum/XYZPEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/enum/XYZPEnum.m	(revision 11330)
@@ -0,0 +1,11 @@
+function macro=XYZPEnum()
+%XYZPENUM - Enum of XYZP
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=XYZPEnum()
+
+macro=StringToEnum('XYZP');
Index: /issm/trunk-jpl-damage/src/m/kml/README.txt
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/README.txt	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/README.txt	(revision 11330)
@@ -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.
+
+nodeconnectivity.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/trunk-jpl-damage/src/m/kml/edgeadjacency.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/edgeadjacency.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/edgeadjacency.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/kml/edgeperimeter.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/edgeperimeter.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/edgeperimeter.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/kml/kml_colorstyle.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_colorstyle.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_colorstyle.m	(revision 11330)
@@ -0,0 +1,202 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_container.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_container.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_container.m	(revision 11330)
@@ -0,0 +1,199 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_document.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_document.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_document.m	(revision 11330)
@@ -0,0 +1,236 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_feature.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_feature.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_feature.m	(revision 11330)
@@ -0,0 +1,295 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_file_swrite.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_file_swrite.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_file_swrite.m	(revision 11330)
@@ -0,0 +1,132 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_file_write.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_file_write.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_file_write.m	(revision 11330)
@@ -0,0 +1,126 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_folder.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_folder.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_folder.m	(revision 11330)
@@ -0,0 +1,236 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_geometry.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_geometry.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_geometry.m	(revision 11330)
@@ -0,0 +1,179 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_linearring.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_linearring.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_linearring.m	(revision 11330)
@@ -0,0 +1,209 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_linestring.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_linestring.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_linestring.m	(revision 11330)
@@ -0,0 +1,209 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_linestyle.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_linestyle.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_linestyle.m	(revision 11330)
@@ -0,0 +1,176 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_mesh_elem.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_mesh_elem.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_mesh_elem.m	(revision 11330)
@@ -0,0 +1,177 @@
+%%
+%  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/trunk-jpl-damage/src/m/kml/kml_mesh_write.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_mesh_write.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_mesh_write.m	(revision 11330)
@@ -0,0 +1,261 @@
+%%
+%  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/trunk-jpl-damage/src/m/kml/kml_multigeometry.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_multigeometry.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_multigeometry.m	(revision 11330)
@@ -0,0 +1,231 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_object.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_object.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_object.m	(revision 11330)
@@ -0,0 +1,180 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_part_edges.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_part_edges.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_part_edges.m	(revision 11330)
@@ -0,0 +1,483 @@
+%%
+%  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=nodeconnectivity(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/trunk-jpl-damage/src/m/kml/kml_part_elems.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_part_elems.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_part_elems.m	(revision 11330)
@@ -0,0 +1,217 @@
+%%
+%  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/trunk-jpl-damage/src/m/kml/kml_part_flagedges.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_part_flagedges.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_part_flagedges.m	(revision 11330)
@@ -0,0 +1,110 @@
+%%
+%  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/trunk-jpl-damage/src/m/kml/kml_partitions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_partitions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_partitions.m	(revision 11330)
@@ -0,0 +1,486 @@
+%%
+%  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=nodeconnectivity(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/trunk-jpl-damage/src/m/kml/kml_placemark.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_placemark.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_placemark.m	(revision 11330)
@@ -0,0 +1,239 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_polygon.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_polygon.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_polygon.m	(revision 11330)
@@ -0,0 +1,272 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_polystyle.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_polystyle.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_polystyle.m	(revision 11330)
@@ -0,0 +1,182 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_style.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_style.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_style.m	(revision 11330)
@@ -0,0 +1,328 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_styleselector.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_styleselector.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_styleselector.m	(revision 11330)
@@ -0,0 +1,179 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_substyle.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_substyle.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_substyle.m	(revision 11330)
@@ -0,0 +1,179 @@
+%
+%  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/trunk-jpl-damage/src/m/kml/kml_unsh_edges.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/kml_unsh_edges.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/kml_unsh_edges.m	(revision 11330)
@@ -0,0 +1,116 @@
+%%
+%  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.nodeconnectivity);
+    [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/trunk-jpl-damage/src/m/kml/nodeconnectivity.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/nodeconnectivity.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/nodeconnectivity.m	(revision 11330)
@@ -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]=nodeconnectivity(elem,nnodes,mxepg)
+
+if ~nargin
+    help nodeconnectivity
+    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/trunk-jpl-damage/src/m/kml/string_buf.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/kml/string_buf.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/kml/string_buf.m	(revision 11330)
@@ -0,0 +1,189 @@
+%
+%  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/trunk-jpl-damage/src/m/model/BasinConstrain.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/BasinConstrain.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/BasinConstrain.m	(revision 11330)
@@ -0,0 +1,63 @@
+function md=BasinConstrain(md,domain);
+%BASINCONSTRAIN - constrain basin
+%
+%   Constrain basin using a constraint domain outline, 
+%   to dirichlet boundary conditions.
+%   constraindomain is an Argus domain outline file enclosing 
+%   the geographical area of interest.
+%
+%   Usage: 
+%      md=BasinConstrain(md,constraindomain)
+%
+%   Example:
+%      md=BasinConstrain(md,'DomainOutline.exp');
+%      md=BasinConstrain(md,'~Iceshelves.exp');
+
+%now, flag nodes and elements outside the domain outline.
+if ischar(domain),
+	if isempty(domain),
+		elementondomain=zeros(md.mesh.numberofelements,1);
+		vertexondomain=zeros(md.mesh.numberofvertices,1);
+		invert=0;
+	elseif strcmpi(domain,'all')
+		elementondomain=ones(md.mesh.numberofelements,1);
+		vertexondomain=ones(md.mesh.numberofvertices,1);
+		invert=0;
+	else
+		%make sure that we actually don't want the elements outside the domain outline!
+		if strcmpi(domain(1),'~'),
+			domain=domain(2:end);
+			invert=1;
+		else
+			invert=0;
+		end
+		%ok, flag elements and nodes
+		[vertexondomain elementondomain]=ContourToMesh(md.mesh.elements(:,1:3),md.mesh.x,md.mesh.y,domain,'element and node',2);
+	end
+	if invert,
+		vertexondomain=~vertexondomain;
+		elementondomain=~elementondomain;
+	end
+else
+	error('BasinConstrain error message: domain type not supported yet');
+end
+
+%list of elements and nodes not on domain
+vertexnotondomain=find(~vertexondomain);
+elementnotondomain=find(~elementondomain);
+
+%all elements outside the constraint domain are equivalent to water. all nodes outside are spc'd.
+md.diagnostic.spcvx(vertexnotondomain)=md.inversion.vx_obs(vertexnotondomain);
+md.diagnostic.spcvy(vertexnotondomain)=md.inversion.vy_obs(vertexnotondomain);
+md.mask.elementonwater(elementnotondomain)=1;
+
+%now, make sure all elements on water have nodes that are spc'd, otherwise, we'll get a singular problem.
+pos=find(~md.mask.elementonwater);
+numpos=unique(md.mesh.elements(pos,:));
+nodes=setdiff(1:1:md.mesh.numberofvertices,numpos);
+md.diagnostic.spcvx(nodes)=md.inversion.vx_obs(nodes);
+md.diagnostic.spcvy(nodes)=md.inversion.vy_obs(nodes);
+
+%make sure icefronts that are completely spc'd are taken out:
+free_segments=find((~isnan(md.diagnostic.spcvx(md.diagnostic.icefront(:,1:2))) + ~isnan(md.diagnostic.spcvy(md.diagnostic.icefront(:,1:2))))~=2);
+md.diagnostic.icefront=md.diagnostic.icefront(free_segments,:);
Index: /issm/trunk-jpl-damage/src/m/model/BasinConstrainShelf.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/BasinConstrainShelf.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/BasinConstrainShelf.m	(revision 11330)
@@ -0,0 +1,74 @@
+function md=BasinConstrainShelf(md,domain);
+%BASINCONSTRAIN - constrain basin
+%
+%   Constrain basin using a constraint domain outline, 
+%   to dirichlet boundary conditions.
+%   constraindomain is an Argus domain outline file enclosing 
+%   the geographical area of interest.
+%
+%   Usage: 
+%      md=BasinConstrain(md,constraindomain)
+%
+%   Example:
+%      md=BasinConstrain(md,'DomainOutline.exp');
+%      md=BasinConstrain(md,'~Iceshelves.exp');
+
+%now, flag nodes and elements outside the domain outline.
+if ischar(domain),
+	if isempty(domain),
+		elementondomain=zeros(md.mesh.numberofelements,1);
+		vertexondomain=zeros(md.mesh.numberofvertices,1);
+		invert=0;
+	elseif strcmpi(domain,'all')
+		elementondomain=ones(md.mesh.numberofelements,1);
+		vertexondomain=ones(md.mesh.numberofvertices,1);
+		invert=0;
+	else
+		%make sure that we actually don't want the elements outside the domain outline!
+		if strcmpi(domain(1),'~'),
+			domain=domain(2:end);
+			invert=1;
+		else
+			invert=0;
+		end
+		%ok, flag elements and nodes
+		[vertexondomain elementondomain]=ContourToMesh(md.mesh.elements(:,1:3),md.mesh.x,md.mesh.y,domain,'element and node',2);
+	end
+	if invert,
+		vertexondomain=~vertexondomain;
+		elementondomain=~elementondomain;
+	end
+else
+	error('BasinConstrain error message: domain type not supported yet');
+end
+
+%list of elements and nodes not on domain
+vertexnotondomain=find(~vertexondomain);
+elementnotondomain=find(~elementondomain);
+
+%all elements outside the constraint domain are equivalent to water. all nodes outside are spc'd.
+md.diagnostic.spcvx(vertexnotondomain)=md.inversion.vx_obs(vertexnotondomain);
+md.diagnostic.spcvy(vertexnotondomain)=md.inversion.vy_obs(vertexnotondomain);
+md.mask.elementonwater(elementnotondomain)=1;
+
+%now, make sure all elements on water have nodes that are spc'd, otherwise, we'll get a singular problem.
+pos=find(~md.mask.elementonwater);
+numpos=unique(md.mesh.elements(pos,:));
+nodes=setdiff(1:1:md.mesh.numberofvertices,numpos);
+md.diagnostic.spcvx(nodes)=md.inversion.vx_obs(nodes);
+md.diagnostic.spcvy(nodes)=md.inversion.vy_obs(nodes);
+
+%make sure any node with NaN velocity is spc'd:
+%we spc to the smoothed value, so that control methods don't go berserk trying to figure out what reaction force to apply for the spc to stand.
+pos=find(isnan(md.inversion.vel_obs_raw));
+md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos); 
+md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos); 
+
+%iceshelves: any vertex on floating ice is spc'd
+pos=find(md.mask.vertexongroundedice);
+md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos); 
+md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos); 
+
+%make sure icefronts that are completely spc'd are taken out:
+free_segments=find((~isnan(md.diagnostic.spcvx(md.diagnostic.icefront(:,1:2))) + ~isnan(md.diagnostic.spcvy(md.diagnostic.icefront(:,1:2))) )~=2);
+md.diagnostic.icefront=md.diagnostic.icefront(free_segments,:);
Index: /issm/trunk-jpl-damage/src/m/model/DepthAverage.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/DepthAverage.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/DepthAverage.m	(revision 11330)
@@ -0,0 +1,33 @@
+function  vector_average=DepthAverage(md,vector);
+%DEPTHAVERAGE - computes depth average of 3d vector, and return value on 2d mesh. 
+%
+%   Usage:
+%      vector_average=DepthAverage(md,vector);
+%
+%   Example:
+%      vel_bar=DepthAverage(md,md.initialization.vel);
+
+%check that the model given in input is 3d
+if ~md.mesh.dimension==3;
+	error('DepthAverage error message: the model given in input must be 3d')
+end
+
+%nods data
+if (length(vector)==md.mesh.numberofvertices),
+	vector_average=zeros(md.mesh.numberofvertices2d,1);
+	for i=1:md.mesh.numberoflayers-1,
+		vector_average=vector_average+(project2d(md,vector,i)+project2d(md,vector,i+1))/2.*(project2d(md,md.mesh.z,i+1)-project2d(md,md.mesh.z,i));
+	end
+	vector_average=vector_average./project2d(md,md.geometry.thickness,1);
+
+%element data
+elseif (length(vector)==md.mesh.numberofelements),
+	vector_average=zeros(md.mesh.numberofelements2d,1);
+	for i=1:md.mesh.numberoflayers-1,
+		vector_average=vector_average+project2d(md,vector,i).*(project2d(md,md.mesh.z,i+1)-project2d(md,md.mesh.z,i));
+	end
+	vector_average=vector_average./project2d(md,md.geometry.thickness,1);
+
+else
+	error('vector size not supported yet');
+end
Index: /issm/trunk-jpl-damage/src/m/model/MeltingGroundingLines.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/MeltingGroundingLines.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/MeltingGroundingLines.m	(revision 11330)
@@ -0,0 +1,26 @@
+function md=MeltingGroundingLines(md,distance,value)
+%MELTINGGROUNDINGLINES - set melting near grounding lines to a constant value
+%
+%   Usage:
+%      md=MeltingGroundingLines(md,distance,value)
+%
+
+%get nodes on ice sheet and on ice shelf
+pos_shelf=find(~md.mask.vertexongroundedice);
+pos_GL=intersect(unique(md.mesh.elements(find(md.mask.elementongroundedice),:)),unique(md.mesh.elements(find(md.mask.elementonfloatingice),:)));
+
+for i=1:length(pos_shelf)
+
+	if (mod(i,100)==0),
+		fprintf('\b\b\b\b\b\b\b%5.2f%s',i/length(pos_shelf)*100,' %');
+	end
+
+	%search the node on ice sheet the closest to i
+	[d posd]=min(sqrt((md.mesh.x(pos_shelf(i))-md.mesh.x(pos_GL)).^2+(md.mesh.y(pos_shelf(i))-md.mesh.y(pos_GL)).^2));
+
+	if d<distance,
+
+		md.melting(pos_shelf(i))=value;
+
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/PropagateFlagsUntilDistance.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/PropagateFlagsUntilDistance.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/PropagateFlagsUntilDistance.m	(revision 11330)
@@ -0,0 +1,64 @@
+function new_flags=PropagateFlagsUntilDistance(md,flags,distance)
+%PROPAGATEFLAGSUNTILDISTANCE
+%
+% Usage: 
+%              flags=PropagateFlagsUntilDistance(md,flags,distance)
+%
+%
+
+
+	
+new_flags=flags;
+
+%make 3d work in 2d: 
+if md.mesh.dimension==3,
+	md.mesh.x=md.mesh.x2d;
+	md.mesh.y=md.mesh.y2d;
+	md.mesh.elements=md.mesh.elements2d;
+end
+
+%find elements that are at the border of flags: 
+flag_elements=find(flags);
+conn=md.mesh.elementconnectivity(flag_elements,:);
+pos=find(conn);conn(pos)=~flags(conn(pos));
+sum_conn=sum(conn,2);
+border_elements=flag_elements(find(sum_conn>=1));
+
+
+%average x and y over elements: 
+x_elem=md.mesh.x(md.mesh.elements)*[1;1;1]/3;
+y_elem=md.mesh.y(md.mesh.elements)*[1;1;1]/3;
+
+while 1,
+
+	%keep copy of new_flags for this loop: 
+	new_flags_bak=new_flags;
+
+	%extend new flags by connectivity
+	pos=find(new_flags);
+
+	connected_elements=md.mesh.elementconnectivity(pos,:);
+	connected_elements=connected_elements(find(connected_elements));
+	new_flags(connected_elements)=1;
+
+	%get new elements: 
+	new_elements=find(new_flags & ~new_flags_bak);
+	if ~length(new_elements),
+		%we are done!
+		break;
+	end
+
+
+	%check which of these new elements are more than distance away from the border elements
+	for i=1:length(new_elements),
+		dist=sqrt(     (x_elem(border_elements)-x_elem(new_elements(i))).^2 + (y_elem(border_elements)-y_elem(new_elements(i))).^2)-distance;
+		if ~any(dist<0)
+			%none of the border elements are within distance, this element is outside out area of interest.
+			%ensure this element never gets found again in the connectivity.
+			pos=find(md.mesh.elementconnectivity==new_elements(i));
+			md.mesh.elementconnectivity(pos)=0;
+			%exclude this new element from the new_flags!
+			new_flags(new_elements(i))=0;
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/README
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/README	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/README	(revision 11330)
@@ -0,0 +1,11 @@
+This directory is similar to @model, in that it only deals
+with methods proper to the @model class. But we need a different 
+directory from @model, to make those methods public, not private. 
+The advantage of public methods is that they will use subsref and 
+susasgn to access data in a @model object.
+
+For ex: 
+calling md.x in a "@model" routine just accesses the x field in the md 
+structure. But calling md.x in a "model" routine will access the x field 
+through the susref routine in @model. This ensures that we protect the 
+data in @model classes from improper use.
Index: /issm/trunk-jpl-damage/src/m/model/SectionValues.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/SectionValues.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/SectionValues.m	(revision 11330)
@@ -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:
+	contempt=expread(infile,1);
+	nods=contempt.nods;
+	x=contempt.x;
+	y=contempt.y;
+else
+	%read infile:
+	nods=infile.nods;
+	x=infile.x;
+	y=infile.y;
+end
+
+
+%get the specified resolution
+if isnumeric(resolution(1))
+	res_h=resolution(1);
+else
+	error('SectionValues error message: wrong resolution type. Resolution must be an array [horizontal_resolution vertical_resolution]')
+end
+if md.mesh.dimension==3
+	if (length(resolution)==2 & isnumeric(resolution(2)))
+		res_v=resolution(2);
+	else
+		error('SectionValues error message: wrong resolution type. Resolution must be an array [horizontal_resolution vertical_resolution]')
+	end
+end
+
+%initialization
+X=[]; %X-coordinate
+Y=[]; %Y-coordinate
+S=0;  %curvilinear coordinate
+
+for i=1:nods-1
+
+	x_start=x(i);
+	x_end=x(i+1);
+	y_start=y(i);
+	y_end=y(i+1);
+	s_start=S(end);
+
+	length_segment=sqrt((x_end-x_start)^2+(y_end-y_start)^2);
+	portion=ceil(length_segment/res_h);
+
+	x_segment=zeros(portion,1);
+	y_segment=zeros(portion,1);
+	s_segment=zeros(portion,1);
+
+	for j=1:portion
+		x_segment(j)=x_start+(j-1)*(x_end-x_start)/portion;
+		y_segment(j)=y_start+(j-1)*(y_end-y_start)/portion;
+		s_segment(j)=s_start+j*length_segment/portion;
+	end
+
+	%plug into X and Y
+	X=[X;x_segment];
+	Y=[Y;y_segment];
+	S=[S;s_segment];
+end
+X(end+1)=x(nods);
+Y(end+1)=y(nods);
+
+%Number of nodes:
+numberofnodes=size(X,1);
+
+%Compute Z
+Z=zeros(numberofnodes,1);
+
+%New mesh and Data interpolation
+if (md.mesh.dimension==2)
+
+	%Interpolation of data on specified points
+	data_interp=InterpFromMeshToMesh2d(md.mesh.elements,md.mesh.x,md.mesh.y,data,X,Y);
+	%data_interp=griddata(md.mesh.x,md.mesh.y,data,X,Y);
+
+	%Compute index
+	index=[1:1:(numberofnodes-1);2:1:numberofnodes]';
+
+else
+
+	%vertically extrude mesh
+
+	%Get bed and surface for each 2d point, offset to make sure that it is inside the glacier system
+	offset=10^-3;
+	bed=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.bed,1),X,Y)+offset;
+	surface=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.surface,1),X,Y)-offset;
+
+	%Some useful parameters
+	layers=ceil(mean(md.geometry.thickness)/res_v);
+	nodesperlayer=numberofnodes;
+	nodestot=nodesperlayer*layers;
+	elementsperlayer=nodesperlayer-1;
+	elementstot=(nodesperlayer-1)*(layers-1);
+
+	%initialization
+	X3=zeros(nodesperlayer*layers,1); Y3=zeros(nodesperlayer*layers,1); Z3=zeros(nodesperlayer*layers,1); S3=zeros(nodesperlayer*layers,1); index3=zeros(elementstot,4);
+
+	%Get new coordinates in 3d
+	for i=1:layers
+		X3(i:layers:end)=X;
+		Y3(i:layers:end)=Y;
+		Z3(i:layers:end)=bed+(i-1)*(surface-bed)/(layers-1);
+		S3(i:layers:end)=S;
+
+		if i<layers %Build index3 with quads
+			index3((i-1)*elementsperlayer+1:i*elementsperlayer,:)=[i:layers:nodestot-layers; i+1:layers:nodestot-layers; i+layers+1:layers:nodestot; i+layers:layers:nodestot]';
+		end
+	end
+
+	%Interpolation of data on specified points
+	data_interp=InterpFromMeshToMesh3d(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,data,X3,Y3,Z3,NaN);
+
+	%build outputs
+	X=X3; Y=Y3; Z=Z3;  S=S3; index=index3;
+end
Index: /issm/trunk-jpl-damage/src/m/model/ThicknessCorrection.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/ThicknessCorrection.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/ThicknessCorrection.m	(revision 11330)
@@ -0,0 +1,77 @@
+function md=ThicknessCorrection(md,varargin)
+%THICKNESSCORRECTION - correct the thickness of the ice shelf near the grounding line
+%
+%   This routine corrects the thickness and the bed on the transition zone
+%   by forcing the hydrostatic equilibrium.
+%   the thickness is modified as follows:
+%      thickness = (1-coeff) * thickness_observation + coeff * thickness_hydrostatic
+%   where:
+%      coeff=(d/distance)^2;
+%      distance=10km by default but can be specified
+%
+%   Usage:
+%      md=ThicknessCorrection(md,varargin);
+%
+%   Example:
+%      md=ThicknessCorrection(md);
+%      md=ThicknessCorrection(md,15000);
+
+%initialize thickness with the observations, and get hydrostatic thickness from the dem
+thickness=md.geometry.thickness;
+thickness_hydro=md.geometry.surface/(1-md.materials.rho_ice/md.materials.rho_water);
+hydrostatic_ratio=zeros(size(md.geometry.thickness));
+
+%get nodes on ice sheet and on ice shelf
+pos_shelf=find(~md.mask.vertexongroundedice);
+pos_GL=intersect(unique(md.mesh.elements(find(md.mask.elementongroundedice),:)),unique(md.mesh.elements(find(md.mask.elementonfloatingice),:)));
+debug=(length(pos_shelf)>50000);
+
+%check that there is a GL
+if isempty(pos_GL)
+	error('ThicknessCorrection error message: no grounding line has been detected. Check the model mask');
+end
+
+%get distance
+if nargin==2,
+	distance=varargin{1};
+else
+	distance=10000;
+end
+
+%modify thickness
+if (debug), fprintf('%s','      correction progress:   0.00 %'); end
+for i=1:length(pos_shelf)
+
+	if (debug & mod(i,100)==0),
+		fprintf('\b\b\b\b\b\b\b%5.2f%s',i/length(pos_shelf)*100,' %');
+	end
+
+	%search the node on ice sheet the closest to i
+	[d posd]=min(sqrt((md.mesh.x(pos_shelf(i))-md.mesh.x(pos_GL)).^2+(md.mesh.y(pos_shelf(i))-md.mesh.y(pos_GL)).^2));
+
+	if d>distance,
+
+		%if d > 15km, hydrostatic equilibrium
+		hydrostatic_ratio(pos_shelf(i))=1;
+		thickness(pos_shelf(i))=thickness_hydro(pos_shelf(i));
+
+	else
+
+		%else: quadratic combination of hydrostatic equilibrium and observations
+		hydrostatic_ratio(pos_shelf(i))=(d/distance)^2;
+		thickness(pos_shelf(i))=(1-hydrostatic_ratio(pos_shelf(i)))*thickness(pos_shelf(i))+hydrostatic_ratio(pos_shelf(i))*thickness_hydro(pos_shelf(i));
+
+	end
+end
+if (debug), fprintf('\b\b\b\b\b\b\b%5.2f%s\n',100,' %'); end
+
+%check the computed thickness
+minth=1/(1-md.materials.rho_ice/md.materials.rho_water);
+pos=find(isnan(thickness) | (thickness<=0));
+thickness(pos)=minth;
+hydrostatic_ratio(pos)=-1;
+
+%change bed to take into account the changes in thickness
+md.geometry.thickness=thickness;
+md.geometry.hydrostatic_ratio=hydrostatic_ratio;
+md.geometry.bed=md.geometry.surface-md.geometry.thickness;
Index: /issm/trunk-jpl-damage/src/m/model/WriteData.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/WriteData.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/WriteData.m	(revision 11330)
@@ -0,0 +1,260 @@
+function WriteData(fid,varargin)
+%WRITEDATA - write model field in binary file
+%
+%   Usage:
+%      WriteData(fid,varargin);
+
+%process options
+options=pairoptions(varargin{:});
+
+%Get data properties
+if exist(options,'object');
+	%This is a object field, construct enum and data
+	obj       = getfieldvalue(options,'object');
+	fieldname = getfieldvalue(options,'fieldname');
+	classname = class(obj);
+
+	enum      = BuildEnum([classname '_' fieldname]);
+	data      = obj.(fieldname);
+else
+	%No processing required
+	data = getfieldvalue(options,'data');
+	enum = getfieldvalue(options,'enum');
+end
+format  = getfieldvalue(options,'format');
+mattype = getfieldvalue(options,'mattype',0);    %only required for matrices
+
+%Process sparse matrices
+if issparse(data),
+	data=full(data);
+end
+
+%Step 1: write the enum to identify this record uniquely
+fwrite(fid,enum,'int'); 
+
+%Step 2: write the data itself.
+if     strcmpi(format,'Boolean'),% {{{
+	if(numel(data)~=1), error(['field ' field ' 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 ' field ' cannot be marshalled as it has more than one element!']); end
+
+	%first write length of record
+	fwrite(fid,8+4,'int');  %1 double+code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write double
+	fwrite(fid,data,'double'); 
+	% }}}
+elseif strcmpi(format,'String'), % {{{
+	%first write length of record
+	fwrite(fid,length(data)+4+4,'int');  %string + string size + code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write string
+	fwrite(fid,length(data),'int'); 
+	fwrite(fid,data,'char'); 
+	% }}}
+elseif strcmpi(format,'BooleanMat'), % {{{
+
+	%Get size
+	s=size(data);
+	%if matrix = NaN, then do not write anything
+	if (s(1)==1 & s(2)==1 & isnan(data)),
+		s(1)=0; s(2)=0;
+	end
+
+	%first write length of record
+	fwrite(fid,4+4+8*s(1)*s(2)+4+4,'int');  %2 integers (32 bits) + the double matrix + code + matrix type
+
+	%write data code and matrix type: 
+	fwrite(fid,FormatToCode(format),'int'); 
+	fwrite(fid,mattype,'int');
+
+	%now write matrix
+	fwrite(fid,s(1),'int'); 
+	fwrite(fid,s(2),'int'); 
+	if s(1)*s(2),
+		fwrite(fid,data','double'); %get to the "c" convention, hence the transpose
+	end
+	% }}}
+elseif strcmpi(format,'IntMat'), % {{{
+
+	%Get size
+	s=size(data);
+	%if matrix = NaN, then do not write anything
+	if (s(1)==1 & s(2)==1 & isnan(data)),
+		s(1)=0; s(2)=0;
+	end
+
+	%first write length of record
+	fwrite(fid,4+4+8*s(1)*s(2)+4+4,'int');  %2 integers (32 bits) + the double matrix + code + matrix type
+
+	%write data code and matrix type: 
+	fwrite(fid,FormatToCode(format),'int'); 
+	fwrite(fid,mattype,'int');
+
+	%now write matrix
+	fwrite(fid,s(1),'int'); 
+	fwrite(fid,s(2),'int'); 
+	if s(1)*s(2),
+		fwrite(fid,data','double'); %get to the "c" convention, hence the transpose
+	end
+	% }}}
+elseif strcmpi(format,'DoubleMat'), % {{{
+
+	%Get size
+	s=size(data);
+	%if matrix = NaN, then do not write anything
+	if (s(1)==1 & s(2)==1 & isnan(data)),
+		s(1)=0; s(2)=0;
+	end
+
+	%first write length of record
+	fwrite(fid,4+4+8*s(1)*s(2)+4+4,'int');  %2 integers (32 bits) + the double matrix + code + matrix type
+
+	%write data code and matrix type: 
+	fwrite(fid,FormatToCode(format),'int'); 
+	fwrite(fid,mattype,'int');
+
+	%now write matrix
+	fwrite(fid,s(1),'int'); 
+	fwrite(fid,s(2),'int'); 
+	if s(1)*s(2),
+		fwrite(fid,data','double'); %get to the "c" convention, hence the transpose
+	end
+	% }}}
+elseif strcmpi(format,'MatArray'), % {{{
+
+	numrecords=numel(data);
+
+	%first get length of record
+	recordlength=4+4; %number of records + code
+	for i=1:numrecords,
+		matrix=data{i};
+		s=size(matrix);
+		recordlength=recordlength+4*2+... %row and col of matrix
+			s(1)*s(2)*8; %matrix of doubles
+	end
+
+	%write length of record
+	fwrite(fid,recordlength,'int'); 
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%write data, first number of records
+	fwrite(fid,numrecords,'int'); 
+
+	%write each matrix: 
+	for i=1:numrecords,
+		matrix=data{i};
+		s=size(matrix);
+		fwrite(fid,s(1),'int'); 
+		fwrite(fid,s(2),'int'); 
+		fwrite(fid,matrix','double');
+	end
+	% }}}
+elseif strcmpi(format,'StringArray'), % {{{
+
+	%first get length of string array: 
+	num=numel(data);
+	%now get length of record: 
+	recordlength=4+4; %for length of array + code
+	for i=1:num,
+		string=data{i};
+		recordlength=recordlength+4+length(string); %for each string
+	end
+
+	%write length of record
+	fwrite(fid,recordlength,'int'); 
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write length of string array
+	fwrite(fid,num,'int'); 
+
+	%now write the strings
+	for i=1:num,
+		string=data{i};
+		fwrite(fid,length(string),'int'); 
+		fwrite(fid,string,'char'); 
+	end
+	% }}}
+else  % {{{
+	error(['WriteData error message: data type: ' num2str(format) ' not supported yet! (' EnumToString(enum) ')']);
+end % }}}
+end
+
+function enum=BuildEnum(string) % {{{
+%BUILDENUM - build enum out of string
+%
+%   Usage:
+%      enum=BuildEnum(string)
+
+	if findstr(string,'_'),
+		indices=findstr(string,'_');
+		for i=1:length(indices),
+			string(indices(i)+1)=upper(string(indices(i)+1));
+		end
+		string(indices)=[];
+	end
+
+	%take first letter of string and make it uppercase: 
+	string(1)=upper(string(1));
+
+	%Get Enum
+	enum=eval([string 'Enum();']); 
+end % }}}
+function code=FormatToCode(format) % {{{1
+%This routine takes the format string, and hardcodes it into an integer, which 
+%is passed along the record, in order to identify the nature of the dataset being 
+%sent.
+	if     strcmpi(format,'Boolean'),
+		code=1;
+	elseif strcmpi(format,'Integer'), 
+		code=2;
+	elseif strcmpi(format,'Double'), 
+		code=3;
+	elseif strcmpi(format,'String'), 
+		code=4;
+	elseif strcmpi(format,'BooleanMat'),
+		code=5;
+	elseif strcmpi(format,'IntMat'),
+		code=6;
+	elseif strcmpi(format,'DoubleMat'),
+		code=7;
+	elseif strcmpi(format,'MatArray'), 
+		code=8;
+	elseif strcmpi(format,'StringArray'),
+		code=9;
+	else 
+		error('FormatToCode error message: data type not supported yet!');
+	end
+end% }}}
Index: /issm/trunk-jpl-damage/src/m/model/addnote.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/addnote.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/addnote.m	(revision 11330)
@@ -0,0 +1,31 @@
+function md=addnote(md,string)
+%ADDNOTE - add a note to the existing model notes field
+%
+%   Usage:
+%      md=addnote(md,string);
+%
+%   Example:
+%      md=addnote(md,'Pine Island, Geometry of 2007');
+
+if (nargin~=2) & (nargout~=1),
+	help addnote
+end
+
+if ~ischar(string),
+	error('addnote error message: second input argument should be a string');
+end
+notes=md.miscellaneous.notes;
+
+if ischar(notes),
+	newnotes=cell(2,1);
+	newnotes(1)={notes};
+	newnotes(2)={string};
+else
+	newnotes=cell(length(notes)+1,1);
+	for i=1:length(notes),
+		newnotes(i)=notes(i);
+	end
+	newnotes(length(notes)+1)={string};
+end
+
+md.miscellaneous.notes=newnotes;
Index: /issm/trunk-jpl-damage/src/m/model/averageconnectivity.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/averageconnectivity.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/averageconnectivity.m	(revision 11330)
@@ -0,0 +1,11 @@
+function conn=averageconnectivity(md)
+%AVERAGECONNECTIVITY - computes the average connectivity of a model
+%
+%   Usage:
+%      connectivity=averageconnectivity(md);
+
+nnz=0;
+for i=1:md.mesh.numberofvertices,
+	nnz=nnz+length(find(md.mesh.elements==i));
+end
+conn=nnz/md.mesh.numberofvertices;
Index: /issm/trunk-jpl-damage/src/m/model/averaging.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/averaging.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/averaging.m	(revision 11330)
@@ -0,0 +1,62 @@
+function average=averaging(md,data,iterations)
+%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
+%
+%   Usage:
+%      smoothdata=averaging(md,data,iterations)
+%
+%   Examples:
+%      velsmoothed=averaging(md,md.initialization.vel,4);
+%      pressure=averaging(md,md.initialization.pressure,0);
+
+if length(data)~=md.mesh.numberofelements & length(data)~=md.mesh.numberofvertices
+	error('averaging error message: data not supported yet');
+end
+
+%initialization
+weights=zeros(md.mesh.numberofvertices,1);
+data=data(:);
+
+%load some variables (it is much faster if the variab;es are loaded from md once for all)
+index=md.mesh.elements;
+numberofnodes=md.mesh.numberofvertices;
+numberofelements=md.mesh.numberofelements;
+
+%build some variables
+line=index(:);
+if md.mesh.dimension==3
+	rep=6;
+	areas=GetAreas(index,md.mesh.x,md.mesh.y,md.mesh.z);
+else
+	rep=3;
+	areas=GetAreas(index,md.mesh.x,md.mesh.y);
+end
+summation=1/rep*ones(rep,1);
+linesize=rep*numberofelements;
+
+%update weights that holds the volume of all the element holding the node i
+weights=sparse(line,ones(linesize,1),repmat(areas,rep,1),numberofnodes,1);
+
+%initialization
+if length(data)==numberofelements
+	average_node=sparse(line,ones(linesize,1),repmat(areas.*data,rep,1),numberofnodes,1);
+	average_node=average_node./weights;
+else
+	average_node=data;
+end
+
+%loop over iteration
+for i=1:iterations
+	average_el=average_node(index)*summation;
+	average_node=sparse(line,ones(linesize,1),repmat(areas.*average_el,rep,1),numberofnodes,1);
+	average_node=average_node./weights;
+end
+
+%return output as a full matrix (C code do not like sparse matrices)
+average=full(average_node);
Index: /issm/trunk-jpl-damage/src/m/model/basalstress.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/basalstress.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/basalstress.m	(revision 11330)
@@ -0,0 +1,22 @@
+function [bx by b]=basalstress(md)
+%BASALSTRESS - compute basal stress from basal drag and geometric information. 
+%
+%   Usage:
+%      [bx by b]=basalstress(md);
+%
+%   See also: plot_basaldrag
+
+
+%compute exponents
+s=averaging(md,1./md.friction.p,0);
+r=averaging(md,md.friction.q./md.friction.p,0);
+
+%compute horizontal velocity
+ub=sqrt(md.initialization.vx.^2+md.initialization.vy.^2)/md.constants.yts;
+ubx=md.initialization.vx/md.constants.yts;
+uby=md.initialization.vy/md.constants.yts;
+
+%compute basal drag
+bx=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed)).^r.*(md.friction.coefficient).^2.*ubx.^s;
+by=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed)).^r.*(md.friction.coefficient).^2.*uby.^s;
+b=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed)).^r.*(md.friction.coefficient).^2.*ub.^s;
Index: /issm/trunk-jpl-damage/src/m/model/basevert.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/basevert.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/basevert.m	(revision 11330)
@@ -0,0 +1,35 @@
+function wb=basevert(md)
+%BASEVERT - computes the basal vertical velcities
+%
+%   This routine computes the basal vertical velocities of ice shelves
+%   for 2d models only using the following formula:
+%   wb=rho_ice/rho_water*div(thickness*vel_horiz)+vel_horiz.grad(base)
+%
+%   Usage:
+%      wb=basevert(md);
+
+alpha=zeros(md.mesh.numberofelements,3);
+beta=zeros(md.mesh.numberofelements,3);
+gamma=zeros(md.mesh.numberofelements,3);
+
+for n=1:md.mesh.numberofelements
+	X=inv([md.mesh.x(md.mesh.elements(n,:)) md.mesh.y(md.mesh.elements(n,:)) ones(3,1)]);
+	alpha(n,:)=X(1,:);
+	beta(n,:)=X(2,:);
+	gamma(n,:)=X(3,:);
+end
+
+hu=md.geometry.thickness.*md.initialization.vx;
+hv=md.geometry.thickness.*md.initialization.vy;
+
+summation=[1;1;1];
+hux=(hu(md.mesh.elements).*alpha)*summation;
+hvy=(hv(md.mesh.elements).*beta)*summation;
+
+uelem=md.initialization.vx(md.mesh.elements)*summation/3;
+velem=md.initialization.vy(md.mesh.elements)*summation/3;
+
+dbdx=(md.geometry.bed(md.mesh.elements).*alpha)*summation;
+dbdy=(md.geometry.bed(md.mesh.elements).*beta)*summation;
+
+wb=-md.materials.rho_ice/md.materials.rho_water*(hux+hvy)+uelem.*dbdx+velem.*dbdy;
Index: /issm/trunk-jpl-damage/src/m/model/bedslope.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/bedslope.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/bedslope.m	(revision 11330)
@@ -0,0 +1,32 @@
+function [bx,by,b]=bedslope(md)
+%BEDSLOPE - compute the bed slope
+%
+%   Usage:
+%      [bx,by,s]=bedslope(md)
+
+%load some variables (it is much faster if the variab;es are loaded from md once for all) 
+if (md.mesh.dimension==2),
+	numberofelements=md.mesh.numberofelements;
+	numberofnodes=md.mesh.numberofvertices;
+	index=md.mesh.elements;
+	x=md.mesh.x; y=md.mesh.y;
+else
+	numberofelements=md.mesh.numberofelements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	index=md.mesh.elements2d;
+	x=md.mesh.x2d; y=md.mesh.y2d;
+end
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+
+summation=[1;1;1];
+bx=(md.geometry.bed(index).*alpha)*summation;
+by=(md.geometry.bed(index).*beta)*summation;
+b=sqrt(bx.^2+by.^2);
+
+if md.mesh.dimension==3,
+	bx=project3d(md,bx,'element');
+	by=project3d(md,by,'element');
+	b=sqrt(bx.^2+by.^2);
+end
Index: /issm/trunk-jpl-damage/src/m/model/collapse.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/collapse.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/collapse.m	(revision 11330)
@@ -0,0 +1,112 @@
+function md=collapse(md)
+%COLLAPSE - collapses a 3d mesh into a 2d mesh
+%
+%   This routine collapses a 3d model into a 2d model
+%   and collapses all the fileds of the 3d model by
+%   taking their depth-averaged values
+%
+%   Usage:
+%      md=collapse(md)
+%
+%   See also: EXTRUDE, MODELEXTRACT
+
+%Check that the model is really a 3d model
+if ~md.mesh.dimension==3,
+	error('collapse error message: only 3d mesh can be collapsed')
+end
+
+%Start with changing alle the fields from the 3d mesh 
+
+%drag is limited to nodes that are on the bedrock.
+md.friction.coefficient=project2d(md,md.friction.coefficient,1);
+
+%p and q (same deal, except for element that are on the bedrock: )
+md.friction.p=project2d(md,md.friction.p,1);
+md.friction.q=project2d(md,md.friction.q,1);
+
+%observations
+if ~isnan(md.inversion.vx_obs), md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers); end;
+if ~isnan(md.inversion.vy_obs), md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers); end;
+if ~isnan(md.inversion.vel_obs), md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers); end;
+if ~isnan(md.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;
+
+%bedinfo and surface info
+md.mesh.elementonbed=ones(md.mesh.numberofelements2d,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements2d,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices2d,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices2d,1);
+
+%elementstype
+if ~isnan(md.flowequation.element_equation)
+	md.flowequation.element_equation=project2d(md,md.flowequation.element_equation,1);
+end	
+
+%boundary conditions
+md.diagnostic.spcvx=project2d(md,md.diagnostic.spcvx,md.mesh.numberoflayers);
+md.diagnostic.spcvy=project2d(md,md.diagnostic.spcvy,md.mesh.numberoflayers);
+md.diagnostic.spcvz=project2d(md,md.diagnostic.spcvz,md.mesh.numberoflayers);
+md.prognostic.spcthickness=project2d(md,md.prognostic.spcthickness,md.mesh.numberoflayers);
+md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers);
+
+%Extrusion of Neumann BC
+if ~isnan(md.diagnostic.icefront),
+	numberofneumann2d=size(md.diagnostic.icefront,1)/md.mesh.numberoflayers;
+	md.diagnostic.icefront=[md.diagnostic.icefront(1:numberofneumann2d,1:2) md.diagnostic.icefront(1:numberofneumann2d,5:6)]; %Add two columns on the first layer 
+end
+
+%materials
+md.materials.rheology_B=DepthAverage(md,md.materials.rheology_B);
+md.materials.rheology_n=project2d(md,md.materials.rheology_n,1);
+
+%special for thermal modeling:
+md.basalforcings.melting_rate=project2d(md,md.basalforcings.melting_rate,1); 
+md.basalforcings.geothermalflux=project2d(md,md.basalforcings.geothermalflux,1); %bedrock only gets geothermal flux
+
+%update of connectivity matrix
+md.mesh.average_vertex_connectivity=25;
+
+%Collapse the mesh
+nodes2d=md.mesh.numberofvertices2d;
+elements2d=md.mesh.numberofelements2d;
+
+%parameters
+md.geometry.surface=project2d(md,md.geometry.surface,1);
+md.geometry.thickness=project2d(md,md.geometry.thickness,1);
+md.geometry.bed=project2d(md,md.geometry.bed,1);
+md.mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1);
+md.mask.elementonfloatingice=project2d(md,md.mask.elementonfloatingice,1);
+md.mask.vertexonfloatingice=project2d(md,md.mask.vertexonfloatingice,1);
+md.mask.elementongroundedice=project2d(md,md.mask.elementongroundedice,1);
+md.mask.vertexongroundedice=project2d(md,md.mask.vertexongroundedice,1);
+
+%Initialize with the 2d mesh
+md.mesh.x=md.mesh.x2d;
+md.mesh.y=md.mesh.y2d;
+md.mesh.z=zeros(size(md.mesh.x2d));
+md.mesh.numberofvertices=md.mesh.numberofvertices2d;
+md.mesh.numberofelements=md.mesh.numberofelements2d;
+md.mesh.elements=md.mesh.elements2d;
+
+%Keep a trace of lower and upper nodes
+md.mesh.lowervertex=NaN;
+md.mesh.uppervertex=NaN;
+
+%Remove old mesh 
+md.mesh.x2d=NaN;
+md.mesh.y2d=NaN;
+md.mesh.elements2d=NaN;
+md.mesh.numberofelements2d=md.mesh.numberofelements;
+md.mesh.numberofvertices2d=md.mesh.numberofvertices;
+md.mesh.numberoflayers=0;
+
+%Update mesh type
+md.mesh.dimension=2;
Index: /issm/trunk-jpl-damage/src/m/model/contourenvelope.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/contourenvelope.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/contourenvelope.m	(revision 11330)
@@ -0,0 +1,124 @@
+function segments=contourenvelope(md,varargin)
+%CONTOURENVELOPE - build a set of segments enveloping a contour .exp
+%
+%   Usage:
+%      segments=contourenvelope(md,varargin)
+%
+%   Example:
+%      segments=contourenvelope(md,'Stream.exp');
+%      segments=contourenvelope(md,md.mask.elementonfloatingice)
+%      segments=contourenvelope(md);
+
+%some checks
+if nargin>2,
+	help contourenvelope
+	error('contourenvelope error message: bad usage');
+end
+if nargin==2,
+	flags=varargin{1};
+
+	if ischar(flags),
+		file=flags;
+		file=varargin{1};
+		if ~exist(file),
+			error(['contourenvelope error message: file ' file ' not found']);
+		end
+		isfile=1;
+	elseif isnumeric(flags),
+		%do nothing for now
+		isfile=0;
+	else
+		error('contourenvelope error message:  second argument should a file or an elements flag');
+	end
+end
+
+%Now, build the connectivity tables for this mesh.
+%Computing connectivity
+if size(md.mesh.vertexconnectivity,1)~=md.mesh.numberofvertices,
+	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
+
+%get nodes inside profile
+mesh.elementconnectivity=md.mesh.elementconnectivity;
+if nargin==2,
+	if isfile,
+		%get flag list of elements and nodes inside the contour
+		nodein=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,file,'node',1);
+		elemin=(sum(nodein(md.mesh.elements),2)==size(md.mesh.elements,2));
+		%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(md.mesh.numberofvertices,1); 
+		elemin=zeros(md.mesh.numberofelements,1); 
+		
+		pos=find(flags); 
+		elemin(pos)=1;
+		nodein(md.mesh.elements(pos,:))=1;
+
+		%modify element connectivity
+		elemout=find(~elemin);
+		mesh.elementconnectivity(elemout,:)=0;
+		mesh.elementconnectivity(find(ismember(mesh.elementconnectivity,elemout)))=0;
+	end
+end
+
+%Find element on boundary
+%First: find elements on the boundary of the domain
+flag=mesh.elementconnectivity;
+if nargin==2,
+	flag(find(flag))=elemin(flag(find(flag)));
+end
+elementonboundary=double(prod(flag,2)==0 & sum(flag,2)>0);
+
+%Find segments on boundary
+pos=find(elementonboundary);
+num_segments=length(pos);
+segments=zeros(num_segments,3);
+count=1;
+
+for i=1:num_segments,
+	el1=pos(i);
+	els2=mesh.elementconnectivity(el1,find(mesh.elementconnectivity(el1,:)));
+	if length(els2)>1,
+		flag=intersect(md.mesh.elements(els2(1),:),md.mesh.elements(els2(2),:));
+		nods1=md.mesh.elements(el1,:);
+		nods1(find(nods1==flag))=[];
+		segments(count,:)=[nods1 el1];
+
+		ord1=find(nods1(1)==md.mesh.elements(el1,:));
+		ord2=find(nods1(2)==md.mesh.elements(el1,:));
+
+		%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=md.mesh.elements(el1,:);
+		flag=setdiff(nods1,md.mesh.elements(els2,:));
+		for j=1:3,
+			nods=nods1; nods(j)=[];
+			if any(ismember(flag,nods)),
+				segments(count,:)=[nods el1];
+				ord1=find(nods(1)==md.mesh.elements(el1,:));
+				ord2=find(nods(2)==md.mesh.elements(el1,:));
+				if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+					temp=segments(count,1);
+					segments(count,1)=segments(count,2);
+					segments(count,2)=temp;
+				end
+				segments(count,1:2)=fliplr(segments(count,1:2));
+				count=count+1;
+			end
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/contourmassbalance.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/contourmassbalance.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/contourmassbalance.m	(revision 11330)
@@ -0,0 +1,45 @@
+function dhdt=contourmassbalance(md,file)
+%CONTOURMASSBALANCE - compute the mass balance on a given profile
+%
+%   Usage:
+%      dhdt=contourmassbalance(md,file)
+
+%some checks
+if nargin~=2,
+	help contourmassbalance
+	error('contourmassbalance error message: bad usage');
+end
+if ((length(md.initialization.vx)~=md.mesh.numberofvertices)|(length(md.initialization.vy)~=md.mesh.numberofvertices))
+	error(['thicknessevolution error message: vx and vy should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+if ~exist(file),
+	error(['thicknessevolution error message: file ' file ' not found']);
+end
+
+%Get segments enveloping contour
+segments=contourenvelope(md,file);
+%md.diagnostic.icefront=segments; plotmodel(md,'data','pressureload','expdisp',file);
+
+%get flag list of elements and nodes inside the contour
+nodein=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,file,'node',1);
+elemin=(sum(nodein(md.mesh.elements),2)==size(md.mesh.elements,2));
+
+%conputing Mass flux
+x=md.mesh.x;
+y=md.mesh.y;
+vx=mean(md.initialization.vx(segments(:,1:end-1)),2);
+vy=mean(md.initialization.vy(segments(:,1:end-1)),2);
+H=mean(md.geometry.thickness(segments(:,1:end-1)),2);
+nx=cos(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+ny=sin(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+L=sqrt((x(segments(:,1))-x(segments(:,2))).^2+(y(segments(:,2))-y(segments(:,1))).^2);
+flux = - md.materials.rho_ice*sum(L.*H.*(vx.*nx+vy.*ny)); %outflux is negative!
+disp(['mass outflux on ' file ' = ' num2str(-flux/10^9) ' Gt/yr']);
+areas=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+dhdt=flux/(sum(areas(find(elemin)))*md.materials.rho_ice);
+disp(['dhdt on ' file ' (Flux  method) = ' num2str(dhdt) ' m/yr']);
+
+dhdt=thicknessevolution(md);
+in=find(elemin);
+dhdt=sum(dhdt(in).*areas(in))/sum(areas(in));
+disp(['dhdt on ' file ' (divHV method) = ' num2str(dhdt) ' m/yr']);
Index: /issm/trunk-jpl-damage/src/m/model/display/fielddisplay.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/display/fielddisplay.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/display/fielddisplay.m	(revision 11330)
@@ -0,0 +1,154 @@
+function fielddisplay(md,name,comment)
+%FIELDDISPLAY - display model field
+%
+%   Usage:
+%      fielddisplay(md,offset,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),
+		if ~isempty(fields(field))
+			displayunit(offset,name,'(structure)',comment),
+			struct_display(field,[offset '   ']),
+		else
+			displayunit(offset,name,'N/A',comment),
+		end
+
+	%cell
+	elseif iscell(field),
+		cell_display(offset,name,field,comment),
+
+	else
+		displayunit(offset,name,'not displayed',comment),
+
+	end
+end%}}}
+
+function struct_display(structure,offset) % {{{
+
+	structure_fields=fields(structure);
+
+	for i=1:length(structure_fields),
+
+		%get current field
+		field=structure.(structure_fields{i});
+
+		%recursive call if necessary
+		if isstruct(field),
+			displayunit(offset,structure_fields{i},'(structure)',''),
+			struct_display(field,[offset '   ']);
+
+		%display value
+		else
+			parsedisplay(offset,structure_fields{i},field,'');
+		end
+	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 supportet yet');
+		end
+	end
+end% }}}
Index: /issm/trunk-jpl-damage/src/m/model/display/fielddisplay2.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/display/fielddisplay2.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/display/fielddisplay2.m	(revision 11330)
@@ -0,0 +1,14 @@
+function fielddisplay2(md,name,comment)
+%FIELDDISPLAY2 - display model field
+%
+%   Usage:
+%      fielddisplay2(md,offset,name,comment)
+
+	%get field
+	field=md.(name);
+
+	if length(name)>23,
+		name=[name(1:20) '...'];
+	end
+
+	disp(sprintf('%s%-23s -- %s','      ',name,comment));
Index: /issm/trunk-jpl-damage/src/m/model/divergence.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/divergence.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/divergence.m	(revision 11330)
@@ -0,0 +1,27 @@
+function div=divergence(md,a,b)
+%DIVERGENCE - divergence of [a;b] vector, using model's triangulation.
+%
+%   Usage:
+%      div=divergence(md,a,b)
+
+if (md.mesh.dimension==2),
+	numberofelements=md.mesh.numberofelements;
+	numberofnodes=md.mesh.numberofvertices;
+	index=md.mesh.elements;
+	x=md.mesh.x; y=md.mesh.y; z=md.mesh.z;
+else
+	numberofelements=md.mesh.numberofelements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	index=md.mesh.elements2d;
+	x=md.mesh.x2d; y=md.mesh.y2d;
+end
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+
+summation=[1;1;1];
+dx=(a(index).*alpha)*summation;
+dy=(b(index).*beta)*summation;
+
+div=dx+dy;
+div=averaging(md,div,1);
Index: /issm/trunk-jpl-damage/src/m/model/drivingstress.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/drivingstress.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/drivingstress.m	(revision 11330)
@@ -0,0 +1,18 @@
+function [px,py,pmag]=drivingstress(md)
+%DRIVINGSTRESS -  evaluates the driving stress
+%
+%   The driving stress is computed according to the following formula: 
+%   driving stress= rho_ice*g*H*slope
+%
+%   Usage:
+%      [Fx,Fy,Fmag]=drivingstress(md)
+
+%Get slope
+[sx,sy,s]=slope(md);
+
+%Average thickness over elements
+thickness_bar=(md.geometry.thickness(md.mesh.elements(:,1))+md.geometry.thickness(md.mesh.elements(:,2))+md.geometry.thickness(md.mesh.elements(:,3)))/3;
+
+px=md.materials.rho_ice*md.constants.g*thickness_bar.*sx;
+py=md.materials.rho_ice*md.constants.g*thickness_bar.*sy;
+pmag=sqrt(px.^2+py.^2);
Index: /issm/trunk-jpl-damage/src/m/model/effectivepressure.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/effectivepressure.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/effectivepressure.m	(revision 11330)
@@ -0,0 +1,12 @@
+function Neff=effectivepressure(md)
+%EFFECTIVEPRESSURE - compute effective pressure
+%
+%   Usage:
+%      Neff=effectivepressure(md)
+%
+%   Example:
+%      Neff=effectivepressure(md)
+
+Neff=md.materials.rho_ice*md.constants.g*md.geometry.thickness+md.materials.rho_ice*md.constants.g*md.geometry.bed;
+pos=find(Neff<0);
+Neff(pos)=0;
Index: /issm/trunk-jpl-damage/src/m/model/extrude.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/extrude.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/extrude.m	(revision 11330)
@@ -0,0 +1,233 @@
+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
+	list=varargin{1};
+	if any(list<0) | any(list>1),
+		error('extrusioncoefficients must be between 0 and 1');
+	end
+	extrusionlist=sort(unique([list(:);0;1]));
+	numlayers=length(extrusionlist);
+elseif nargin==3, %one polynomial law
+	if varargin{2}<=0,
+		help extrude;
+		error('extrusionexponent must be >=0');
+	end
+	numlayers=varargin{1};
+	extrusionlist=((0:1:numlayers-1)/(numlayers-1)).^varargin{2};
+elseif nargin==4, %two polynomial laws
+	numlayers=varargin{1};
+	lowerexp=varargin{2};
+	upperexp=varargin{3};
+
+	if varargin{2}<=0 | varargin{3}<=0,
+		help extrude;
+		error('lower and upper extrusionexponents must be >=0');
+	end
+
+	lowerextrusionlist=[(0:2/(numlayers-1):1).^lowerexp]/2;
+	upperextrusionlist=[(0:2/(numlayers-1):1).^upperexp]/2;
+	extrusionlist=sort(unique([lowerextrusionlist 1-upperextrusionlist]));
+
+end
+
+if numlayers<2,
+	error('number of layers should be at least 2');
+end
+if md.mesh.dimension==3,
+	error('Cannot extrude a 3d mesh (extrude cannot be called more than once)');
+end
+
+%Initialize with the 2d mesh
+x3d=[]; 
+y3d=[];
+z3d=[];  %the lower node is on the bed
+thickness3d=md.geometry.thickness; %thickness and bed for these nodes
+bed3d=md.geometry.bed;
+
+%Create the new layers
+for i=1:numlayers,
+	x3d=[x3d; md.mesh.x]; 
+	y3d=[y3d; md.mesh.y];
+	%nodes are distributed between bed and surface accordingly to the given exponent
+	z3d=[z3d; bed3d+thickness3d*extrusionlist(i)]; 
+end
+number_nodes3d=size(x3d,1); %number of 3d nodes for the non extruded part of the mesh
+
+%Extrude elements 
+elements3d=[];
+for i=1:numlayers-1,
+	elements3d=[elements3d;[md.mesh.elements+(i-1)*md.mesh.numberofvertices md.mesh.elements+i*md.mesh.numberofvertices]]; %Create the elements of the 3d mesh for the non extruded part
+end
+number_el3d=size(elements3d,1); %number of 3d nodes for the non extruded part of the mesh
+
+%Keep a trace of lower and upper nodes
+mesh.lowervertex=NaN*ones(number_nodes3d,1);
+mesh.uppervertex=NaN*ones(number_nodes3d,1);
+mesh.lowervertex(md.mesh.numberofvertices+1:end)=1:(numlayers-1)*md.mesh.numberofvertices;
+mesh.uppervertex(1:(numlayers-1)*md.mesh.numberofvertices)=md.mesh.numberofvertices+1:number_nodes3d;
+md.mesh.lowervertex=mesh.lowervertex;
+md.mesh.uppervertex=mesh.uppervertex;
+
+%same for lower and upper elements
+mesh.lowerelements=NaN*ones(number_el3d,1);
+mesh.upperelements=NaN*ones(number_el3d,1);
+mesh.lowerelements(md.mesh.numberofelements+1:end)=1:(numlayers-2)*md.mesh.numberofelements;
+mesh.upperelements(1:(numlayers-2)*md.mesh.numberofelements)=md.mesh.numberofelements+1:(numlayers-1)*md.mesh.numberofelements;
+md.mesh.lowerelements=mesh.lowerelements;
+md.mesh.upperelements=mesh.upperelements;
+
+%Save old mesh 
+md.mesh.x2d=md.mesh.x;
+md.mesh.y2d=md.mesh.y;
+md.mesh.elements2d=md.mesh.elements;
+md.mesh.numberofelements2d=md.mesh.numberofelements;
+md.mesh.numberofvertices2d=md.mesh.numberofvertices;
+
+%Update mesh type
+md.mesh.dimension=3;
+
+%Build global 3d mesh 
+md.mesh.elements=elements3d;
+md.mesh.x=x3d;
+md.mesh.y=y3d;
+md.mesh.z=z3d;
+md.mesh.numberofelements=number_el3d;
+md.mesh.numberofvertices=number_nodes3d;
+md.mesh.numberoflayers=numlayers;
+
+%Ok, now deal with the other fields from the 2d mesh:
+
+%drag coefficient is limited to nodes that are on the bedrock.
+md.friction.coefficient=project3d(md,'vector',md.friction.coefficient,'type','node','layer',1);
+
+%p and q (same deal, except for element that are on the bedrock: )
+md.friction.p=project3d(md,'vector',md.friction.p,'type','element');
+md.friction.q=project3d(md,'vector',md.friction.q,'type','element');
+
+%observations
+md.inversion.vx_obs=project3d(md,'vector',md.inversion.vx_obs,'type','node');
+md.inversion.vy_obs=project3d(md,'vector',md.inversion.vy_obs,'type','node');
+md.inversion.vel_obs=project3d(md,'vector',md.inversion.vel_obs,'type','node');
+md.surfaceforcings.mass_balance=project3d(md,'vector',md.surfaceforcings.mass_balance,'type','node');
+md.surfaceforcings.accumulation_rate=project3d(md,'vector',md.surfaceforcings.accumulation_rate,'type','node');
+md.surfaceforcings.ablation_rate=project3d(md,'vector',md.surfaceforcings.ablation_rate,'type','node');
+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;
+
+%bedinfo and surface info
+md.mesh.elementonbed=project3d(md,'vector',ones(md.mesh.numberofelements2d,1),'type','element','layer',1);
+md.mesh.elementonsurface=project3d(md,'vector',ones(md.mesh.numberofelements2d,1),'type','element','layer',md.mesh.numberoflayers-1);
+md.mesh.vertexonbed=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',1);
+md.mesh.vertexonsurface=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',md.mesh.numberoflayers);
+
+%elementstype
+if ~isnan(md.flowequation.element_equation)
+	oldelements_type=md.flowequation.element_equation;
+	md.flowequation.element_equation=zeros(number_el3d,1);
+	md.flowequation.element_equation=project3d(md,'vector',oldelements_type,'type','element');
+end
+
+%verticestype
+if ~isnan(md.flowequation.vertex_equation)
+	oldvertices_type=md.flowequation.vertex_equation;
+	md.flowequation.vertex_equation=zeros(number_nodes3d,1);
+	md.flowequation.vertex_equation=project3d(md,'vector',oldvertices_type,'type','node');
+end
+md.flowequation.bordermacayeal=project3d(md,'vector',md.flowequation.bordermacayeal,'type','node');
+md.flowequation.borderpattyn=project3d(md,'vector',md.flowequation.borderpattyn,'type','node');
+md.flowequation.borderstokes=project3d(md,'vector',md.flowequation.borderstokes,'type','node');
+
+%boundary conditions
+md.diagnostic.spcvx=project3d(md,'vector',md.diagnostic.spcvx,'type','node');
+md.diagnostic.spcvy=project3d(md,'vector',md.diagnostic.spcvy,'type','node');
+md.diagnostic.spcvz=project3d(md,'vector',md.diagnostic.spcvz,'type','node');
+md.thermal.spctemperature=project3d(md,'vector',md.thermal.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',NaN);
+md.prognostic.spcthickness=project3d(md,'vector',md.prognostic.spcthickness,'type','node');
+md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node');
+md.diagnostic.referential=project3d(md,'vector',md.diagnostic.referential,'type','node');
+
+%in 3d, pressureload: [node1 node2 node3 node4 element]
+pressureload_layer1=[md.diagnostic.icefront(:,1:2)  md.diagnostic.icefront(:,2)+md.mesh.numberofvertices2d  md.diagnostic.icefront(:,1)+md.mesh.numberofvertices2d  md.diagnostic.icefront(:,3:4)]; %Add two columns on the first layer 
+pressureload=[];
+for i=1:numlayers-1,
+	pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d pressureload_layer1(:,6)];
+end
+md.diagnostic.icefront=pressureload;
+
+%connectivity
+md.mesh.elementconnectivity=repmat(md.mesh.elementconnectivity,numlayers-1,1);
+md.mesh.elementconnectivity(find(md.mesh.elementconnectivity==0))=NaN;
+for i=2:numlayers-1,
+	md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)...
+	=md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)+md.mesh.numberofelements2d;
+end
+md.mesh.elementconnectivity(find(isnan(md.mesh.elementconnectivity)))=0;
+
+%materials
+md.materials.rheology_B=project3d(md,'vector',md.materials.rheology_B,'type','node');
+md.materials.rheology_n=project3d(md,'vector',md.materials.rheology_n,'type','element');
+
+%parameters
+md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node');
+md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node');
+md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node');
+md.geometry.bed=project3d(md,'vector',md.geometry.bed,'type','node');
+md.geometry.bathymetry=project3d(md,'vector',md.geometry.bathymetry,'type','node');
+md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node');
+md.mask.elementonfloatingice=project3d(md,'vector',md.mask.elementonfloatingice,'type','element');
+md.mask.vertexonfloatingice=project3d(md,'vector',md.mask.vertexonfloatingice,'type','node');
+md.mask.elementongroundedice=project3d(md,'vector',md.mask.elementongroundedice,'type','element');
+md.mask.vertexongroundedice=project3d(md,'vector',md.mask.vertexongroundedice,'type','node');
+md.mask.elementonwater=project3d(md,'vector',md.mask.elementonwater,'type','element');
+md.mask.vertexonwater=project3d(md,'vector',md.mask.vertexonwater,'type','node');
+if ~isnan(md.inversion.cost_functions_coefficients),md.inversion.cost_functions_coefficients=project3d(md,'vector',md.inversion.cost_functions_coefficients,'type','node');end;
+
+%Put lithostatic pressure is there is an existing pressure
+if ~isnan(md.initialization.pressure),
+	md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z);
+end
+
+%special for thermal modeling:
+md.basalforcings.melting_rate=project3d(md,'vector',md.basalforcings.melting_rate,'type','node','layer',1); 
+if ~isnan(md.basalforcings.geothermalflux)
+	md.basalforcings.geothermalflux=project3d(md,'vector',md.basalforcings.geothermalflux,'type','node','layer',1); %bedrock only gets geothermal flux
+end
+
+%increase connectivity if less than 25:
+if md.mesh.average_vertex_connectivity<=25,
+	md.mesh.average_vertex_connectivity=100;
+end
Index: /issm/trunk-jpl-damage/src/m/model/graddetection.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/graddetection.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/graddetection.m	(revision 11330)
@@ -0,0 +1,33 @@
+function [direction,direction2]=graddetection(md)
+%GRADDETECTION detect gradient of control method between steps nsteps+1 and nsteps
+%
+% Usage: direction=graddetection(md);
+
+%keep copy of md: 
+md2=md;
+
+%solve first batch of control methods, with given settings.
+md2=solve(md2,'solution_type','DiagnosticAnalysis');
+
+%record final optimized parameter. 
+parameter1=md2.results.DiagnosticAnalysis.parameter;
+
+%plug optimized parameter in model. 
+md2.(EnumToModelField(md2.results.DiagnosticAnalysis.inversion.control_parameters))=parameter1;
+
+%put nsteps to 1: 
+md2.nsteps=1;
+md2.optscal=md2.optscal(end)*ones(md2.nsteps,1);
+md2.fit=md2.fit(end)*ones(md2.nsteps,1);
+md2.cm_jump=md2.cm_jump(end)*ones(md2.nsteps,1);
+md2.maxiter=md2.maxiter(end)*ones(md2.nsteps,1);
+
+%rerun control method with optimized parameter, only for 1 more step.
+md2=solve(md2,'solution_type','DiagnosticAnalysis');
+
+%get optimized parameter after 1 more step. 
+parameter2=md2.results.DiagnosticAnalysis.parameter;
+
+%return relative  difference between nsteps+1 and nsteps;
+direction=(parameter2-parameter1)./parameter1;
+direction2=(parameter2-parameter1);
Index: /issm/trunk-jpl-damage/src/m/model/ismodelselfconsistent.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/ismodelselfconsistent.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/ismodelselfconsistent.m	(revision 11330)
@@ -0,0 +1,40 @@
+function ismodelselfconsistent(md),
+%ISMODELSELFCONSISTENT - check that model forms a closed form solvable problem.
+%
+%   Usage:
+%      ismodelselfconsistent(md),
+
+%initialize consistency as true
+modelconsistency(true);
+
+%Get solution and associated analyses
+solution=md.private.solution;
+[analyses,numanalyses]=AnalysisConfiguration(solution);
+
+%Go through al 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))
+		checkmessage(['field ''' char(field) ''' is not an object']);
+	end
+
+	%Check consistency of the object
+	if verLessThan('matlab', '7.6')
+		checkconsistency(md.(field),md,solution,analyses);
+	else
+		md.(field).checkconsistency(md,solution,analyses);
+	end
+end
+
+%error message if mode is not consistent
+if modelconsistency==false,
+	error(' ');
+end
Index: /issm/trunk-jpl-damage/src/m/model/kmlimagesc.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/kmlimagesc.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/kmlimagesc.m	(revision 11330)
@@ -0,0 +1,67 @@
+function kmlimagesc(md,fieldname,varargin)
+%KMLIMAGESC - create lat,long kml image
+%
+%   Usage:
+%      kmlimagesc(md,field,options);
+%   Options: 
+%      'hemisphere': default +1;
+%      'central_meridian: 45 for Greenland and 0 for Antarctica
+%      'standard_parallel: 70 for Greenland and 71 for Antarctica
+%      'posting': default .1 degree
+%
+
+%process varargin for options: 
+options=pairoptions(varargin{:});
+
+%recover field: 
+field=md.(fieldname);
+
+%recover some options, and set defaults
+fontsize=getfieldvalue(options,'fontsize',12);
+posting=getfieldvalue(options,'posting',.1);
+minlong=getfieldvalue(options,'minlong',min(md.mesh.long));
+maxlong=getfieldvalue(options,'maxlong',max(md.mesh.long));
+minlat=getfieldvalue(options,'minlat',min(md.mesh.lat));
+maxlat=getfieldvalue(options,'maxlat',max(md.mesh.lat));
+minfield=getfieldvalue(options,'minfield',min(field));
+maxfield=getfieldvalue(options,'maxfield',max(field));
+
+%do we have hemisphere setup?:
+if ~isstr(md.mesh.hemisphere),
+	error('md.mesh.hemisphere should be ''s'' or ''n''');
+end
+
+if strcmpi(md.mesh.hemisphere,'s'),
+	hemisphere=1;
+	central_meridian=getfieldvalue(options,'central_meridian',45);
+	standard_parallel=getfieldvalue(options,'standard_parallel',70);
+elseif strcmpi(md.mesh.hemisphere,'n'),
+	hemisphere=-1;
+	central_meridian=getfieldvalue(options,'central_meridian',0);
+	standard_parallel=getfieldvalue(options,'standard_parallel',71);
+else
+	error('md.mesh.hemisphere should be ''s'' or ''n''');
+end
+
+%figure out nlines and ncols in our image
+nlines=(maxlat-minlat)/posting;
+ncols=(maxlong-minlong)/posting;
+
+%regrid to lat,long grid
+[x_m,y_m,field]=InterpFromMeshToGrid(md.mesh.elements,md.mesh.long,md.mesh.lat,field,minlong,maxlat,posting,posting,nlines,ncols,NaN);
+field=flipud(field);
+
+%massage  and log:
+pos=find(field<minfield); field(pos)=minfield;
+pos=find(field>maxfield);field(pos)=maxfield;
+
+%create google earth kml file out of this regridded dataset:
+imagestr=ge_imagesc(x_m,y_m,field,'imgURL',[fieldname '.png'],'name',fieldname);
+imagestr=ge_folder(fieldname,imagestr);
+colorbarstr=ge_colorbar((min(x_m)+max(x_m))/2,(min(y_m)+max(y_m))/2,field,'name',fieldname);
+colorbarstr=ge_folder('Colorbar',colorbarstr);
+ge_output([fieldname '.kml'],[imagestr colorbarstr]);
+
+
+%now, create kmz file:
+system(['mv ' [fieldname '.kml'] ' doc.kml && zip ' [fieldname '.kmz'] ' doc.kml ' fieldname '.png && rm -rf doc.kml ' [fieldname '.png'] ]);
Index: /issm/trunk-jpl-damage/src/m/model/loadmultipleresultsfromcluster.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/loadmultipleresultsfromcluster.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/loadmultipleresultsfromcluster.m	(revision 11330)
@@ -0,0 +1,34 @@
+function md_list=loadmultipleresultsfromcluster(md_list)
+%LOADMULTIPLERESULTSFROMCLUSTER - load multiple results of solution sequences from cluster
+%
+%   Usage:
+%      md_list=loadresultsfromcluster(md_list);
+
+nummodels=length(md_list);
+
+%Get cluster settings
+cluster=md_list{1}.cluster;
+name=md_list{1}.name;
+cluster_rc_location=which('cluster.rc');
+[codepath,executionpath,login]=ClusterParameters(cluster,cluster_rc_location);
+
+%Remote tar: 
+disp('tarring results');
+issmssh(cluster,['"cd ' executionpath ' && rm -rf file_list.txt ModelResults.tar.gz && find -iname ''*_*vs*.outbin'' > file_list.txt && tar zcvf ModelResults.tar.gz --files-from file_list.txt  && rm -rf file_list.txt "']);
+
+%copy results from cluster to present directory
+scpin(cluster, executionpath, {'ModelResults.tar.gz'});
+
+%untar:
+!tar -zxvf ModelResults.tar.gz
+
+%ok, go through list and load results from disk: 
+for i=1:nummodels,
+	%load  results for this model
+	md_list{i}=loadresultsfromdisk(md_list{i},[md_list{i}.name '.outbin']);
+
+	delete([name '.outbin']);
+end
+
+%erase files 
+delete('ModelResults.tar.gz');
Index: /issm/trunk-jpl-damage/src/m/model/loadresultsfromcluster.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/loadresultsfromcluster.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/loadresultsfromcluster.m	(revision 11330)
@@ -0,0 +1,46 @@
+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
+if verLessThan('matlab', '7.6');
+	Download(cluster,md);
+else
+	cluster.Download(md);
+end
+
+%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']);
+	delete([md.private.runtimename '.tar.gz']);
+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 '.queue']);
+		delete([md.miscellaneous.name '.petsc']);
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/loadresultsfromdisk.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/loadresultsfromdisk.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/loadresultsfromdisk.m	(revision 11330)
@@ -0,0 +1,54 @@
+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,
+
+	%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);
+	md.results.(structure(1).SolutionType)=structure;
+
+	%recover solution_type from results
+	md.private.solution=structure(1).SolutionType;
+
+	%read log files onto  fields
+	if exist([md.miscellaneous.name '.errlog'],'file'),
+		md.results.(structure(1).SolutionType)(1).errlog=char(textread([md.miscellaneous.name '.errlog'],'%s','delimiter','\n'));
+	else
+		md.results.(structure(1).SolutionType)(1).errlog='';
+	end
+
+	if exist([md.miscellaneous.name '.outlog'],'file'),
+		md.results.(structure(1).SolutionType)(1).outlog=char(textread([md.miscellaneous.name '.outlog'],'%s','delimiter','\n'));
+	else
+		md.results.(structure(1).SolutionType)(1).outlog='';
+	end
+
+	if ~isempty(md.results.(structure(1).SolutionType)(1).errlog),
+		disp(['loadresultsfromcluster info message: error during solution. Check your errlog and outlog model fields']);
+	end
+
+
+%post processes qmu results if necessary
+else
+
+	if isscalar(md.private.solution),
+		md.private.solution=EnumToString(md.private.solution);
+	end
+	md=postqmu(md);
+	cd ..
+
+end
Index: /issm/trunk-jpl-damage/src/m/model/marshall.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/marshall.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/marshall.m	(revision 11330)
@@ -0,0 +1,46 @@
+function marshall(md)
+%MARSHALL - outputs a compatible binary file from @model md, for certain solution type.
+%
+%   The routine creates a compatible binary file from @model md
+%   This binary file will be used for parallel runs in JPL-package
+%
+%   Usage:
+%      marshall(md)
+
+disp(['marshalling file ' md.miscellaneous.name '.bin']);
+
+%open file for binary writing
+fid=fopen([ md.miscellaneous.name '.bin'],'wb');
+if fid==-1,
+	error(['marshall error message: could not open ' [md.miscellaneous.name '.bin'],' file for binary writing']);
+end
+
+%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' 'debug' 'radaroverlay' 'solver' 'cluster'  'flaim' 'private'}),
+		continue;
+	end
+
+	%Check that current field is an object
+	if ~isobject(md.(field))
+		checkmessage(['field ''' char(field) ''' is not an object']);
+	end
+
+	%Marshall current object
+	%disp(['marshalling ' field '...']);
+	if verLessThan('matlab', '7.6')
+		marshall(md.(field),fid);
+	else
+		md.(field).marshall(fid);
+	end
+end
+
+%close file
+st=fclose(fid);
+if st==-1,
+	error(['marshall error message: could not close file ' [md.miscellaneous.name '.bin']]);
+end
Index: /issm/trunk-jpl-damage/src/m/model/mechanicalproperties.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mechanicalproperties.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mechanicalproperties.m	(revision 11330)
@@ -0,0 +1,118 @@
+function md=mechanicalproperties(md,vx,vy)
+%MECHANICALPROPERTIES - compute stress and strain rate for a goven velocity
+%
+%   this routine computes the components of the stress tensor
+%   strain rate tensor and their respective principal directions.
+%   the results are in the model md: md.results
+%
+%   Usage:
+%      md=mechanicalproperties(md,vx,vy)
+%
+%   Example:
+%      md=mechanicalproperties(md,md.initialization.vx,md.initialization.vy);
+%      md=mechanicalproperties(md,md.inversion.vx_obs,md.inversion.vy_obs);
+
+%some checks
+if length(vx)~=md.mesh.numberofvertices | length(vy)~=md.mesh.numberofvertices,
+	error(['the input velocity should be of size ' num2str(md.mesh.numberofvertices) '!'])
+end
+if ~(md.mesh.dimension==2)
+	error('only 2d model supported yet');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non macayeal elements. These will be treated like MacAyeal''s elements');
+end
+
+%initialization
+numberofelements=md.mesh.numberofelements;
+index=md.mesh.elements;
+summation=[1;1;1];
+directionsstress=zeros(numberofelements,4);
+directionsstrain=zeros(numberofelements,4);
+valuesstress=zeros(numberofelements,2);
+valuesstrain=zeros(numberofelements,2);
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,md.mesh.x,md.mesh.y);
+
+%compute shear
+vxlist=vx(index)/md.constants.yts;
+vylist=vy(index)/md.constants.yts;
+ux=(vxlist.*alpha)*summation;
+uy=(vxlist.*beta)*summation;
+vx=(vylist.*alpha)*summation;
+vy=(vylist.*beta)*summation;						
+uyvx=(vx+uy)./2;
+clear vxlist vylist
+
+%compute viscosity
+nu=zeros(numberofelements,1);
+B_bar=md.materials.rheology_B(index)*summation/3;
+power=(md.materials.rheology_n-1)./(2*md.materials.rheology_n);
+second_inv=(ux.^2+vy.^2+((uy+vx).^2)/4+ux.*vy);
+%some corrections
+location=find(second_inv~=0);
+nu(location)=B_bar(location)./(second_inv(location).^power(location));
+location=find(second_inv==0 & power~=0);
+nu(location)=10^18; 	%arbitrary maximum viscosity to apply where there is no effective shear
+location=find(second_inv==0 & power==0);
+nu(location)=B_bar(location);
+clear B_bar location second_inv power
+
+%compute stress
+tau_xx=nu.*ux;
+tau_yy=nu.*vy;
+tau_xy=nu.*uyvx;
+
+%compute principal properties of stress
+for i=1:numberofelements,
+
+	%compute stress and strainrate matrices
+	stress=[tau_xx(i) tau_xy(i)
+	tau_xy(i)  tau_yy(i)];
+	strain=[ux(i) uyvx(i)
+	uyvx(i)  vy(i)];
+
+	%eigen values and vectors
+	[directions,value]=eig(stress);
+	valuesstress(i,:)=[value(1,1) value(2,2)];
+	directionsstress(i,:)=directions(:)';
+	[directions,value]=eig(strain);
+	valuesstrain(i,:)=[value(1,1) value(2,2)];
+	directionsstrain(i,:)=directions(:)';
+end
+
+%plug onto the model
+%NB: Matlab sorts the eigen value in increasing order, we want the reverse
+stress=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
+stress.xx=tau_xx;
+stress.yy=tau_yy;
+stress.xy=tau_xy;
+stress.principalvalue2=valuesstress(:,1);
+stress.principalaxis2=directionsstress(:,1:2);
+stress.principalvalue1=valuesstress(:,2);
+stress.principalaxis1=directionsstress(:,3:4);
+stress.effectivevalue=1/sqrt(2)*sqrt(stress.xx.^2+stress.yy.^2+2*stress.xy.^2);
+md.results.stress=stress;
+
+strainrate=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
+strainrate.xx=ux;
+strainrate.yy=vy;
+strainrate.xy=uyvx;
+strainrate.principalvalue2=valuesstrain(:,1)*(365.25*24*3600); %strain rate in 1/a instead of 1/s
+strainrate.principalaxis2=directionsstrain(:,1:2);
+strainrate.principalvalue1=valuesstrain(:,2)*(365.25*24*3600); %strain rate in 1/a instead of 1/s
+strainrate.principalaxis1=directionsstrain(:,3:4);
+strainrate.effectivevalue=1/sqrt(2)*sqrt(strainrate.xx.^2+strainrate.yy.^2+2*strainrate.xy.^2);
+md.results.strainrate=strainrate;
+
+deviatoricstress=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
+deviatoricstress.xx=tau_xx;
+deviatoricstress.yy=tau_yy;
+deviatoricstress.xy=tau_xy;
+deviatoricstress.principalvalue2=valuesstress(:,1);
+deviatoricstress.principalaxis2=directionsstress(:,1:2);
+deviatoricstress.principalvalue1=valuesstress(:,2);
+deviatoricstress.principalaxis1=directionsstress(:,3:4);
+deviatoricstress.effectivevalue=1/sqrt(2)*sqrt(stress.xx.^2+stress.yy.^2+2*stress.xy.^2);
+md.results.deviatoricstress=deviatoricstress;
Index: /issm/trunk-jpl-damage/src/m/model/mesh/bamg.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/bamg.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/bamg.m	(revision 11330)
@@ -0,0 +1,340 @@
+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 esge 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 ration 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        : geometrical 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 ration 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: maximal angle of corners in degree (default is 10)
+%   - maxnbv      : maximum number of vertices used to allocate memory (default is 10^6)
+%   - maxsubdiv   : maximum subdivision of exisiting elements (default is 10)
+%   - metric      : matrix (numberofnodes x 3) used as a metric
+%   - Metrictype  : 1 -> absolute error          c/(err coeff^2) * Abs(H)        (default)
+%                   2 -> relative error          c/(err coeff^2) * Abs(H)/max(s,cutoff*max(s))
+%                   3 -> rescaled absolute error c/(err coeff^2) * Abs(H)/(smax-smin)
+%   - nbjacoby    : correction used by Hessiantype=1 (default is 1)
+%   - nbsmooth    : number of metric smoothing procedure (default is 3)
+%   - omega       : relaxation parameter of the smoothing procedure (default is 1.8)
+%   - power       : power applied to the metric (default is 1)
+%   - splitcorners : split triangles whuch have 3 vertices on the outline (default is 1)
+%   - geometricalmetric : Take the geometry into account to generate the metric (default is 0)
+%   - verbose     : level of verbosity (default is 1)
+%
+%   - rifts : followed by an ARGUS file that prescribes the rifts
+%   - toltip: tolerance to move tip on an existing point of the domain outline
+%   - tracks: followed by an ARGUS file that prescribes the tracks that the mesh will stick to
+%   - RequiredVertices: mesh vertices that are required. [x,y,ref]; ref is optional
+%   - tol:    if the distance between 2 points of the domain outline is less than tol, they
+%             will be merged
+%
+%   Examples:
+%      md=bamg(md,'domain','DomainOutline.exp','hmax',3000);
+%      md=bamg(md,'field',[md.inversion.vel_obs md.geometry.thickness],'hmax',20000,'hmin',1000);
+%      md=bamg(md,'metric',A,'hmin',1000,'hmax',20000,'gradation',3,'anisomax',1);
+
+%process options
+options=pairoptions(varargin{:});
+options=deleteduplicates(options,1);
+
+%initialize the structures required as input of Bamg
+bamg_options=struct();
+bamg_geometry=bamggeom;
+bamg_mesh=bamgmesh;
+
+% Bamg Geometry parameters {{{1
+if exist(options,'domain'),
+
+	%Check that file exists
+	domainfile=getfieldvalue(options,'domain');
+	if ~exist(domainfile,'file') error(['bamg error message: file ' domainfile ' not found ']); end
+
+	%Build geometry 
+	domain=expread(domainfile);
+	count=0;
+	for i=1:length(domain),
+
+		%Check that the domain is closed
+		if (domain(i).x(1)~=domain(i).x(end) | domain(i).y(1)~=domain(i).y(end)),
+			error('bamg error message: all contours provided in ''domain'' should be closed');
+		end
+
+		%Checks that all holes are INSIDE the principle domain outline
+		if i>1,
+			flags=ContourToNodes(domain(i).x,domain(i).y,domain(1),0);
+			if any(~flags),
+				error('bamg error message: All holes should be stricly inside the principal domain');
+			end
+		end
+
+		%Add all points to bamg_geometry
+		nods=domain(i).nods-1; %the domain are closed 1=end;
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; [domain(i).x(1:nods) domain(i).y(1:nods) ones(nods,1)]];
+		bamg_geometry.Edges   =[bamg_geometry.Edges;    [transpose(count+1:count+nods) transpose([count+2:count+nods count+1])  1*ones(nods,1)]];
+		if i>1, bamg_geometry.SubDomains=[bamg_geometry.SubDomains; 2 count+1 1 1]; end
+
+		%update counter
+		count=count+nods;
+	end
+
+	%take care of rifts
+	if exist(options,'rifts'),
+
+		%Check that file exists
+		riftfile=getfieldvalue(options,'rifts');
+		if ~exist(riftfile,'file')
+			error(['bamg error message: file ' riftfile ' not found ']);
+		end
+		rift=expread(riftfile);
+
+		for i=1:length(rift),
+
+			%detect wether all points of the rift are inside the domain
+			flags=ContourToNodes(rift(i).x,rift(i).y,domain(1),0);
+			if ~flags,
+				error('one Rift has all his points outside of the domain outline'),
+
+			elseif any(~flags),
+				%We LOTS of work to do
+				disp('Rift tip outside of or on the domain has been detected and is being processed...');
+
+				%check that only one point is outsie (for now)
+				if sum(~flags)~=1,
+					error('bamg error message: only one point outside of the domain is supported yet');
+				end
+
+				%Move tip outside to the first position
+				if flags(1)==0,
+					%OK, first point is outside (do nothing),
+				elseif (flags(end)==0),
+					rift(i).x=flipud(rift(i).x);
+					rift(i).y=flipud(rift(i).y);
+				else
+					error('bamg error message: only a rift tip can be outside of the domain');
+				end
+
+				%Get cordinate of intersection point
+				x1=rift(i).x(1); y1=rift(i).y(1);
+				x2=rift(i).x(2); y2=rift(i).y(2);
+				for j=1:length(domain(1).x)-1;
+					if SegIntersect([x1 y1; x2 y2],[domain(1).x(j) domain(1).y(j); domain(1).x(j+1) domain(1).y(j+1)]),
+
+						%Get position of the two nodes of the edge in domain
+						i1=j;
+						i2=mod(j+1,domain(1).nods);
+
+						%rift is crossing edge [i1 i2] of the domain
+						%Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html)
+						x3=domain(1).x(i1); y3=domain(1).y(i1);
+						x4=domain(1).x(i2); y4=domain(1).y(i2);
+						x=det([det([x1 y1; x2 y2])  x1-x2;det([x3 y3; x4 y4])  x3-x4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+						y=det([det([x1 y1; x2 y2])  y1-y2;det([x3 y3; x4 y4])  y3-y4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+
+						segdis= sqrt((x4-x3)^2+(y4-y3)^2);
+						tipdis=[sqrt((x-x3)^2+(y-y3)^2)  sqrt((x-x4)^2+(y-y4)^2)];
+
+						if (min(tipdis)/segdis) < getfieldvalue(options,'toltip',0),
+							disp('moving tip-domain intersection point');
+
+							%Get position of the closest point
+							if tipdis(1)>tipdis(2),
+								pos=i2;
+							else
+								pos=i1;
+							end
+
+							%This point is only in Vertices (number pos).
+							%OK, no we can add our own rift
+							nods=rift(i).nods-1;
+							bamg_geometry.Vertices=[bamg_geometry.Vertices; [rift(i).x(2:end) rift(i).y(2:end) ones(nods,1)]];
+							bamg_geometry.Edges=[bamg_geometry.Edges;...
+								pos count+1  (1+i);...
+								[transpose(count+1:count+nods-1) transpose([count+2:count+nods])  (1+i)*ones(nods-1,1)]];
+							count=count+nods;
+
+							break;
+
+						else
+							%Add intersection point to Vertices
+							bamg_geometry.Vertices=[bamg_geometry.Vertices; x y 1];
+							count=count+1;
+
+							%Decompose the crossing edge in 2 subedges
+							pos=find(bamg_geometry.Edges(:,1)==i1 & bamg_geometry.Edges(:,2)==i2);
+							if isempty(pos) error('bamg error message: a problem occured...'); end
+							bamg_geometry.Edges=[bamg_geometry.Edges(1:pos-1,:);...
+								bamg_geometry.Edges(pos,1) count                           bamg_geometry.Edges(pos,3);...
+								count                      bamg_geometry.Edges(pos,2)   bamg_geometry.Edges(pos,3);...
+								bamg_geometry.Edges(pos+1:end,:)];
+
+							%OK, no we can add our own rift
+							nods=rift(i).nods-1;
+							bamg_geometry.Vertices=[bamg_geometry.Vertices; [rift(i).x(2:end) rift(i).y(2:end) ones(nods,1)]];
+							bamg_geometry.Edges=[bamg_geometry.Edges;...
+								count  count+1  2 ;...
+								[transpose(count+1:count+nods-1) transpose([count+2:count+nods])  (1+i)*ones(nods-1,1)]];
+							count=count+nods;
+
+							break;
+						end
+					end
+				end
+			else
+				nods=rift(i).nods-1;
+				bamg_geometry.Vertices=[bamg_geometry.Vertices; [rift(i).x(:) rift(i).y(:) ones(nods+1,1)]];
+				bamg_geometry.Edges=[bamg_geometry.Edges; [transpose(count+1:count+nods) transpose([count+2:count+nods+1])  (1+i)*ones(nods,1)]];
+				count=count+nods+1;
+			end
+		end
+	end
+
+	%Deal with tracks
+	if exist(options,'tracks'),
+
+		%read tracks
+		track=getfieldvalue(options,'tracks');
+		if all(ischar(track)),
+			A=expread(track); 
+			track=[A.x A.y];
+		else
+			track=double(track); %for some reason, it is of class "single"
+		end
+		if(size(track,2)==2), track=[track 3*ones(size(track,1),1)]; end
+
+		%only keep those inside
+		flags=ContourToNodes(track(:,1),track(:,2),domainfile,0);
+		track=track(find(flags),:);
+
+		%Add all points to bamg_geometry
+		nods=size(track,1);
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; track];
+		bamg_geometry.Edges=[bamg_geometry.Edges; [transpose(count+1:count+nods-1) transpose([count+2:count+nods])  3*ones(nods-1,1)]];
+
+		%update counter
+		count=count+nods;
+	end
+
+	%Deal with vertices that need to be kept by mesher
+	if exist(options,'RequiredVertices'),
+
+		%recover RequiredVertices
+		requiredvertices=double(getfieldvalue(options,'RequiredVertices')); %for some reason, it is of class "single"
+		if(size(requiredvertices,2)==2), requiredvertices=[requiredvertices 4*ones(size(requiredvertices,1),1)]; end
+	
+		%only keep those inside
+		flags=ContourToNodes(requiredvertices(:,1),requiredvertices(:,2),domain(1),0);
+		requiredvertices=requiredvertices(find(flags),:);
+
+		%Add all points to bamg_geometry
+		nods=size(requiredvertices,1);
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; requiredvertices];
+
+		%update counter
+		count=count+nods;
+
+	end
+
+	%process geom
+	%bamg_geometry=processgeometry(bamg_geometry,getfieldvalue(options,'tol',NaN),domain(1));
+
+elseif isstruct(md.private.bamg) & isfield(md.private.bamg,'geometry'),
+	bamg_geometry=bamggeom(md.private.bamg.geometry); 
+else
+	%do nothing...
+end
+%}}}
+% Bamg Mesh parameters {{{1
+if (~exist(options,'domain') & md.mesh.numberofvertices~=0 & md.mesh.dimension==2),
+
+	if isstruct(md.private.bamg) & isfield(md.private.bamg,'mesh'),
+		bamg_mesh=bamgmesh(md.private.bamg.mesh);
+	else
+		bamg_mesh.Vertices=[md.mesh.x md.mesh.y ones(md.mesh.numberofvertices,1)];
+		bamg_mesh.Triangles=[md.mesh.elements ones(md.mesh.numberofelements,1)];
+	end
+
+	if isstruct(md.rifts.riftstruct)
+		error('bamg error message: rifts not supported yet. Do meshprocessrift AFTER bamg');
+	end
+end
+%}}}
+% Bamg Options {{{1
+bamg_options.Crack=getfieldvalue(options,'Crack',0);
+bamg_options.anisomax=getfieldvalue(options,'anisomax',10^30);
+bamg_options.coeff=getfieldvalue(options,'coeff',1);
+bamg_options.cutoff=getfieldvalue(options,'cutoff',10^-5);
+bamg_options.err=getfieldvalue(options,'err',0.01);
+bamg_options.errg=getfieldvalue(options,'errg',0.1);
+bamg_options.field=getfieldvalue(options,'field',[]);
+bamg_options.gradation=getfieldvalue(options,'gradation',1.5);
+bamg_options.Hessiantype=getfieldvalue(options,'Hessiantype',0);
+bamg_options.hmin=getfieldvalue(options,'hmin',10^-100);
+bamg_options.hmax=getfieldvalue(options,'hmax',10^100);
+bamg_options.hminVertices=getfieldvalue(options,'hminVertices',[]);
+bamg_options.hmaxVertices=getfieldvalue(options,'hmaxVertices',[]);
+bamg_options.hVertices=getfieldvalue(options,'hVertices',[]);
+bamg_options.KeepVertices=getfieldvalue(options,'KeepVertices',1);
+bamg_options.MaxCornerAngle=getfieldvalue(options,'MaxCornerAngle',10);
+bamg_options.maxnbv=getfieldvalue(options,'maxnbv',10^6);
+bamg_options.maxsubdiv=getfieldvalue(options,'maxsubdiv',10);
+bamg_options.metric=getfieldvalue(options,'metric',[]);
+bamg_options.Metrictype=getfieldvalue(options,'Metrictype',0);
+bamg_options.nbjacobi=getfieldvalue(options,'nbjacobi',1);
+bamg_options.nbsmooth=getfieldvalue(options,'nbsmooth',3);
+bamg_options.omega=getfieldvalue(options,'omega',1.8);
+bamg_options.power=getfieldvalue(options,'power',1);
+bamg_options.splitcorners=getfieldvalue(options,'splitcorners',1);
+bamg_options.geometricalmetric=getfieldvalue(options,'geometricalmetric',0);
+bamg_options.verbose=getfieldvalue(options,'verbose',1);
+%}}}
+
+%call Bamg
+[bamgmesh_out bamggeom_out]=BamgMesher(bamg_mesh,bamg_geometry,bamg_options);
+
+% plug results onto model
+md.private.bamg=struct();
+md.private.bamg.mesh=bamgmesh(bamgmesh_out);
+md.private.bamg.geometry=bamggeom(bamggeom_out);
+md.mesh.x=bamgmesh_out.Vertices(:,1);
+md.mesh.y=bamgmesh_out.Vertices(:,2);
+md.mesh.elements=bamgmesh_out.Triangles(:,1:3);
+md.mesh.edges=bamgmesh_out.IssmEdges;
+md.mesh.segments=bamgmesh_out.IssmSegments(:,1:3);
+md.mesh.segmentmarkers=bamgmesh_out.IssmSegments(:,4);
+
+%Fill in rest of fields:
+md.mesh.dimension=2;
+md.mesh.numberofelements=size(md.mesh.elements,1);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.numberofedges=size(md.mesh.edges,1);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.elementconnectivity=md.private.bamg.mesh.ElementConnectivity;
+md.mesh.elementconnectivity(find(isnan(md.mesh.elementconnectivity)))=0;
+
+%Check for orphan
+reshape(md.mesh.elements,3*md.mesh.numberofelements,1);
+(~ismember(1:md.mesh.numberofvertices,sort(unique(reshape(md.mesh.elements,3*md.mesh.numberofelements,1)))));
+if any(~ismember(1:md.mesh.numberofvertices,sort(unique(reshape(md.mesh.elements,3*md.mesh.numberofelements,1)))))
+	error('Output mesh has orphans. Decrease MaxCornerAngle to prevent outside points (ex: 0.01)');
+end
Index: /issm/trunk-jpl-damage/src/m/model/mesh/findsegments.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/findsegments.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/findsegments.m	(revision 11330)
@@ -0,0 +1,92 @@
+function segments=findsegments(md,varargin)
+%FINDSEGMENTS - build segments model field
+%
+%   Optional inputs:
+%      'mesh.elementconnectivity'
+%
+%   Usage:
+%      segments=findsegments(md,varargin);
+
+%get options
+options=pairoptions(varargin{:});
+
+%Get connectivity
+mesh.elementconnectivity=getfieldvalue(options,'mesh.elementconnectivity',md.mesh.elementconnectivity);
+
+%Now, build the connectivity tables for this mesh if not correclty done
+if size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements,
+	if exist(options,'mesh.elementconnectivity'),
+		error(' ''mesh.elementconnectivity'' option does not have thge right size.');
+	else
+		mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+	end
+end
+
+%Recreate the segments
+elementonboundary=double(mesh.elementconnectivity(:,3)==0);
+pos=find(elementonboundary);
+num_segments=length(pos);
+segments=zeros(num_segments,3);
+count=1;
+
+%loop over the segments
+for i=1:num_segments,
+
+	%get current element on boundary
+	el1=pos(i);
+
+	%get elements connected to el1
+	els2=mesh.elementconnectivity(el1,find(mesh.elementconnectivity(el1,:)));
+
+	%el1 is connected to 2 other elements
+	if length(els2)>1,
+
+		%get nodes of el1
+		nods1=md.mesh.elements(el1,:);
+
+		%find the common vertices to the two elements connected to el1 (1 or 2)
+		flag=intersect(md.mesh.elements(els2(1),:),md.mesh.elements(els2(2),:));
+
+		%get the vertices on the boundary and build segment
+		nods1(find(ismember(nods1,flag)))=[];
+		segments(count,:)=[nods1 el1];
+
+		%swap segment nodes if necessary
+		ord1=find(nods1(1)==md.mesh.elements(el1,:));
+		ord2=find(nods1(2)==md.mesh.elements(el1,:));
+		if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+			temp=segments(count,1);
+			segments(count,1)=segments(count,2);
+			segments(count,2)=temp;
+		end
+		segments(count,1:2)=fliplr(segments(count,1:2));
+		count=count+1;
+
+	%el1 is connected to only one element
+	else
+		%get nodes of el1
+		nods1=md.mesh.elements(el1,:);
+
+		%find the vertex  the el1 to not share with els2
+		flag=setdiff(nods1,md.mesh.elements(els2,:));
+
+		for j=1:3,
+			nods=nods1; nods(j)=[];
+			if any(ismember(flag,nods)),
+
+				segments(count,:)=[nods el1];
+
+				%swap segment nodes if necessary
+				ord1=find(nods(1)==md.mesh.elements(el1,:));
+				ord2=find(nods(2)==md.mesh.elements(el1,:));
+				if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+					temp=segments(count,1);
+					segments(count,1)=segments(count,2);
+					segments(count,2)=temp;
+				end
+				segments(count,1:2)=fliplr(segments(count,1:2));
+				count=count+1;
+			end
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/mesh/meshconvert.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/meshconvert.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/meshconvert.m	(revision 11330)
@@ -0,0 +1,48 @@
+function md=meshconvert(md,varargin)
+%CONVERTMESH - convert mesh to bamg mesh
+%
+%   Usage:
+%      md=meshconvert(md);
+%      md=meshconvert(md,index,x,y);
+
+if nargin~=1 & nargin~=4,
+	help meshconvert
+	error('meshconvert error message: bad usage');
+end
+
+if nargin==1,
+	x=md.mesh.x;
+	y=md.mesh.y;
+	index=md.mesh.elements;
+else
+	x=varargin{1};
+	y=varargin{2};
+	index=varargin{3};
+end
+
+%call Bamg
+[bamgmesh_out bamggeom_out]=BamgConvertMesh(index,x,y);
+
+% plug results onto model
+md.private.bamg=struct();
+md.private.bamg.mesh=bamgmesh(bamgmesh_out);
+md.private.bamg.geometry=bamggeom(bamggeom_out);
+md.mesh.x=bamgmesh_out.Vertices(:,1);
+md.mesh.y=bamgmesh_out.Vertices(:,2);
+md.mesh.elements=bamgmesh_out.Triangles(:,1:3);
+md.mesh.edges=bamgmesh_out.IssmEdges;
+md.mesh.segments=bamgmesh_out.IssmSegments(:,1:3);
+md.mesh.segmentmarkers=bamgmesh_out.IssmSegments(:,4);
+
+%Fill in rest of fields:
+md.mesh.dimension=2;
+md.mesh.numberofelements=size(md.mesh.elements,1);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.numberofedges=size(md.mesh.edges,1);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
Index: /issm/trunk-jpl-damage/src/m/model/mesh/meshnodensity.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/meshnodensity.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/meshnodensity.m	(revision 11330)
@@ -0,0 +1,71 @@
+function md=meshnodensity(md,domainname,varargin)
+%MESH - create model mesh
+%
+%   This routine creates a model mesh using TriMeshNoDensity and a domain outline
+%   where md is a @model object, domainname is the name of an Argus domain outline file, 
+%   Riftname is an optional argument (Argus domain outline) describing rifts.
+%   The  difference with mesh.m is that the resolution of the mesh follows that of the domain 
+%   outline and the riftoutline
+%
+%   Usage:
+%      md=meshnodensity(md,domainname)
+%   or md=meshnodensity(md,domainname,riftname);
+%
+%   Examples:
+%      md=meshnodensity(md,'DomainOutline.exp');
+%      md=meshnodensity(md,'DomainOutline.exp','Rifts.exp');
+
+if (nargin==2),
+	riftname='';
+end
+if (nargin==3),
+	riftname=varargin{1};
+end
+
+%Mesh using TriMeshNoDensity
+if strcmp(riftname,''),
+	[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers]=TriMeshNoDensity(domainname);
+else
+	[elements,x,y,segments,segmentmarkers]=TriMeshNoDensity(domainname,riftname);
+
+	%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),
+		%get rid of the orphan node i
+		%update x and y
+		x=[x(1:orphan(i)-(i-1)-1); x(orphan(i)-(i-1)+1:end)];
+		y=[y(1:orphan(i)-(i-1)-1); y(orphan(i)-(i-1)+1:end)];
+		%update elements
+		pos=find(elements>orphan(i)-(i-1));
+		elements(pos)=elements(pos)-1;
+		%update segments
+		pos1=find(segments(:,1)>orphan(i)-(i-1));
+		pos2=find(segments(:,2)>orphan(i)-(i-1));
+		segments(pos1,1)=segments(pos1,1)-1;
+		segments(pos2,2)=segments(pos2,2)-1;
+	end
+
+	%plug into md
+	md.mesh.x=x;
+	md.mesh.y=y;
+	md.mesh.elements=elements;
+	md.mesh.segments=segments;
+	md.mesh.segmentmarkers=segmentmarkers;
+end
+
+%Fill in rest of fields:
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%type of model
+md.mesh.dimension=2;
Index: /issm/trunk-jpl-damage/src/m/model/mesh/meshrefine.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/meshrefine.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/meshrefine.m	(revision 11330)
@@ -0,0 +1,40 @@
+function md=meshrefine(md,areas)
+%MESHREFINE:  refined the mesh from a model, according to an area metric.
+%
+%   Usage:
+%      md=meshrefine(md,metric)
+
+%some checks on list of arguments
+if ((nargin~=2) | (nargout~=1)),
+	meshrefineusage();
+	error('meshrefine error message');
+end
+if ( (isempty(areas)) |  (length(areas)~=md.mesh.numberofelements) | (length(find(isnan(areas))))),
+	meshrefineusage();
+	error('meshrefine error message');
+end
+
+%Refine using TriMeshRefine
+[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers]=TriMeshRefine(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers,areas,'yes');
+
+%Fill in rest of fields:
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%type of model
+md.mesh.dimension=2;
+end
+
+function meshrefineusage(),
+disp('usage: md=meshrefine(md,areas)');
+end
Index: /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshaddrifts.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshaddrifts.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshaddrifts.m	(revision 11330)
@@ -0,0 +1,93 @@
+function md=meshaddrifts(md,riftname);
+%MESHADDRIFTS - add rifts to a preloaded mesh (typically, an argus mesh)
+%
+%   Usage:
+%      md=meshaddrifts(md,riftname);
+%
+%        where md is a model with a preexisting mesh, and riftname is the name of an .exp file.
+%        The format of the riftname file is as follows: a list of pairs of closed and open contours. 
+%        The closed contour defines the envelop of the rift, the open contour that follows in the 
+%        file defines the rift. The density of the rift should be chosen carefully in the file, as it 
+%        will be used to define the rift contour density of the mesh. The open contour density will 
+%        be preserved. There can be as many pairs of closed contour and rift contour as wished.
+
+
+%read rift: 
+domains=expread(riftname,1);
+contours=domains(1:2:end);
+rifts=domains(2:2:end);
+
+%now loop over rifts: 
+for rift_i=1:length(rifts),
+	
+	%refine rift to desired resolution: 
+	contour=contours(rift_i);
+	rift=rifts(rift_i);
+	
+	delete('Meshaddrifts.Rift.exp');
+	expwrite(rift,'Meshaddrifts.Rift.Coarse.exp');
+	expcoarsen('Meshaddrifts.Rift.exp','Meshaddrifts.Rift.Coarse.exp',rift.density);
+	delete('Meshaddrifts.Rift.Coarse.exp');
+	
+	%extract model:
+	expwrite(contour,'Meshaddrifts.Contour.exp');
+	md2=modelextract(md,'Meshaddrifts.Contour.exp');
+	
+	%create domain of md2 model: 
+	md2.mesh.segments=contourenvelope(md2,'Meshaddrifts.Contour.exp');
+	domain_index=md2.mesh.segments(1,1:2);
+	while (domain_index(end)~=domain_index(1)),
+		pos=find(md2.mesh.segments(:,1)==domain_index(end));
+		domain_index(end+1)=md2.mesh.segments(pos,2);
+	end
+	
+	domain.x=md2.mesh.x(domain_index);
+	domain.y=md2.mesh.y(domain_index);
+	domain.name='Meshaddrifts.Domain.exp';
+	domain.density=1;
+	expwrite(domain,'Meshaddrifts.Domain.exp');
+	
+	%unloop domain index: used for later.
+	domain_index=domain_index(1:end-1);
+	
+	%remesh md2 using new domain outline, and rift profile: 
+	md2=meshnodensity(md2,'Meshaddrifts.Domain.exp','Meshaddrifts.Rift.exp');
+	md2=meshprocessrifts(md2);
+	
+	%plug md2 mesh into md mesh: 
+	[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,md.mesh.numberofelements,md.mesh.numberofvertices,elconv,nodeconv,elconv2,nodeconv2]=meshplug(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,...
+								md2.mesh.elements,md2.mesh.x,md2.mesh.y,md2.mesh.z,md2.extractednodes,md2.extractedelements,domain_index);
+
+	%update md2 rifts using elconv and nodeconv, and plug them into md: 
+	md2.rifts=updateriftindexing(md2.rifts,elconv2,nodeconv2);
+	
+	for i=1:md.rifts.numrifts,
+		md.rifts.riftstruct(i)=updateriftindexing(md.rifts.riftstruct(i),elconv,nodeconv);
+	end
+	
+	if md.rifts.numrifts==0,
+		md.rifts.riftstruct=md2.rifts;
+		md.rifts.numrifts=1;
+	else
+		md.rifts.riftstruct(end+1,1)=md2.rifts;
+		md.rifts.numrifts=md.rifts.numrifts+1;
+	end
+	
+	md.mesh.segments(:,1:2)=nodeconv(md.mesh.segments(:,1:2));
+	md.mesh.segments(:,3)=elconv(md.mesh.segments(:,3));
+
+end
+
+%finish up "a la" mesh.h
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%type of model
+md.mesh.dimension=2;
Index: /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshplug.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshplug.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshplug.m	(revision 11330)
@@ -0,0 +1,89 @@
+function [elements,x,y,z,numberofelements,numberofnodes,elconv,nodeconv,elconv2,nodeconv2]=meshplug(elements,x,y,z,elements2,x2,y2,z2,extractednodes,extractedelements,domain);
+%MESHPLUG - embed mesh into another one
+%     See also meshaddrifts
+
+
+%initialize elconv,nodeconv conversion tables from md mesh to new md mesh
+elconv=1:size(elements,1); elconv=elconv';
+nodeconv=1:size(x,1); nodeconv=nodeconv';
+
+%take away old elements in area of interest: 
+elements(extractedelements,:)=[];
+element_offset=size(elements,1);
+
+%update elconv after having extracted the area of interest elements
+temp_elconv=elconv; temp_elconv(extractedelements)=[];
+temp_elconvnum=1:length(temp_elconv);
+elconv(temp_elconv)=temp_elconvnum;
+elconv(extractedelements)=NaN;
+
+%initialize elconv2 and nodeconv2, conversion tables from md2 mesh to new md mesh
+elconv2=1:size(elements2,1);elconv2=elconv2'+element_offset;
+nodeconv2=(size(x,1)+1):(size(x,1)+size(x2,1)); nodeconv2=nodeconv2';
+
+extractednodes_minusborder=extractednodes;
+extractednodes_minusborder(domain)=[];
+
+x(extractednodes_minusborder)=NaN;
+y(extractednodes_minusborder)=NaN;
+
+%now, plug md2 mesh: 
+
+%first, offset all ids of md2 mesh
+elements2=elements2+length(x);
+
+%NaN border nodes in second mesh
+x2(1:length(domain))=NaN;
+y2(1:length(domain))=NaN;
+
+%redirect border nodes in elements2  to elements
+for i=1:length(domain),
+	pos=find(elements2==(i+length(x)));
+	elements2(pos)=extractednodes(domain(i));
+end
+
+%same deal for nodeconv2:
+for i=1:length(domain),
+	nodeconv2(i)=extractednodes(domain(i));
+end
+
+
+%plug elements
+elements=[elements;elements2];
+
+
+%now, increase number of nodes
+x=[x; x2];
+y=[y; y2];
+z=[z; z2];
+
+%now, get rid of NaN in x:
+while  ~isempty(find(isnan(x))),
+
+	pos=find(isnan(x));
+	node=pos(1);
+
+	%collapse node
+	x(node)=[];
+	y(node)=[];
+	z(node)=[];
+
+	%renumber all nodes > node in elements
+	pos=find(elements>node);
+	elements(pos)=elements(pos)-1;
+
+	%same deal for nodeconv2: 
+	pos=find(nodeconv2>node);
+	nodeconv2(pos)=nodeconv2(pos)-1;
+
+end
+
+numberofnodes=length(x);
+numberofelements=length(elements);
+
+%finish nodeconv: 
+temp_nodeconv=nodeconv;  temp_nodeconv(extractednodes_minusborder)=[];
+temp_nodeconvnum=1:length(temp_nodeconv);
+nodeconv(temp_nodeconv)=temp_nodeconvnum;
+nodeconv(extractednodes_minusborder)=NaN;
+
Index: /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshprocessoutsiderifts.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshprocessoutsiderifts.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshprocessoutsiderifts.m	(revision 11330)
@@ -0,0 +1,94 @@
+function md=meshprocessoutsiderifts(md,domainoutline)
+%MESHPROCESSOUTSIDERIFTS - process rifts when they touch the domain outline
+%
+%   Usage:
+%      md=meshprocessoutsiderifts(md,domain)
+%
+
+
+
+%go through rifts, and figure out which ones touch the domain outline
+for i=1:md.rifts.numrifts,
+	
+	%first, flag nodes that belong to the domain outline
+	flags=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,domainoutline,'node',0);
+
+	rift=md.rifts.riftstruct(i);
+	tips=rift.tips;
+	outsidetips=tips(find(flags(rift.tips)==0));
+
+	%we have found outsidetips, tips that touch the domain outline. go through them
+	for j=1:length(outsidetips),
+		
+		tip=outsidetips(j);
+		%find tip in the segments, take first segment (there should be 2) that holds tip, 
+		%and node_connected_to_tip is the other node on this segment:
+		tipindex=find(rift.segments(:,1)==tip); 
+		if length(tipindex),
+			tipindex=tipindex(1);
+			node_connected_to_tip=rift.segments(tipindex,2);
+		else
+			tipindex=find(rift.segments(:,2)==tip); tipindex=tipindex(1);
+			node_connected_to_tip=rift.segments(tipindex,1);
+		end
+
+		%ok, we have the tip node, and the first node connected to it, on the rift. Now, 
+		%identify all the elements that are connected to the tip, and that are on the same 
+		%side of the rift.
+		A=tip;
+		B=node_connected_to_tip;
+
+		elements=[];
+
+		while  flags(B), %as long as B does not belong to the domain outline, keep looking.
+			%detect elements on edge A,B:
+			edgeelements=ElementsFromEdge(md.mesh.elements,A,B);
+			%rule out those we already detected
+			already_detected=ismember(edgeelements,elements);
+			nextelement=edgeelements(find(~already_detected));
+			%add new detected element to the list of elements we are looking for.
+			elements=[elements;nextelement];
+			%new B:
+			B=md.mesh.elements(nextelement,find(~ismember(md.mesh.elements(nextelement,:),[A B])));
+		end
+		
+		%take the list of elements on one side of the rift that connect to the tip, 
+		%and duplicate the tip on them, so as to open the rift to the outside.
+		num=length(md.mesh.x)+1;
+		md.mesh.x=[md.mesh.x;md.mesh.x(tip)];
+		md.mesh.y=[md.mesh.y;md.mesh.y(tip)];
+		md.mesh.numberofvertices=num;
+		
+		%replace tip in elements
+		newelements=md.mesh.elements(elements,:);
+		pos=find(newelements==tip);
+		newelements(pos)=num;
+		md.mesh.elements(elements,:)=newelements;
+		md.rifts.riftstruct(i).tips=[md.rifts.riftstruct(i).tips num];
+
+		%deal with segments
+		tipsegments=find((md.mesh.segments(:,1)==tip) | (md.mesh.segments(:,2)==tip));
+		for  k=1:length(tipsegments),
+			segment_index=tipsegments(k);
+			pos=find(md.mesh.segments(segment_index,1:2)~=tip);
+			other_node=md.mesh.segments(segment_index,pos);
+			if ~isconnected(md.mesh.elements,other_node,tip),
+				pos=find(md.mesh.segments(segment_index,1:2)==tip);
+				md.mesh.segments(segment_index,pos)=num;
+			end
+		end
+	end
+end
+
+
+%Fill in rest of fields:
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary=zeros(length(md.mesh.x),1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.rifts.numrifts=length(md.rifts.riftstruct);
+md.flowequation.element_equation=3*ones(md.mesh.numberofelements,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
Index: /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshprocessrifts.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshprocessrifts.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshprocessrifts.m	(revision 11330)
@@ -0,0 +1,69 @@
+function md=meshprocessrifts(md,domainoutline)
+%MESHPROCESSRIFTS - process mesh when rifts are present
+%
+%   split rifts inside mesh (rifts are defined by presence of
+%   segments inside the domain outline)
+%   if domain outline is provided, check for rifts that could touch it, and open them up.
+%
+%   Usage:
+%      md=meshprocessrifts(md,domainoutline)
+%
+%   Ex: 
+%      md=meshprocessrifts(md,'DomainOutline.exp');
+%
+
+%some checks on arguments: 
+if nargout~=1,
+	help meshprocessrifts
+	error('meshprocessrifts usage error:');
+end
+
+if nargin~=2,
+	help meshprocessrifts
+	error('meshprocessrifts usage error:');
+end
+
+%Call MEX file
+[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers,md.rifts.riftstruct]=TriMeshProcessRifts(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers);
+if ~isstruct(md.rifts.riftstruct),
+	error('TriMeshProcessRifts did not find any rift');
+end
+
+%Fill in rest of fields:
+numrifts=length(md.rifts.riftstruct);
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary=zeros(length(md.mesh.x),1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+
+%get coordinates of rift tips
+for i=1:numrifts,
+	md.rifts.riftstruct(i).tip1coordinates=[md.mesh.x(md.rifts.riftstruct(i).tips(1)) md.mesh.y(md.rifts.riftstruct(i).tips(1))];
+	md.rifts.riftstruct(i).tip2coordinates=[md.mesh.x(md.rifts.riftstruct(i).tips(2)) md.mesh.y(md.rifts.riftstruct(i).tips(2))];
+end
+
+%In case we have rifts that open up the domain outline, we need to open them: 
+flags=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,domainoutline,'node',0);
+found=0;
+for i=1:numrifts,
+	if flags(md.rifts.riftstruct(i).tips(1))==0,
+		found=1;
+		break;
+	end
+	if flags(md.rifts.riftstruct(i).tips(2))==0,
+		found=1;
+		break;
+	end
+end
+if found,
+	md=meshprocessoutsiderifts(md,domainoutline);
+end
+
+%get elements that are not correctly oriented in the correct direction:
+aires=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+pos=find(aires<0);
+md.mesh.elements(pos,:)=[md.mesh.elements(pos,2) md.mesh.elements(pos,1) md.mesh.elements(pos,3)];
Index: /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshyamsrecreateriftsegments.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshyamsrecreateriftsegments.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/rifts/meshyamsrecreateriftsegments.m	(revision 11330)
@@ -0,0 +1,90 @@
+function md=meshyamsrecreateriftsegments(md)
+
+	%recreate rift segments: just used for yams. temporaroy routine.
+	pos_record=[];
+	if md.rifts.numrifts,
+		for i=1:md.rifts.numrifts,
+			rift=md.rifts.riftstruct(i);
+
+			%closed rifts first:
+			if length(rift.tips)==2,
+
+				%find tip1 and tip2 for this rift, in the new mesh created by yams.
+				pos=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip1coordinates(1),rift.tip1coordinates(2));
+				tip1=md.mesh.segments(pos,1);
+				pos=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip2coordinates(1),rift.tip2coordinates(2));
+				tip2=md.mesh.segments(pos,1);
+
+				%start from tip1, and build segments of this rift. 
+				pos=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip1coordinates(1),rift.tip1coordinates(2));
+				pos_record=[pos_record; pos];
+				riftsegs=md.mesh.segments(pos,:);
+				while 1,
+					A=riftsegs(end,1); B=riftsegs(end,2); el=riftsegs(end,3);
+					%find other segment that holds B.
+					pos=find(md.mesh.segments(:,1)==B);
+					pos_record=[pos_record; pos];
+					riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+					if riftsegs(end,2)==tip1, 
+						break;
+					end
+				end
+				md.rifts.riftstruct(i).segments=riftsegs;
+				md.rifts.riftstruct(i).tips=[tip1 tip2];
+
+			else
+				%ok, this is a rift that opens up to the domain outline.  One tip is going to be 
+				%double, the other one, single. We are going to start from the single tip, towards the two 
+				%other doubles
+
+				%find tip1 and tip2 for this rift, in the new mesh created by yams.
+				pos1=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip1coordinates(1),rift.tip1coordinates(2));
+				tip1=md.mesh.segments(pos1,1);
+				pos2=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip2coordinates(1),rift.tip2coordinates(2));
+				tip2=md.mesh.segments(pos2,1);
+				if length(tip1)==2,
+					%swap.
+					temp=tip1; tip1=tip2; tip2=temp;
+					temp=pos1; pos1=pos2; pos2=temp;
+					pos=pos1;
+				else
+					pos=pos1;
+				end
+
+				pos_record=[pos_record; pos];
+				riftsegs=md.mesh.segments(pos,:);
+				while 1,
+					A=riftsegs(end,1); B=riftsegs(end,2); el=riftsegs(end,3);
+					%find other segment that holds B.
+					pos=find(md.mesh.segments(:,1)==B);
+					pos_record=[pos_record; pos];
+					riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+					if ((riftsegs(end,2)==tip2(1)) | (riftsegs(end,2)==tip2(2))), 
+						%figure out which tip we reached
+						if riftsegs(end,2)==tip2(1), index=2; else index=1; end
+						break;
+					end
+				end
+
+				%ok, now, we start from the other tip2, towards tip1
+				pos=pos2(index);
+				pos_record=[pos_record; pos];
+				riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+				while 1,
+					A=riftsegs(end,1); B=riftsegs(end,2); el=riftsegs(end,3);
+					%find other segment that holds B.
+					pos=find(md.mesh.segments(:,1)==B);
+					pos_record=[pos_record; pos];
+					riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+					if riftsegs(end,2)==tip1, 
+						break;
+					end
+				end
+				md.rifts.riftstruct(i).segments=riftsegs;
+				md.rifts.riftstruct(i).tips=[tip1 tip2(1) tip2(2)];
+
+			end
+		end
+	end
+	%take out rift segments from segments
+	md.mesh.segments(pos_record,:)=[];
Index: /issm/trunk-jpl-damage/src/m/model/mesh/rifts/rifttipsrefine.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/rifts/rifttipsrefine.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/rifts/rifttipsrefine.m	(revision 11330)
@@ -0,0 +1,26 @@
+function md=rifttipsrefine(md,filename,resolution,circleradius);
+%RIFTTIPSREFINE - refine mesh near rift tips
+%
+%   Usage:
+%      md=rifttipsrefine(md,filename,resolution,circleradius);
+
+numberofnodes=50;
+
+%take rifts, and create refinement circles around tips
+rifts=expread(filename,1);
+
+!echo -n "" > Circles.exp
+for i=1:length(rifts),
+	tip1=[rifts(i).x(1) rifts(i).y(1)];
+	tip2=[rifts(i).x(end) rifts(i).y(end)];
+	%create circle around tip
+	expcreatecircle('Circle1.exp',tip1(1),tip1(2),circleradius,numberofnodes);
+	expcreatecircle('Circle2.exp',tip2(1),tip2(2),circleradius,numberofnodes);
+	!cat Circles.exp Circle1.exp Circle2.exp > Circles2.exp
+	!mv Circles2.exp Circles.exp
+	!rm -rf Circle1.exp Circle2.exp
+end
+
+md=meshexprefine(md,'Circles.exp',resolution);
+
+system('rm -rf Circles.exp');
Index: /issm/trunk-jpl-damage/src/m/model/mesh/rifts/updateriftindexing.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/rifts/updateriftindexing.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/rifts/updateriftindexing.m	(revision 11330)
@@ -0,0 +1,11 @@
+function rift=updateriftindexing(rift,elconv,nodeconv)
+%UPDATERIFTINDEXING - update rift indexing, using mesh to new mesh conversion tables
+%     See also meshaddrift
+
+rift.segments(:,1:2)=nodeconv(rift.segments(:,1:2));
+rift.segments(:,3)=elconv(rift.segments(:,3));
+rift.pairs=elconv(rift.pairs);
+rift.tips=nodeconv(rift.tips);
+
+rift.penaltypairs(:,1:2)=nodeconv(rift.penaltypairs(:,1:2));
+rift.penaltypairs(:,3:4)=elconv(rift.penaltypairs(:,3:4));
Index: /issm/trunk-jpl-damage/src/m/model/mesh/triangle.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/triangle.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/triangle.m	(revision 11330)
@@ -0,0 +1,85 @@
+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
+if strcmp(riftname,''),
+	[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers]=TriMesh(domainname,area,'yes');
+else
+	[elements,x,y,segments,segmentmarkers]=TriMesh(domainname,riftname,area,'yes');
+
+	%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),
+		%get rid of the orphan node i
+		%update x and y
+		x=[x(1:orphan(i)-(i-1)-1); x(orphan(i)-(i-1)+1:end)];
+		y=[y(1:orphan(i)-(i-1)-1); y(orphan(i)-(i-1)+1:end)];
+		%update elements
+		pos=find(elements>orphan(i)-(i-1));
+		elements(pos)=elements(pos)-1;
+		%update segments
+		pos1=find(segments(:,1)>orphan(i)-(i-1));
+		pos2=find(segments(:,2)>orphan(i)-(i-1));
+		segments(pos1,1)=segments(pos1,1)-1;
+		segments(pos2,2)=segments(pos2,2)-1;
+	end
+
+	%plug into md
+	md.mesh.x=x;
+	md.mesh.y=y;
+	md.mesh.elements=elements;
+	md.mesh.segments=segments;
+	md.mesh.segmentmarkers=segmentmarkers;
+end
+
+%Fill in rest of fields:
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%type of model
+md.mesh.dimension=2;
Index: /issm/trunk-jpl-damage/src/m/model/mesh/yams.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/mesh/yams.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/mesh/yams.m	(revision 11330)
@@ -0,0 +1,171 @@
+function md=yams(md,varargin);
+%MESHYAMS - Build model of Antarctica by refining according to observed velocity error estimator
+%
+%   Usage:
+%      md=yams(md,varargin);
+%      where varargin is a lit of paired arguments. 
+%      arguments can be: 'domainoutline': Argus file containing the outline of the domain to be meshed
+%      arguments can be: 'velocities': matlab file containing the velocities [m/yr]
+%      optional arguments: 'groundeddomain': Argus file containing the outline of the grounded ice
+%                          this option is used to minimize the metric on water (no refinement)
+%      optional arguments: 'resolution': initial mesh resolution [m]
+%      optional arguments: 'nsteps': number of steps of mesh adaptation
+%      optional arguments: 'epsilon': average interpolation error wished [m/yr]
+%      optional arguments: 'hmin': minimum edge length
+%      optional arguments: 'hmanx': maximum edge
+%      optional arguments: 'riftoutline': if rifts are present, specifies rift outline file.
+%      
+%
+%   Examples:
+%      md=yams(md,'domainoutline','Domain.exp','velocities','vel.mat');
+%      md=yams(md,'domainoutline','Domain.exp','velocities','vel.mat','groundeddomain','ground.exp');
+%      md=yams(md,'domainoutline','Domain.exp','velocities','vel.mat','groundeddomain','ground.exp','nsteps',6,'epsilon',2,'hmin',500,'hmax',30000);
+
+%recover options
+options=pairoptions(varargin{:});
+options=deleteduplicates(options,1);
+
+%recover some fields
+disp('MeshYams Options:')
+domainoutline=getfieldvalue(options,'domainoutline');
+disp(sprintf('   %-15s: ''%s''','DomainOutline',domainoutline));
+riftoutline=getfieldvalue(options,'riftoutline','N/A');
+disp(sprintf('   %-15s: ''%s''','riftoutline',riftoutline));
+groundeddomain=getfieldvalue(options,'groundeddomain','N/A');
+disp(sprintf('   %-15s: ''%s''','GroundedDomain',groundeddomain));
+velocities=getfieldvalue(options,'velocities');
+disp(sprintf('   %-15s: ''%s''','Velocities',velocities));
+resolution=getfieldvalue(options,'resolution',5000);
+disp(sprintf('   %-15s: %f','Resolution',resolution));
+nsteps=getfieldvalue(options,'nsteps',6);
+disp(sprintf('   %-15s: %i','nsteps',nsteps));
+gradation=getfieldvalue(options,'gradation',2*ones(nsteps,1));
+disp(sprintf('   %-15s: %g','gradation',gradation(1)));
+epsilon=getfieldvalue(options,'epsilon',3);
+disp(sprintf('   %-15s: %f','epsilon',epsilon));
+hmin=getfieldvalue(options,'hmin',500);
+disp(sprintf('   %-15s: %f','hmin',hmin));
+hmax=getfieldvalue(options,'hmax',150*10^3);
+disp(sprintf('   %-15s: %f\n','hmax',hmax));
+
+%mesh with initial resolution
+disp('Initial mesh generation...');
+if strcmpi(riftoutline,'N/A');
+	md=setmesh(md,domainoutline,resolution);
+else
+	md=setmesh(md,domainoutline,riftoutline,resolution);
+	md=meshprocessrifts(md,domainoutline);
+end
+disp(['Initial mesh, number of elements: ' num2str(md.mesh.numberofelements)]);
+
+%load velocities 
+disp('loading velocities...');
+Names=VelFindVarNames(velocities);
+Vel=load(velocities);
+
+%start mesh adaptation
+for i=1:nsteps,
+	disp(['Iteration #' num2str(i) '/' num2str(nsteps)]);
+
+	%interpolate velocities onto mesh
+	disp('   interpolating velocities...');
+	if strcmpi(Names.interp,'node'),
+		vx_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+		vy_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+	else
+		vx_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+		vy_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+	end
+	field=sqrt(vx_obs.^2+vy_obs.^2);
+
+	%set mask.vertexonwater  field
+	if ~strcmp(groundeddomain,'N/A'),
+		nodeground=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,groundeddomain,'node',2);
+		md.mask.vertexonwater=ones(md.mesh.numberofvertices,1);
+		md.mask.vertexonwater(find(nodeground))=0;
+	else
+		md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+	end
+
+	%adapt according to velocities
+	disp('   adapting...');
+	md=YamsCall(md,field,hmin,hmax,gradation(i),epsilon);
+
+	%if we have rifts, we just messed them up, we need to recreate the segments that constitute those 
+	%rifts, because the segments are used in YamsCall to freeze the rifts elements during refinement.
+	if md.rifts.numrifts, 
+		md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+		md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+		md.mesh.segments=findsegments(md);
+		md=yamsrecreateriftsegments(md);
+	end
+
+end
+	
+disp(['Final mesh, number of elements: ' num2str(md.mesh.numberofelements)]);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%recreate segments
+md.mesh.segments=findsegments(md);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+
+%Fill in rest of fields:
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+if ~strcmp(groundeddomain,'N/A'),
+	nodeground=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,groundeddomain,'node',2);
+	md.mask.vertexonwater=ones(md.mesh.numberofvertices,1);
+	md.mask.vertexonwater(find(nodeground))=0;
+else
+	md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+end
+if strcmpi(Names.interp,'node'),
+	md.inversion.vx_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+	md.inversion.vy_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+else
+	md.inversion.vx_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+	md.inversion.vy_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+end
+md.inversion.vel_obs=sqrt(md.inversion.vx_obs.^2+md.inversion.vy_obs.^2);
+
+%deal with rifts 
+if md.rifts.numrifts,
+	%first, recreate rift segments
+	md=meshyamsrecreateriftsegments(md);
+
+	%using the segments, recreate the penaltypairs
+	for j=1:md.rifts.numrifts,
+		rift=md.rifts.riftstruct(j);
+
+		%build normals and lengths of segments:
+		lengths=sqrt((md.mesh.x(rift.segments(:,1))-md.mesh.x(rift.segments(:,2))).^2 + (md.mesh.y(rift.segments(:,1))-md.mesh.y(rift.segments(:,2))).^2 );
+		normalsx=cos(atan2((md.mesh.x(rift.segments(:,1))-md.mesh.x(rift.segments(:,2))) , (md.mesh.y(rift.segments(:,2))-md.mesh.y(rift.segments(:,1)))));
+		normalsy=sin(atan2((md.mesh.x(rift.segments(:,1))-md.mesh.x(rift.segments(:,2))) , (md.mesh.y(rift.segments(:,2))-md.mesh.y(rift.segments(:,1)))));
+
+		%ok, build penaltypairs: 
+		numpenaltypairs=length(rift.segments)/2-1;
+		rift.penaltypairs=zeros(numpenaltypairs,7);
+
+		for i=1:numpenaltypairs,
+			rift.penaltypairs(i,1)=rift.segments(i,2);
+			rift.penaltypairs(i,2)=rift.segments(end-i,2);
+			rift.penaltypairs(i,3)=rift.segments(i,3);
+			rift.penaltypairs(i,4)=rift.segments(end-i,3);
+			rift.penaltypairs(i,5)=normalsx(i)+normalsx(i+1);
+			rift.penaltypairs(i,6)=normalsy(i)+normalsy(i+1);
+			rift.penaltypairs(i,7)=(lengths(i)+lengths(i+1))/2;
+		end
+		%renormalize norms: 
+		norms=sqrt(rift.penaltypairs(:,5).^2+rift.penaltypairs(:,6).^2);
+		rift.penaltypairs(:,5)=rift.penaltypairs(:,5)./norms;
+		rift.penaltypairs(:,6)=rift.penaltypairs(:,6)./norms;
+
+		md.rifts.riftstruct(j)=rift;
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/misfit.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/misfit.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/misfit.m	(revision 11330)
@@ -0,0 +1,37 @@
+function J=misfit(md)
+%MISFIT - compute misfit
+%
+%   Usage:
+%      J=misfit(md)
+%
+%   Example:
+%      J=misfit(md)
+%
+
+if md.mesh.dimension==2,
+	elements=md.mesh.elements;
+	x=md.mesh.x;
+	y=md.mesh.y;
+	vx=md.initialization.vx;
+	vy=md.initialization.vy;
+	vx_obs=md.inversion.vx_obs;
+	vy_obs=md.inversion.vy_obs;
+else
+	elements=md.mesh.elements2d;
+	x=md.mesh.x2d;
+	y=md.mesh.y2d;
+	vx=project2d(md,md.initialization.vx,md.mesh.numberoflayers);
+	vy=project2d(md,md.initialization.vy,md.mesh.numberoflayers);
+	vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers);
+	vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers);
+end
+
+%compute areas;
+areas=GetAreas(elements,x,y);
+
+%compute delta v on elements
+deltav=1/2*(   (vx-vx_obs).^2+(vy-vy_obs).^2)/md.constants.yts^2;
+deltav_elem=deltav(elements)*[1;1;1]/3;
+
+%compute misfit
+J=sum(deltav_elem.*areas);
Index: /issm/trunk-jpl-damage/src/m/model/modelextract.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/modelextract.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/modelextract.m	(revision 11330)
@@ -0,0 +1,273 @@
+function md2=modelextract(md1,area)
+%modelextract - 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 
+%   modelextract2d, add '~' to the name of the domain file (ex: '~Pattyn.exp');
+%   an empty string '' will be considered as an empty domain
+%   a string 'all' will be considered as the entire domain
+%   add an argument 0 if you do not want the elements to be checked (faster)
+%
+%   Usage:
+%      md2=modelextract(md1,area);
+%
+%   Examples:
+%      md2=modelextract(md,'Domain.exp');
+%      md2=modelextract(md,md.mask.elementonfloatingice);
+%
+%   See also: EXTRUDE, COLLAPSE
+
+%some checks
+if ((nargin~=2) | (nargout~=1)),
+	help modelextract
+	error('modelextract error message: bad usage');
+end
+
+%get check option
+if (nargin==3 & varargin{1}==0),
+	checkoutline=0;
+else
+	checkoutline=1;
+end
+
+%get elements that are inside area
+flag_elem=FlagElements(md1,area);
+if ~any(flag_elem),
+	error('extracted model is empty');
+end
+
+%kick out all elements with 3 dirichlets
+spc_elem=find(~flag_elem);
+spc_node=sort(unique(md1.mesh.elements(spc_elem,:)));
+flag=ones(md1.mesh.numberofvertices,1);
+flag(spc_node)=0;
+pos=find(sum(flag(md1.mesh.elements),2)==0);
+flag_elem(pos)=0;
+
+%extracted elements and nodes lists
+pos_elem=find(flag_elem);
+pos_node=sort(unique(md1.mesh.elements(pos_elem,:)));
+
+%keep track of some fields
+numberofvertices1=md1.mesh.numberofvertices;
+numberofelements1=md1.mesh.numberofelements;
+numberofvertices2=length(pos_node);
+numberofelements2=length(pos_elem);
+flag_node=zeros(numberofvertices1,1);
+flag_node(pos_node)=1;
+
+%Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements)
+Pelem=zeros(numberofelements1,1);
+Pelem(pos_elem)=[1:numberofelements2]';
+Pnode=zeros(numberofvertices1,1);
+Pnode(pos_node)=[1:numberofvertices2]';
+
+%renumber the elements (some node won't exist anymore)
+elements_1=md1.mesh.elements;
+elements_2=elements_1(pos_elem,:);
+elements_2(:,1)=Pnode(elements_2(:,1));
+elements_2(:,2)=Pnode(elements_2(:,2));
+elements_2(:,3)=Pnode(elements_2(:,3));
+if md1.mesh.dimension==3,
+	elements_2(:,4)=Pnode(elements_2(:,4));
+	elements_2(:,5)=Pnode(elements_2(:,5));
+	elements_2(:,6)=Pnode(elements_2(:,6));
+end
+
+%OK, now create the new model !
+
+	%take every fields from model
+	md2=md1;
+
+	%automatically modify fields
+
+	%loop over model fields
+	model_fields=fields(md1);
+	for i=1:length(model_fields),
+		%get field
+		field=md1.(model_fields{i});
+		fieldsize=size(field);
+		if isobject(field), %recursive call
+			object_fields=fields(md1.(model_fields{i}));
+			for j=1:length(object_fields),
+				%get field
+				field=md1.(model_fields{i}).(object_fields{j});
+				fieldsize=size(field);
+				%size = number of nodes * n
+				if fieldsize(1)==numberofvertices1
+					md2.(model_fields{i}).(object_fields{j})=field(pos_node,:);
+				elseif (fieldsize(1)==numberofvertices1+1)
+					md2.(model_fields{i}).(object_fields{j})=[field(pos_node,:); field(end,:)];
+					%size = number of elements * n
+				elseif fieldsize(1)==numberofelements1
+					md2.(model_fields{i}).(object_fields{j})=field(pos_elem,:);
+				end
+			end
+		else
+			%size = number of nodes * n
+			if fieldsize(1)==numberofvertices1
+				md2.(model_fields{i})=field(pos_node,:);
+			elseif (fieldsize(1)==numberofvertices1+1)
+				md2.(model_fields{i})=[field(pos_node,:); field(end,:)];
+				%size = number of elements * n
+			elseif fieldsize(1)==numberofelements1
+				md2.(model_fields{i})=field(pos_elem,:);
+			end
+		end
+	end
+
+	%modify some specific fields
+
+	%Mesh
+	md2.mesh.numberofelements=numberofelements2;
+	md2.mesh.numberofvertices=numberofvertices2;
+	md2.mesh.elements=elements_2;
+
+	%mesh.uppervertex mesh.lowervertex
+	if md1.mesh.dimension==3
+		md2.mesh.uppervertex=md1.mesh.uppervertex(pos_node);
+		pos=find(~isnan(md2.mesh.uppervertex));
+		md2.mesh.uppervertex(pos)=Pnode(md2.mesh.uppervertex(pos));
+
+		md2.mesh.lowervertex=md1.mesh.lowervertex(pos_node);
+		pos=find(~isnan(md2.mesh.lowervertex));
+		md2.mesh.lowervertex(pos)=Pnode(md2.mesh.lowervertex(pos));
+
+		md2.mesh.upperelements=md1.mesh.upperelements(pos_elem);
+		pos=find(~isnan(md2.mesh.upperelements));
+		md2.mesh.upperelements(pos)=Pelem(md2.mesh.upperelements(pos));
+
+		md2.mesh.lowerelements=md1.mesh.lowerelements(pos_elem);
+		pos=find(~isnan(md2.mesh.lowerelements));
+		md2.mesh.lowerelements(pos)=Pelem(md2.mesh.lowerelements(pos));
+	end
+
+	%Initial 2d mesh 
+	if md1.mesh.dimension==3
+		flag_elem_2d=flag_elem(1:md1.mesh.numberofelements2d);
+		pos_elem_2d=find(flag_elem_2d);
+		flag_node_2d=flag_node(1:md1.mesh.numberofvertices2d);
+		pos_node_2d=find(flag_node_2d);
+
+		md2.mesh.numberofelements2d=length(pos_elem_2d);
+		md2.mesh.numberofvertices2d=length(pos_node_2d);
+		md2.mesh.elements2d=md1.mesh.elements2d(pos_elem_2d,:);
+		md2.mesh.elements2d(:,1)=Pnode(md2.mesh.elements2d(:,1));
+		md2.mesh.elements2d(:,2)=Pnode(md2.mesh.elements2d(:,2));
+		md2.mesh.elements2d(:,3)=Pnode(md2.mesh.elements2d(:,3));
+
+		md2.mesh.x2d=md1.mesh.x(pos_node_2d);
+		md2.mesh.y2d=md1.mesh.y(pos_node_2d);
+	end
+
+	%Edges
+	if size(md2.mesh.edges,2)>1, %do not use ~isnan because there are some NaNs...
+		%renumber first two columns
+		pos=find(~isnan(md2.mesh.edges(:,4)));
+		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 NaN in the last two columns;
+		pos=find(md2.mesh.edges(:,3)==0);
+		md2.mesh.edges(pos,3)=NaN;
+		pos=find(md2.mesh.edges(:,4)==0);
+		md2.mesh.edges(pos,4)=NaN;
+		%Invert NaN of the third column with last column (Also invert first two columns!!)
+		pos=find(isnan(md2.mesh.edges(:,3)));
+		md2.mesh.edges(pos,3)=md2.mesh.edges(pos,4);
+		md2.mesh.edges(pos,4)=NaN;
+		values=md2.mesh.edges(pos,2);
+		md2.mesh.edges(pos,2)=md2.mesh.edges(pos,1);
+		md2.mesh.edges(pos,1)=values;
+		%Finally remove edges that do not belong to any element
+		pos=find(isnan(md2.mesh.edges(:,3)) & isnan(md2.mesh.edges(:,4)));
+		md2.mesh.edges(pos,:)=[];
+	end
+
+	%Penalties
+	if ~isnan(md2.diagnostic.vertex_pairing),
+		for i=1:size(md1.diagnostic.vertex_pairing,1);
+			md2.diagnostic.vertex_pairing(i,:)=Pnode(md1.diagnostic.vertex_pairing(i,:));
+		end
+		md2.diagnostic.vertex_pairing=md2.diagnostic.vertex_pairing(find(md2.diagnostic.vertex_pairing(:,1)),:);
+	end
+	if ~isnan(md2.prognostic.vertex_pairing),
+		for i=1:size(md1.prognostic.vertex_pairing,1);
+			md2.prognostic.vertex_pairing(i,:)=Pnode(md1.prognostic.vertex_pairing(i,:));
+		end
+		md2.prognostic.vertex_pairing=md2.prognostic.vertex_pairing(find(md2.prognostic.vertex_pairing(:,1)),:);
+	end
+
+	%recreate segments
+	if md1.mesh.dimension==2
+		md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices);
+		md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity);
+		md2.mesh.segments=contourenvelope(md2);
+		md2.mesh.vertexonboundary=zeros(numberofvertices2,1); md2.mesh.vertexonboundary(md2.mesh.segments(:,1:2))=1;
+	end
+
+	%Boundary conditions: Dirichlets on new boundary
+	%Catch the elements that have not been extracted
+	orphans_elem=find(~flag_elem);
+	orphans_node=unique(md1.mesh.elements(orphans_elem,:))';
+	%Figure out which node are on the boundary between md2 and md1
+	nodestoflag1=intersect(orphans_node,pos_node);
+	nodestoflag2=Pnode(nodestoflag1);
+	if numel(md1.diagnostic.spcvx)>1 & numel(md1.diagnostic.spcvy)>2 & numel(md1.diagnostic.spcvz)>2,
+		if numel(md1.inversion.vx_obs)>1 & numel(md1.inversion.vy_obs)>1
+			md2.diagnostic.spcvx(nodestoflag2)=md2.inversion.vx_obs(nodestoflag2); 
+			md2.diagnostic.spcvy(nodestoflag2)=md2.inversion.vy_obs(nodestoflag2);
+		else
+			md2.diagnostic.spcvx(nodestoflag2)=NaN;
+			md2.diagnostic.spcvy(nodestoflag2)=NaN;
+			disp(' ')
+			disp('!! modelextract warning: spc values should be checked !!')
+			disp(' ')
+		end
+		%put 0 for vz
+		md2.diagnostic.spcvz(nodestoflag2)=0;
+	end
+	if ~isnan(md1.thermal.spctemperature),
+		md2.thermal.spctemperature(nodestoflag2,1)=1;
+	end
+
+	%Diagnostic
+	if ~isnan(md2.diagnostic.icefront)
+		md2.diagnostic.icefront(:,1)=Pnode(md1.diagnostic.icefront(:,1)); 
+		md2.diagnostic.icefront(:,2)=Pnode(md1.diagnostic.icefront(:,2)); 
+		md2.diagnostic.icefront(:,end-1)=Pelem(md1.diagnostic.icefront(:,end-1));
+		if md1.mesh.dimension==3
+			md2.diagnostic.icefront(:,3)=Pnode(md1.diagnostic.icefront(:,3)); 
+			md2.diagnostic.icefront(:,4)=Pnode(md1.diagnostic.icefront(:,4)); 
+		end
+		md2.diagnostic.icefront=md2.diagnostic.icefront(find(md2.diagnostic.icefront(:,1) & md2.diagnostic.icefront(:,2) & md2.diagnostic.icefront(:,end)),:);
+	end
+
+	%Results fields
+	if isstruct(md1.results),
+		md2.results=struct();
+		solutionfields=fields(md1.results);
+		for i=1:length(solutionfields),
+			%get subfields
+			solutionsubfields=fields(md1.results.(solutionfields{i}));
+			for j=1:length(solutionsubfields),
+				field=md1.results.(solutionfields{i}).(solutionsubfields{j});
+				if length(field)==numberofvertices1,
+					md2.results.(solutionfields{i}).(solutionsubfields{j})=field(pos_node);
+				elseif length(field)==numberofelements1,
+					md2.results.(solutionfields{i}).(solutionsubfields{j})=field(pos_elem);
+				else
+					md2.results.(solutionfields{i}).(solutionsubfields{j})=field;
+				end
+			end
+		end
+	end
+
+%Keep track of pos_node and pos_elem
+md2.mesh.extractedvertices=pos_node;
+md2.mesh.extractedelements=pos_elem;
Index: /issm/trunk-jpl-damage/src/m/model/modelsextract.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/modelsextract.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/modelsextract.m	(revision 11330)
@@ -0,0 +1,87 @@
+function md_list=modelsextract(md,flags,minel,varargin)
+%modelsextract - extract several self contained models according to a list of element flags.
+%
+%   The difference between this routine and the modelextract.m routine (without an 's') is that 
+%   as many models are extracted as there are closed contours defined in area. 
+%   This routine is needed for example when doing data assimilation of ice shelves in Antarctica. 
+%   Many independent ice shelves are present, and we don't want data assimilation on one ice shelf 
+%   to be hindered by another totally independent ice shelf.
+%
+%   Usage:
+%      md_list=modelsextract(md,elementfalgs,minel);
+%
+%   Examples:
+%      md_list=modelsextract(md,md.mask.elementonfloatingice,1000);
+%
+%   See also: EXTRUDE, COLLAPSE, MODELEXTRACT
+
+disp('selecting pools of elements');
+%go through flags and build as many independent element flags as there are groups of connected 1s
+%in flags.
+
+%2D or 3D?
+if md.mesh.dimension==3,
+	numberofelements=md.mesh.numberofelements2d; %this will be forgotten when we get out.
+	flags=project2d(md,flags,1);
+else
+	numberofelements=md.mesh.numberofelements;
+end
+
+%recover extra arguments: 
+distance=0;
+if nargin==4,
+	distance=varargin{1};
+end
+
+flag_list=cell(0,1);
+
+for i=1:size(flags,1),
+
+	if (flags(i)),
+
+		%ok, we are sure element i is part of a new pool.
+		pool=zeros(numberofelements,1);
+		pool=PropagateFlagsFromConnectivity(md.mesh.elementconnectivity,pool,i,flags);
+		flag_list{end+1,1}=pool;
+		
+		%speed up rest of computation by taking pool out of flags: 
+		pos=find(pool);flags(pos)=0;
+
+	end
+end
+
+%go through flag_list and discard any pool of less than minel elements: 
+ex_pos=[];
+for i=1:length(flag_list),
+	if length(find(flag_list{i}))<minel,
+		ex_pos=[ex_pos; i];
+	end
+end
+flag_list(ex_pos)=[];
+
+%now, if distance was specified, expand the flag_list by distance km: 
+if distance,
+	for i=1:length(flag_list),
+		flag_list{i}=PropagateFlagsUntilDistance(md,flag_list{i},distance);
+	end
+end
+
+%now, go use the pools of flags to extract models: 
+disp(['extracting ' num2str(size(flag_list,1)) ' models']);
+models=cell(0,1);
+
+for i=1:size(flag_list,1),
+	disp(['   ' num2str(i) '/' num2str(size(flag_list,1))]);
+	if md.mesh.dimension==3,
+		flags2d=flag_list{i};
+		realflags=project3d(md,flags2d,'element');
+	else
+		realflags=flag_list{i};
+	end
+	models{end+1,1}=modelextract(md,realflags);
+end
+
+%return model list
+md_list=modellist(models);
+
+end %end of this function
Index: /issm/trunk-jpl-damage/src/m/model/modelsextractfromdomains.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/modelsextractfromdomains.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/modelsextractfromdomains.m	(revision 11330)
@@ -0,0 +1,25 @@
+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 
Index: /issm/trunk-jpl-damage/src/m/model/modis.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/modis.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/modis.m	(revision 11330)
@@ -0,0 +1,35 @@
+function [xm,ym,modis]=modis(modisgeotif,xlim,ylim)
+%MODIS - from modis geotiff, return image
+%
+%   Usage:
+%      [xm,ym,modis]=modis(modisgeotif,xlim,ylim)
+%
+
+%find gdal coordinates
+x0=min(xlim);
+x1=max(xlim);
+
+y0=min(ylim);
+y1=max(ylim);
+
+%Get path  to gdal binaries
+path_gdal=[issmtier() '/externalpackages/gdal/install/bin/'];
+
+%Was gdal compiled? 
+if ~exist([path_gdal 'gdal_translate']),
+	error(['modis error message: GDAL library needs to be compiled to use this routine. Compile GDAL in ' issmtier() '/externalpackages/gdal to use this routine.']);
+end
+
+inputname='./temp.tif';
+system([path_gdal 'gdal_translate -quiet -projwin ' num2str(x0) ' ' num2str(y1) ' ' num2str(x1) ' ' num2str(y0) ' ' modisgeotif ' ' inputname ]);
+
+%Read in temp.tif:
+modis=double(flipud(imread('temp.tif','TIFF')));
+xm=(x0:(x1-x0)/(size(md.radaroverlay.pwr,2)-1):x1);
+ym=(y0:(y1-y0)/(size(md.radaroverlay.pwr,1)-1):y1);
+
+%Erase image
+system('rm -rf ./temp.tif');
+
+
+end
Index: /issm/trunk-jpl-damage/src/m/model/multiplequeue/BuildMultipleQueueingScript.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/multiplequeue/BuildMultipleQueueingScript.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/multiplequeue/BuildMultipleQueueingScript.m	(revision 11330)
@@ -0,0 +1,23 @@
+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
Index: /issm/trunk-jpl-damage/src/m/model/multiplequeue/BuildMultipleQueueingScriptGeneric.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/multiplequeue/BuildMultipleQueueingScriptGeneric.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/multiplequeue/BuildMultipleQueueingScriptGeneric.m	(revision 11330)
@@ -0,0 +1,9 @@
+function BuildMultipleQueueingScriptGeneric(name,executionpath,codepath)
+%BUILDMULTIPLEQUEUEINGSCRIPTGENERIC - ...
+%
+%   Usage:
+%      BuildMultipleQueueingScriptGeneric(executionpath,codepath)
+
+%not done yet
+error('BuildMultipleQueueingScriptGenericerror message: not supported yet!');
+
Index: /issm/trunk-jpl-damage/src/m/model/multiplequeue/BuildMultipleQueueingScriptgemini.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/multiplequeue/BuildMultipleQueueingScriptgemini.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/multiplequeue/BuildMultipleQueueingScriptgemini.m	(revision 11330)
@@ -0,0 +1,23 @@
+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);
Index: /issm/trunk-jpl-damage/src/m/model/multiplequeue/LaunchMultipleQueueJob.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/multiplequeue/LaunchMultipleQueueJob.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/multiplequeue/LaunchMultipleQueueJob.m	(revision 11330)
@@ -0,0 +1,21 @@
+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
Index: /issm/trunk-jpl-damage/src/m/model/multiplequeue/LaunchMultipleQueueJobGeneric.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/multiplequeue/LaunchMultipleQueueJobGeneric.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/multiplequeue/LaunchMultipleQueueJobGeneric.m	(revision 11330)
@@ -0,0 +1,7 @@
+function LaunchMultipleQueueJobGeneric(cluster,name,executionpath)
+%LAUNCHMULTIPLEQUEUEJOBGENERIC - Generic routine to launch multiple queueing job
+%
+%   Usage:
+%      LaunchMultipleQueueJobGeneric(cluster,name,executionpath)
+
+error('LaunchMultipleQueueJobGeneric error message: not supported yet!');
Index: /issm/trunk-jpl-damage/src/m/model/multiplequeue/LaunchMultipleQueueJobgemini.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/multiplequeue/LaunchMultipleQueueJobgemini.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/multiplequeue/LaunchMultipleQueueJobgemini.m	(revision 11330)
@@ -0,0 +1,22 @@
+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 "']);
Index: /issm/trunk-jpl-damage/src/m/model/outflow.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/outflow.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/outflow.m	(revision 11330)
@@ -0,0 +1,18 @@
+function flag=outflow(md);
+%OUTFLOW - flag nodes on outflux boundary
+%
+%   Usage:
+%      flag=outflow(md);
+
+A=md.mesh.segments(:,1);
+B=md.mesh.segments(:,2);
+Nx=-(md.mesh.y(A)-md.mesh.y(B));
+Ny=  md.mesh.x(A)-md.mesh.x(B);
+Vx=(md.initialization.vx(A)+md.initialization.vx(B))/2;
+Vy=(md.initialization.vy(A)+md.initialization.vy(B))/2;
+
+%dot product
+VdotN=Vx.*Nx+Vy.*Ny;
+
+flag=zeros(md.mesh.numberofvertices,1);
+flag(A(find(VdotN>0)))=1;
Index: /issm/trunk-jpl-damage/src/m/model/parametercontroloptimization.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/parametercontroloptimization.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/parametercontroloptimization.m	(revision 11330)
@@ -0,0 +1,70 @@
+function md=parametercontroloptimization(md,varargin),
+%PARAMETERCONTROLOPTIMIZATION - 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, specify the 
+%   kind of fit to use or the the optscal.
+%   
+%   Usage:
+%       md=parametercontroloptimization(md,varargin)
+%
+%   Example:
+%      md=parametercontroloptimization(md,'nsteps',6)
+
+%process options
+options=pairoptions(varargin{:});
+
+%Copy model
+md2=md;
+
+%Hard coded parameters
+%variable
+cmax_max=1000;
+cm_maxs=linspace(cmax_max/10,cmax_max,3);
+optscal_max=1000;
+optscals=linspace(optscal_max/10,optscal_max,3);
+fits=[0 2];
+%Kept constant
+md2.verbose=0;
+md2.cm_min=1;
+md2.eps_cm=NaN;
+md2.nsteps=getfieldvalue(options,'nsteps',5);
+md2.inversion.control_parameters=getfieldvalue(options,'md2.inversion.control_parameters',{'FrictionCoefficient'});
+md2.maxiter=10*ones(md2.nsteps,1);
+md2.cm_jump=0.99*ones(md2.nsteps,1);
+md2.inversion.iscontrol=1;
+md2.weights=ones(md2.numberofnodes,1);
+
+%loop over the set of parameters
+best=0;
+count=1;
+for fit=fits,
+	md2.fit=fit*ones(md2.nsteps,1);
+	for cm_max=cm_maxs;
+		md2.cm_max=cm_max;
+		for optscal=optscals;
+			md2.optscal=optscal*ones(md2.nsteps,1);
+
+			%current run
+			disp(sprintf('\n   Step %i/%i, fit=%i, cm_max=%g, optscal=%g\n',count,length(cm_maxs)*length(optscals)*length(fits),fit,cm_max,optscal))
+			md2=solve(md2,'analysis_type','DiagnosticAnalysis');
+			count=count+1;
+
+			%Check misfit difference
+			rel=(md2.results.DiagnosticAnalysis.J(1)-md2.results.DiagnosticAnalysis.J(end))/md2.results.DiagnosticAnalysis.J(1);
+			disp(['   ΔJ/J=' num2str(rel*100) '% for fit=' num2str(fit) ',cm_max=' num2str(cm_max) ', and optscal=' num2str(optscal) ]);
+			if (rel>best),
+				disp(sprintf('   --> current best'))
+				fit_final    =md2.fit;
+				cmmax_final  =md2.cm_max;
+				optscal_final=md2.optscal;
+				best=rel;
+			end
+		end
+	end
+end
+
+%load final parameters onto initial model
+md.fit    =fit_final;
+md.inversion.max_parameters =cmmax_final;
+md.inversion.gradient_scaling=optscal_final;
Index: /issm/trunk-jpl-damage/src/m/model/parameterization/parametercontrolB.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/parameterization/parametercontrolB.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/parameterization/parametercontrolB.m	(revision 11330)
@@ -0,0 +1,122 @@
+function md=parametercontrolB(md,varargin),
+%PARAMETERCONTROLB - parameterization for control method on B
+%
+%   It is possible to specify the number of steps, values for the
+%   minimum and maximum values of B, the 
+%   kind of cm_responses to use or the the optscal.
+%   
+%   Usage:
+%       md=parametercontrolB(md,varargin)
+%
+%   Example:
+%      md=parametercontrolB(md)
+%      md=parametercontrolB(md,'nsteps',20,'cm_responses',0)
+%      md=parametercontrolB(md,'cm_min',10,'cm_max',10^8,'cm_jump',0.99,'maxiter',20)
+%      md=parametercontrolB(md,eps_cm',10^-4,'optscal',[10^7 10^8])
+%
+%   See also  PARAMETERCONTROLDRAG
+
+%process options
+options=pairoptions(varargin{:});
+
+%control type
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+
+%weights
+weights=getfieldvalue(options,'weights',ones(md.mesh.numberofvertices,1));
+if (length(weights)~=md.mesh.numberofvertices)
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+else
+	md.inversion.cost_functions_coefficients=weights;
+end
+
+%nsteps
+nsteps=getfieldvalue(options,'nsteps',100);
+if (length(nsteps)~=1 | nsteps<=0 | floor(nsteps)~=nsteps)
+	md.inversion.nsteps=100;
+else
+	md.inversion.nsteps=nsteps;
+end
+
+
+%cm_min
+cm_min=getfieldvalue(options,'cm_min',paterson(273.15+5)*ones(md.mesh.numberofvertices,1));
+if (length(cm_min)==1)
+	md.inversion.min_parameters=cm_min*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_min)==md.mesh.numberofvertices)
+	md.inversion.min_parameters=cm_min;
+else
+	md.inversion.min_parameters=cm_min;
+end
+
+%cm_max
+cm_max=getfieldvalue(options,'cm_max',paterson(273.15-70)*ones(md.mesh.numberofvertices,1));
+if (length(cm_max)==1)
+	md.inversion.max_parameters=cm_max*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_max)==md.mesh.numberofvertices)
+	md.inversion.max_parameters=cm_max;
+else
+	md.inversion.max_parameters=cm_max;
+end
+
+%eps_cm
+eps_cm=getfieldvalue(options,'eps_cm',NaN);
+if (length(eps_cm)~=1 | eps_cm<0 )
+	md.inversion.cost_function_threshold=NaN;
+else
+	md.inversion.cost_function_threshold=eps_cm;
+end
+
+%maxiter
+maxiter=getfieldvalue(options,'maxiter',10*ones(md.inversion.nsteps,1));
+if (any(maxiter<0) | any(floor(maxiter)~=maxiter))
+	md.inversion.maxiter_per_step=10*ones(md.inversion.nsteps,1);
+else
+	md.inversion.maxiter_per_step=repmat(maxiter(:),md.inversion.nsteps,1);
+	md.inversion.maxiter_per_step(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_jump
+cm_jump=getfieldvalue(options,'cm_jump',0.9*ones(md.inversion.nsteps,1));
+if ~isreal(cm_jump)
+	md.inversion.step_threshold=0.9*ones(md.inversion.nsteps,1);
+else
+	md.inversion.step_threshold=repmat(cm_jump(:),md.inversion.nsteps,1);
+	md.inversion.step_threshold(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_responses
+found=0;
+if exist(options,'cm_responses'),
+	cm_responses=getfieldvalue(options,'cm_responses');
+	if ~any(~ismember(cm_responses,[ 101:105])),
+		md.inversion.cost_functions=repmat(cm_responses(:),md.inversion.nsteps,1);
+		md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.cost_functions=[...
+		103*ones(third,1);...
+		101*ones(third,1);...
+		repmat([101;101;103;101],third,1)...
+		];
+	md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+end
+
+%optscal
+found=0;
+if exist(options,'optscal'),
+	optscal=getfieldvalue(options,'optscal');
+	if ~any(optscal<0),
+		md.inversion.gradient_scaling=repmat(optscal(:),md.inversion.nsteps,1);
+		md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.gradient_scaling=[2*10^8*ones(3,1);10^8*ones(third-3,1);10^7*ones(2*third,1);];
+	md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+end
Index: /issm/trunk-jpl-damage/src/m/model/parameterization/parametercontroldrag.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/parameterization/parametercontroldrag.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/parameterization/parametercontroldrag.m	(revision 11330)
@@ -0,0 +1,121 @@
+function md=parametercontroldrag(md,varargin),
+%PARAMETERCONTROLDRAG - parameterization for control method on drag
+%
+%   It is possible to specify the number of steps, values for the
+%   minimum and maximum values of the drag, the 
+%   kind of cm_responses to use or the the optscal.
+%   
+%   Usage:
+%       md=parametercontroldrag(md,varargin)
+%
+%   Example:
+%      md=parametercontroldrag(md)
+%      md=parametercontroldrag(md,'nsteps',20,'cm_responses',0)
+%      md=parametercontroldrag(md,'cm_min',1,'cm_max',150,'cm_jump',0.99,'maxiter',20)
+%      md=parametercontroldrag(md,eps_cm',10^-4,'optscal',[10^7 10^8])
+%
+%   See also PARAMETERCONTROLB
+
+%process options
+options=pairoptions(varargin{:});
+
+%control type
+md.inversion.control_parameters={'FrictionCoefficient'};
+
+%weights
+weights=getfieldvalue(options,'weights',ones(md.mesh.numberofvertices,1));
+if (length(weights)~=md.mesh.numberofvertices)
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+else
+	md.inversion.cost_functions_coefficients=weights;
+end
+
+%nsteps
+nsteps=getfieldvalue(options,'nsteps',100);
+if (length(nsteps)~=1 | nsteps<=0 | floor(nsteps)~=nsteps)
+	md.inversion.nsteps=100;
+else
+	md.inversion.nsteps=nsteps;
+end
+
+%cm_min
+cm_min=getfieldvalue(options,'cm_min',1*ones(md.mesh.numberofvertices,1));
+if (length(cm_min)==1)
+	md.inversion.min_parameters=cm_min*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_min)==md.mesh.numberofvertices)
+	md.inversion.min_parameters=cm_min;
+else
+	md.inversion.min_parameters=cm_min;
+end
+
+%cm_max
+cm_max=getfieldvalue(options,'cm_max',250*ones(md.mesh.numberofvertices,1));
+if (length(cm_max)==1)
+	md.inversion.max_parameters=cm_max*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_max)==md.mesh.numberofvertices)
+	md.inversion.max_parameters=cm_max;
+else
+	md.inversion.max_parameters=cm_max;
+end
+
+%eps_cm
+eps_cm=getfieldvalue(options,'eps_cm',NaN);
+if (length(eps_cm)~=1 | eps_cm<0 )
+	md.inversion.cost_function_threshold=NaN;
+else
+	md.inversion.cost_function_threshold=eps_cm;
+end
+
+%maxiter
+maxiter=getfieldvalue(options,'maxiter',10*ones(md.inversion.nsteps,1));
+if (any(maxiter<0) | any(floor(maxiter)~=maxiter))
+	md.inversion.maxiter_per_step=10*ones(md.inversion.nsteps,1);
+else
+	md.inversion.maxiter_per_step=repmat(maxiter(:),md.inversion.nsteps,1);
+	md.inversion.maxiter_per_step(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_jump
+cm_jump=getfieldvalue(options,'cm_jump',0.8*ones(md.inversion.nsteps,1));
+if ~isreal(cm_jump)
+	md.inversion.step_threshold=0.8*ones(md.inversion.nsteps,1);
+else
+	md.inversion.step_threshold=repmat(cm_jump(:),md.inversion.nsteps,1);
+	md.inversion.step_threshold(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_responses
+found=0;
+if exist(options,'cm_responses'),
+	cm_responses=getfieldvalue(options,'cm_responses');
+	if ~any(~ismember(cm_responses,[101 105]))
+		md.inversion.cost_functions=repmat(cm_responses(:),md.inversion.nsteps,1);
+		md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.cost_functions=[...
+		103*ones(third,1);...
+		101*ones(third,1);...
+		repmat([101;101;103;101],third,1)...
+		];
+	md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+end
+
+%optscal
+found=0;
+if exist(options,'optscal'),
+	optscal=getfieldvalue(options,'optscal');
+	if ~any(optscal<0),
+		md.inversion.gradient_scaling=repmat(optscal(:),md.inversion.nsteps,1);
+		md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.gradient_scaling=[50*ones(3,1);15*ones(third-3,1);10*ones(third,1);repmat([10;10;20;10],third,1)];
+	md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+end
Index: /issm/trunk-jpl-damage/src/m/model/parameterization/parameterize.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/parameterization/parameterize.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/parameterization/parameterize.m	(revision 11330)
@@ -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 paramter 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=addnote(md,['Model created by using parameter file: ' parametername ' on: ' datestr(now)]);
Index: /issm/trunk-jpl-damage/src/m/model/parseresultsfromdisk.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/parseresultsfromdisk.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/parseresultsfromdisk.m	(revision 11330)
@@ -0,0 +1,212 @@
+function results=parseresultsfromdisk(filename,iosplit)
+%PARSERESULTSFROMDISK - ...
+%
+%   Usage:
+%      results=parseresultsfromdisk(filename,iosplit)
+
+if iosplit,
+	results=parseresultsfromdiskiosplit(filename);
+else
+	results=parseresultsfromdiskioserial(filename);
+end
+
+%process patch if necessary
+results=MatlabProcessPatch(results);
+
+function results=parseresultsfromdiskioserial(filename) % {{{
+%PARSERESULTSFROMDISK - ...
+%
+%   Usage:
+%      results=parseresultsfromdiskioserial(filename)
+
+
+%Open file
+fid=fopen(filename,'rb');
+if(fid==-1),
+	error(['loadresultsfromdisk error message: could not open ',filename,' for binary reading']);
+end
+results=struct();
+
+%Read fields until the end of the file.
+result=ReadData(fid);
+while ~isempty(result), 
+	%Get time and step
+	results(result.step).step=result.step;
+	results(result.step).time=result.time; 
+
+	%Add result
+	if (length(results)>=result.step & isfield(results,result.fieldname) & ~strcmp(result.fieldname,'SolutionType')),
+			results(result.step).(result.fieldname)=[ results(result.step).(result.fieldname); result.field];
+	else
+		results(result.step).(result.fieldname)=result.field;
+	end
+
+	%read next result
+	result=ReadData(fid);
+
+end
+
+fclose(fid);
+% }}}
+function results=parseresultsfromdiskiosplit(filename) % {{{
+%PARSERESULTSFROMDISKIOSPLIT - ...
+%
+%   Usage:
+%      results=parseresultsfromdiskiosplit(filename)
+
+
+%Open file
+fid=fopen(filename,'rb');
+if(fid==-1),
+	error(['loadresultsfromdisk error message: could not open ',filename,' for binary reading']);
+end
+results=struct();
+
+%if we have done split I/O, ie, we have results that are fragmented across patches, 
+%do a first pass, and figure out the structure of results
+result=ReadDataDimensions(fid);
+while ~isempty(result),
+
+	%Get time and step
+	results(result.step).step=result.step;
+	results(result.step).time=result.time; 
+
+	%Add result
+	if strcmpi(result.fieldname,'Patch'),
+		results(result.step).(result.fieldname)=[0 result.N];
+	else
+		results(result.step).(result.fieldname)=NaN;
+	end
+
+	%read next result
+	result=ReadDataDimensions(fid);
+end
+
+%do a second pass, and figure out the size of the patches
+fseek(fid,0,-1); %rewind
+result=ReadDataDimensions(fid);
+while ~isempty(result),
+
+	%Add result
+	if strcmpi(result.fieldname,'Patch'),
+		patchdimensions=results(result.step).(result.fieldname);
+		results(result.step).(result.fieldname)=[patchdimensions(1)+result.M result.N];
+	end
+
+	%read next result
+	result=ReadDataDimensions(fid);
+end
+
+%allocate patches
+for i=1:length(results),
+	results(i).Patch=zeros(results(i).Patch(1),results(i).Patch(2));
+	results(i).counter=1; %use to index into the patch
+end
+
+%third pass, this time to read the real information
+fseek(fid,0,-1); %rewind
+result=ReadData(fid);
+while ~isempty(result),
+
+	%Get time and step
+	results(result.step).step=result.step;
+	results(result.step).time=result.time; 
+
+	%Add result
+	if strcmpi(result.fieldname,'Patch'),
+		counter=results(result.step).counter;
+		counter2=counter+size(result.field,1)-1;
+		results(result.step).(result.fieldname)(counter:counter2,:)=result.field;
+
+		%increment counter: 
+		results(result.step).counter=counter2+1;
+	else
+		results(result.step).(result.fieldname)=result.field;
+	end
+
+	%read next result
+	result=ReadData(fid);
+
+end
+
+%close file
+fclose(fid);
+	% }}}
+function result=ReadData(fid) % {{{
+%READDATA - ...
+%
+%   Usage:
+%      field=ReadData(fid)
+
+%read field
+[length,count]=fread(fid,1,'int');
+
+if count==0,
+	result=struct([]);
+else
+	fieldname=fread(fid,length,'char');
+	fieldname=fieldname(1:end-1)';
+	fieldname=char(fieldname);
+	time=fread(fid,1,'double');
+	step=fread(fid,1,'int');
+
+	type=fread(fid,1,'int');
+	M=fread(fid,1,'int');
+	if type==1,
+		field=fread(fid,M,'double');
+	elseif type==2,
+		field=fread(fid,M,'char');
+		field=char(field(1:end-1)');
+	elseif type==3,
+		N=fread(fid,1,'int');
+		field=transpose(fread(fid,[N M],'double'));
+	else
+		error(['cannot read data of type ' num2str(type) ]);
+	end
+
+	result.fieldname=fieldname;
+	result.time=time;
+	result.step=step;
+	result.field=field;
+end
+% }}}
+function result=ReadDataDimensions(fid) % {{{
+%READDATA - read data dimensions, step and time, but not the data itself.
+%
+%   Usage:
+%      field=ReadDataDimensions(fid)
+
+
+%read field
+[length,count]=fread(fid,1,'int');
+
+if count==0,
+	result=struct([]);
+else
+	fieldname=fread(fid,length,'char');
+	fieldname=fieldname(1:end-1)';
+	fieldname=char(fieldname);
+	time=fread(fid,1,'double');
+	step=fread(fid,1,'int');
+
+	type=fread(fid,1,'int');
+	M=fread(fid,1,'int');
+	N=1; %default
+	if type==1,
+		fseek(fid,M*8,0);
+	elseif type==2,
+		fseek(fid,M,0);
+	elseif type==3,
+		N=fread(fid,1,'int');
+		fseek(fid,N*M*8,0);
+	else
+		error(['cannot read data of type ' num2str(type) ]);
+	end
+
+	result.fieldname=fieldname;
+	result.time=time;
+	result.step=step;
+	result.M=M;
+	result.N=N;
+end
+% }}}
Index: /issm/trunk-jpl-damage/src/m/model/partition/AreaAverageOntoPartition.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/partition/AreaAverageOntoPartition.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/partition/AreaAverageOntoPartition.m	(revision 11330)
@@ -0,0 +1,55 @@
+function partvector=AreaAverageOntoPartition(md,vector,layer)
+%AREAAVERAGEONTOPARTITION 
+%   compute partition values for a certain vector expressed on the vertices of the mesh.
+%   Use area weighted average.
+%
+%   Usage:
+%      average=AreaAverageOntoPartition(md,vector)
+%      average=AreaAverageOntoPartition(md,vector,layer) %if in 3D, chose which layer is partitioned
+
+%some checks
+if md.mesh.dimension==3,
+	if nargin~=3,
+		error('layer should be provided onto which Area Averaging occurs');
+	end
+	%save 3D model
+	md3d=md;
+	
+	md.mesh.elements=md.mesh.elements2d;
+	md.mesh.x=md.mesh.x2d;
+	md.mesh.y=md.mesh.y2d;
+	md.mesh.numberofvertices=md.mesh.numberofvertices2d;
+	md.mesh.numberofelements=md.mesh.numberofelements2d;
+	md.qmu.vertex_weight=[];
+	md.mesh.vertexconnectivity=[];
+
+	%run connectivity routine
+	md=adjacency(md);
+
+	%finally, project vector: 
+	vector=project2d(md3d,vector,layer);
+	md.qmu.partition=project2d(md3d,md3d.part,layer);
+end
+
+%ok, first check that part is Matlab indexed
+part=md.qmu.partition+1;
+
+%some check: 
+if md.qmu.numberofpartitions~=max(part),
+	error('AreaAverageOntoPartition error message: ''npart'' should be equal to max(md.qmu.partition)');
+end
+
+%initialize output
+partvector=zeros(max(part),1);
+
+%start weight average
+weightedvector=vector.*md.qmu.vertex_weight;
+for i=1:max(part),
+	pos=find(part==i);
+	partvector(i)=sum(weightedvector(pos))/sum(md.qmu.vertex_weight(pos));
+end
+
+%in 3D, restore 3D model:
+if md.mesh.dimension==3,
+	md=md3d;
+end
Index: /issm/trunk-jpl-damage/src/m/model/partition/adjacency.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/partition/adjacency.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/partition/adjacency.m	(revision 11330)
@@ -0,0 +1,26 @@
+function md=adjacency(md);
+%ADJACENCY -  compute adjacency matrix, list of vertices and list of weights.
+%
+%  function to create the adjacency matrix from the connectivity table.
+%
+%  the required output is:
+%    md.adj_mat     (double [sparse nv x nv], vertex adjacency matrix)
+%    md.qmu.vertex_weight        (double [nv], vertex weights)
+
+indi=[md.mesh.elements(:,1);md.mesh.elements(:,2);md.mesh.elements(:,3)];
+indj=[md.mesh.elements(:,2);md.mesh.elements(:,3);md.mesh.elements(:,1)];
+values=1;
+
+md.qmu.adjacency=sparse(indi,indj,values,md.mesh.numberofvertices,md.mesh.numberofvertices);
+md.qmu.adjacency=double([md.qmu.adjacency | md.qmu.adjacency']);
+
+%now, build vwgt:
+areas=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+
+%get node connectivity
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+
+connectivity=md.mesh.vertexconnectivity(:,1:end-1);
+pos=find(connectivity);
+connectivity(pos)=areas(connectivity(pos))/3;
+md.qmu.vertex_weight=sum(connectivity,2);
Index: /issm/trunk-jpl-damage/src/m/model/partition/flagedges.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/partition/flagedges.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/partition/flagedges.m	(revision 11330)
@@ -0,0 +1,45 @@
+function [xsegments ysegments]=flagedges(elements,x,y,partition);
+%FLAGEDGES - return pairs of x,y segments, delimiting partitions.
+%
+%   Usage:
+%      [xsegments ysegments]=flagedges(elements,x,y,partition)
+
+xsegments=[];
+ysegments=[];
+
+for i=1:size(elements,1),
+	m1=partition(elements(i,1));
+	m2=partition(elements(i,2));
+	m3=partition(elements(i,3));
+	x1=x(elements(i,1));
+	x2=x(elements(i,2));
+	x3=x(elements(i,3));
+	y1=y(elements(i,1));
+	y2=y(elements(i,2));
+	y3=y(elements(i,3));
+
+	if (m1~=m2) & (m1~=m3) & (m2~=m3),
+		xmiddle=(x1+x2+x3)/3;
+		ymiddle=(y1+y2+y3)/3;
+		xsegments=[xsegments; (x1+x2)/2 xmiddle];
+		xsegments=[xsegments; (x1+x3)/2 xmiddle];
+		xsegments=[xsegments; (x2+x3)/2 xmiddle];
+		ysegments=[ysegments; (y1+y2)/2 ymiddle];
+		ysegments=[ysegments; (y1+y3)/2 ymiddle];
+		ysegments=[ysegments; (y2+y3)/2 ymiddle];
+	end
+
+	if (m1==m2) & (m1~=m3),
+		xsegments=[xsegments; (x1+x3)/2 (x2+x3)/2];
+		ysegments=[ysegments; (y1+y3)/2 (y2+y3)/2];
+	end
+	if (m1==m3) & (m2~=m3),
+		xsegments=[xsegments; (x1+x2)/2 (x2+x3)/2];
+		ysegments=[ysegments; (y1+y2)/2 (y2+y3)/2];
+	end
+
+	if (m2==m3) & (m1~=m3),
+		xsegments=[xsegments; (x1+x2)/2 (x1+x3)/2];
+		ysegments=[ysegments; (y1+y2)/2 (y1+y3)/2];
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/partition/partitioner.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/partition/partitioner.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/partition/partitioner.m	(revision 11330)
@@ -0,0 +1,105 @@
+function md=partitioner(md,varargin)
+%PARTITIONER - partition mesh 
+%
+%   List of options to partitioner: 
+%
+%   package: 'chaco', 'metis' or 'scotch'
+%   npart: number of partitions.
+%   weighting: 'on' or 'off': default off
+%   section:  1 by defaults(1=bisection, 2=quadrisection, 3=octasection)
+%   recomputeadjacency:  'on' by default (set to 'off' to compute existing one)
+%   Output: md.qmu.partition recover the partition vector
+%   
+%   Usage:
+%      md=partitioner(md,'package','chaco','npart',100,'weighting','on');
+%
+
+%get options: 
+options=pairoptions(varargin{:});
+
+%set defaults
+options=addfielddefault(options,'package','chaco');
+options=addfielddefault(options,'npart',10);
+options=addfielddefault(options,'weighting','on');
+options=addfielddefault(options,'section',1);
+options=addfielddefault(options,'recomputeadjacency','on');
+
+%get package: 
+package=getfieldvalue(options,'package');
+npart=getfieldvalue(options,'npart');
+recomputeadjacency=getfieldvalue(options,'recomputeadjacency');
+
+if(md.mesh.dimension==3),
+	%partitioning essentially happens in 2D. So partition in 2D, then 
+	%extrude the partition vector vertically. 
+	md3d=md; %save  for later
+	md.mesh.elements=md.mesh.elements2d;
+	md.mesh.x=md.mesh.x2d;
+	md.mesh.y=md.mesh.y2d;
+	md.mesh.numberofvertices=md.mesh.numberofvertices2d;
+	md.mesh.numberofelements=md.mesh.numberofelements2d;
+	md.qmu.vertex_weight=[];
+	md.mesh.vertexconnectivity=[];
+end
+
+%adjacency matrix if needed:
+if strcmpi(recomputeadjacency,'on'),
+	md=adjacency(md);
+else
+	disp('skipping adjacency matrix computation as requested in the options');
+end
+
+
+if strcmpi(package,'chaco'),
+
+	%  default method (from chaco.m)
+	method=[1 1 0 0 1 1 50 0 .001 7654321]';
+	method(1)=3;    %  global method (3=inertial (geometric))
+	method(3)=0;    %  vertex weights (0=off, 1=on)
+	
+	%specify bisection
+	method(6)=getfieldvalue(options,'section');%  ndims (1=bisection, 2=quadrisection, 3=octasection)
+
+	%are we using weights? 
+	if strcmpi(getfieldvalue(options,'weighting'),'on'),
+		weights=floor(md.qmu.vertex_weight/min(md.qmu.vertex_weight));
+		method(3)=1;
+	else 
+		weights=[];
+	end
+	
+	%  partition into nparts
+	part=Chaco(md.qmu.adjacency,weights,[],md.mesh.x, md.mesh.y ,md.mesh.z,method,npart,[])'+1; %index partitions from 1 up. like metis.
+
+elseif strcmpi(package,'scotch'),
+
+	%are we using weights? 
+	if strcmpi(getfieldvalue(options,'weighting'),'on'),
+		weights=floor(md.qmu.vertex_weight/min(md.qmu.vertex_weight));
+	end
+	maptab=Scotch(md.qmu.adjacency,[],weights,[],'cmplt',[npart]);
+	
+	part=maptab(:,2);%index partitions from 1 up. like metis.
+
+
+elseif strcmpi(package,'linear'),
+
+	part=1:1:md.mesh.numberofvertices;
+
+elseif strcmpi(package,'metis'),
+
+	[element_partitioning,part]=MeshPartition(md.mesh,md.qmu.numberofpartitions);
+
+else
+
+	error(['partitioner error message: could not find ' package ' partitioner']);
+	help partitioner
+end
+
+%extrude if we are in 3D:
+if md.mesh.dimension==3,
+	md=md3d;
+	part=project3d(md,'vector',part','type','node');
+end
+
+md.qmu.partition=part;
Index: /issm/trunk-jpl-damage/src/m/model/petscversion.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/petscversion.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/petscversion.m	(revision 11330)
@@ -0,0 +1,24 @@
+function PETSC_VERSION=petscversion()
+%PETSCVERSION - recover petsc version number, inside config.h file
+%
+%   Usage:
+%       PETSC_VERSION=petscversion();
+
+
+configfile=[issmtier() '/config.h'];
+if ~exist(configfile,'file'),
+	error(['File ' configfile ' not found. ISSM has not been configured yet!']);
+end
+
+%go through the file, and recover the line we want
+fid=fopen(configfile,'r');
+if(fid==-1), error(['could not open file: ' configfile]); end
+
+while(true),
+	tline=fgets(fid);
+	if ~ischar(tline), break, end
+	if  strncmp(tline,'#define _PETSC_MAJOR_',21),
+		PETSC_VERSION=str2num(tline(23));
+	end
+end
+fclose(fid);
Index: /issm/trunk-jpl-damage/src/m/model/plot/applyoptions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/applyoptions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/applyoptions.m	(revision 11330)
@@ -0,0 +1,525 @@
+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 strcmpi(md.mesh.hemisphere,'n'), options=addfielddefault(options,'hemisphere','n'); 
+elseif strcmpi(md.mesh.hemisphere,'s'), options=addfielddefault(options,'hemisphere','s'); 
+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
+if exist(options,'xlabel');
+	xlabel(getfieldvalue(options,'xlabel'),'FontSize',fontsize,'FontWeight',fontweight);
+end
+
+%ylabel
+if exist(options,'ylabel');
+	ylabel(getfieldvalue(options,'ylabel'),'FontSize',fontsize,'FontWeight',fontweight);
+end
+
+%zlabel
+if exist(options,'zlabel');
+	zlabel(getfieldvalue(options,'zlabel'),'FontSize',fontsize,'FontWeight',fontweight);
+end
+
+%xtikcs
+if exist(options,'xtick'), set(gca,'XTick',getfieldvalue(options,'xtick')); end
+if exist(options,'ytick'), set(gca,'YTick',getfieldvalue(options,'ytick')); end
+if exist(options,'ztick'), set(gca,'ZTick',getfieldvalue(options,'ztick')); end
+
+%view 
+if md.mesh.dimension==3 & ~exist(options,'layer'),
+	view(getfieldvalue(options,'view',3));
+else
+	view(getfieldvalue(options,'view',2));
+end
+
+%axis
+set(gca,'FontSize',getfieldvalue(options,'axisfontsize',fontsize));;
+if exist(options,'axis')
+	eval(['axis ' getfieldvalue(options,'axis')]);
+else
+	if ((md.mesh.dimension==2) | exist(options,'layer')),
+		axis tight equal;
+	else
+		axis auto tight
+	end
+end
+
+%box
+if exist(options,'box')
+	eval(['box ' getfieldvalue(options,'box')]);
+end
+
+%xlim
+if exist(options,'xlim');
+	xlim(getfieldvalue(options,'xlim'));
+end
+
+%ylim
+if exist(options,'ylim');
+	ylim(getfieldvalue(options,'ylim'));
+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
+
+
+%zlim
+if exist(options,'zlim');
+	zlim(getfieldvalue(options,'zlim'));
+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
+if exist(options,'colormap'),
+	cname=getfieldvalue(options,'colormap');
+	if strcmpi(cname,'Ala'),
+		c = jet(64);
+		c = c (32:end,:);
+	elseif strcmpi(cname,'redblue'),
+		%m = 30;
+		%n = fix(0.5*m);
+		%r = [(0:1:n-1)/n,ones(1,n)];
+		%g = [(0:n-1)/n, (n-1:-1:0)/n];
+		%b = [ones(1,n),(n-1:-1:0)/n];
+		%c = [r(:), g(:), b(:)]; 
+
+		c = hsv(64);
+		c = rgb2hsv(c);
+		c(:,2) = max(min( abs(c(:,1)-0.5)/0.5 ,1),0);
+		c(1:32,1)   = 0.7;
+		c(33:end,1) = 1;
+		c = hsv2rgb(c);
+
+	elseif strcmpi(cname,'Rignot'),
+		c = hsv;
+
+		%adjust saturation
+		c = rgb2hsv(c);
+		alpha=getfieldvalue(options,'alpha',1);
+		c(:,2) = max(min( (0.1+c(:,1)).^(1/alpha) ,1),0);
+		c = hsv2rgb(c);
+
+	elseif strcmpi(cname,'Rignot2'),
+		c = hsv;
+
+		%adjust saturation
+		c = rgb2hsv(c);
+		alpha=getfieldvalue(options,'alpha',1);
+		c(:,2) = max(min( (0.1+c(:,1)).^(1/alpha) ,1),0);
+		c = hsv2rgb(c);
+
+		c=flipud(c);
+
+	else
+		c = cname;
+	end
+	h=colormap(c);
+else
+	h=colormap(jet(60));
+end
+
+%wrapping
+if exist(options,'wrapping'),
+	if ~exist(options,'colormap'),
+		h=jet;
+	end
+	colormap(repmat(h,getfieldvalue(options,'wrapping',1),1));
+end
+
+%colorbar
+if getfieldvalue(options,'colorbar',1)==1,
+	if exist(options,'colorbarcornerposition'),
+		c=colorbar(getfieldvalue(options,'colorbarcornerposition'),'peer',gca);
+	else 
+		c=colorbar('peer',gca);
+	end
+	set(c,'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'YColor',getfieldvalue(options,'FontColor','k'));
+	if exist(options,'wrapping')
+		lim=get(c,'Ylim');
+		lim=[lim(1) lim(1)+(lim(2)-lim(1))/getfieldvalue(options,'wrapping')];
+		set(c,'Ylim',lim);
+	end
+	if exist(options,'colorbarpos'),
+		set(c,'Position',getfieldvalue(options,'colorbarpos'));
+	end
+	if exist(options,'log'),
+		nlab=5;
+		logvalue=getfieldvalue(options,'log');
+
+		scaleminmax=caxis;
+		Min=min(scaleminmax);
+		Max=max(scaleminmax);
+		set(c,'YLim',[Min Max]); % set colorbar limits
+		set(c,'YTick',linspace(Min,Max,nlab));     % set tick mark locations
+
+		labels = cell(1,nlab);
+		tick_vals = linspace(Min,Max,nlab);
+		tick_vals = exp(log(logvalue)*tick_vals);
+		warning off MATLAB:log:logOfZero;
+		for i = 1:nlab
+			labels{i} = sprintf('%-3.4g',round_ice(tick_vals(i),2));
+			%labels{i} = sprintf('%-.4g',round_ice(tick_vals(i),2));
+		end
+		warning on MATLAB:log:logOfZero;
+		set(c,'YTickLabel',labels);
+	end
+	if exist(options,'colorbartitle'),
+		set(get(c,'title'),'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'String',getfieldvalue(options,'colorbartitle'),...
+			'Color',getfieldvalue(options,'FontColor','k'));
+	end
+	if exist(options,'colorbarYLabel'),
+		set(get(c,'Ylabel'),'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'String',getfieldvalue(options,'colorbarYLabel'),...
+			'Color',getfieldvalue(options,'FontColor','k'),'Interpreter',getfieldvalue(options,'Interpreter','none'));
+	end
+	if exist(options,'colorbarwidth'),
+		posaxes=get(gca,'Position');
+		alpha=getfieldvalue(options,'colorbarwidth',1);
+		position=get(c,'Position');
+		dx=position(3);
+		newdx=dx*alpha;
+		position(1)=position(1)+(dx-newdx)/2;
+		position(3)=newdx;
+		set(c,'Position',position);
+		set(gca,'Position',posaxes);
+	end
+	if exist(options,'colorbarheight'),
+		posaxes=get(gca,'Position');
+		alpha=getfieldvalue(options,'colorbarheight',1);
+		position=get(c,'Position');
+		dy=position(4);
+		newdy=dy*alpha;
+		position(2)=position(2)+(dy-newdy)/2;
+		position(4)=newdy;
+		set(c,'Position',position);
+		set(gca,'Position',posaxes);
+	end
+
+
+elseif getfieldvalue(options,'colorbar',1)==0,
+	colorbar('off');
+else
+	%do nothing
+	
+end
+
+
+%area
+if exist(options,'area'),
+	antzoom(getfieldvalue(options,'area'));
+end
+
+%expdisp
+filename=(getfieldvalue(options,'expdisp'));
+style=(getfieldvalue(options,'expstyle'));
+for i=1:length(getfieldvalue(options,'expdisp')),
+	filenamei=filename{i};
+	stylei=style{i};
+	expdisp(filenamei,gcf,stylei,getfieldvalue(options,'linewidth',1),getfieldvalue(options,'unit',1));
+end
+
+%text (default value is empty, not NaN...)
+if exist(options,'text');
+	textstring=getfieldvalue(options,'text');
+	textweight=getfieldvalue(options,'textweight','b');
+	textsize=getfieldvalue(options,'textsize');
+	textcolor=getfieldvalue(options,'textcolor');
+	textposition=getfieldvalue(options,'textposition');
+	textrotation=getfieldvalue(options,'textrotation');
+	for i=1:length(getfieldvalue(options,'text'));
+		textstringi=textstring{i};
+		textweighti=textweight{i};
+		textsizei=textsize{i};
+		textcolori=textcolor{i};
+		textpositioni=textposition{i};
+		textrotationi=textrotation{i};
+		h=text(textpositioni(1),textpositioni(2),textstringi,'FontSize',textsizei,'FontWeight',textweighti,'Color',textcolori,'Rotation',textrotationi);
+		set(h,'Clipping','on'); %prevent text from appearing outside of the box
+	end
+end
+
+%north arrow
+if exist(options,'northarrow'),
+	northarrow(getfieldvalue(options,'northarrow'));
+end
+
+%Scale ruler
+if exist(options,'scaleruler'),
+	scaleruler(options);
+end
+
+%streamliness
+if exist(options,'streamlines'),
+	plot_streamlines(md,options);
+end
+
+%contours
+if exist(options,'contourlevels'),
+	plot_contour(md,data,options);
+end
+
+%YTickLabel
+if exist(options,'yticklabel'),
+	set(gca,'YTickLabel',getfieldvalue(options,'YTickLabel'));
+end
+
+%XTickLabel
+if exist(options,'xticklabel'),
+	set(gca,'XTickLabel',getfieldvalue(options,'XTickLabel'));
+end
+
+%xtick
+if exist(options,'xtick'),
+	set(gca,'xtick',getfieldvalue(options,'xtick'));
+end
+
+%ytick
+if exist(options,'ytick'),
+	set(gca,'ytick',getfieldvalue(options,'ytick'));
+end
+
+%Axis positions
+if exist(options,'offsetaxispos'),
+	offset=getfieldvalue(options,'offsetaxispos');
+	P=get(gca,'pos');
+	P(1)=P(1)+offset(1);
+	P(2)=P(2)+offset(2);
+	P(3)=P(3)+offset(3);
+	P(3)=P(4)+offset(4);
+	set(gca,'pos',P);
+end
+if exist(options,'axispos'),
+	Axis=getfieldvalue(options,'axispos');
+	set(gca,'pos',Axis);
+end
+
+
+%position of figure
+if exist(options,'figposition'),
+	
+	figposition=getfieldvalue(options,'figposition');
+	if ischar(figposition),
+		if strcmpi(figposition,'larour'),
+			set(gcf,'Position',[1604 4 1594 1177]);
+		elseif strcmpi(figposition,'larour2'),
+			set(gcf,'Position',[756    62   827   504]);
+		elseif strcmpi(figposition,'mathieu'),
+			set(gcf,'Position',[300 1 1580 1150]);
+		elseif strcmpi(figposition,'fullscreen'),
+			set(gcf,'Position',get(0,'ScreenSize'));
+		elseif strcmpi(figposition,'halfright'),
+			screen=get(0,'ScreenSize');
+			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+			set(gcf,'Position',fix([left+widt/2 bott widt/2 heig]));
+		elseif strcmpi(figposition,'halfleft'),
+			screen=get(0,'ScreenSize');
+			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+			set(gcf,'Position',fix([left bott widt/2 heig]));
+		elseif strcmpi(figposition,'portrait'),
+			%reformat with letter paper size (8.5" x 11")
+			screen=get(0,'ScreenSize');
+			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+			portrait=fix([left+widt-(heig*8.5/11) bott heig*8.5/11 heig]);
+			set(gcf,'Position',portrait)
+		elseif strcmpi(figposition,'landscape'),
+			%reformat with letter paper size (8.5" x 11")
+			screen=get(0,'ScreenSize');
+			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+			landscape=fix([left+widt-(heig*11/8.5) bott heig*11/8.5 heig]);
+			set(gcf,'Position',landscape)
+		else
+			disp('''figposition'' string not supported yet');
+		end
+	else
+		set(gcf,'Position',figposition);
+	end
+
+end
+
+%axes position
+if exist(options,'axesPosition')
+	set(gca,'Position',getfieldvalue(options,'axesPosition'));
+end
+
+%showregion
+if strcmpi(getfieldvalue(options,'showregion','off'),'on'),
+	%Keep pointer of main axis
+	maingca=gca;
+	%get inset relative position (x,y,width,height)
+	insetpos=getfieldvalue(options,'insetpos',[0.02 0.70 0.18 0.18]);
+	%get current plos position
+	cplotpos=get(maingca,'pos');
+	%compute inset position
+	PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
+	axes('pos',PosInset);
+	axis equal off
+	%box off
+	if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
+		A=expread([ issmdir() '/projects/Exp/GreenlandBoxFront.exp']);
+		[A.x A.y]=ll2xy(A.x,A.y,+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s') | strcmpi(md.mesh.hemisphere,'south'),
+		A=expread([ issmdir() '/projects/Exp/Antarctica.exp']);
+	else
+		error('applyoptions error message: hemisphere not defined');
+	end
+	Ax=[min(A.x) max(A.x)];
+	Ay=[min(A.y) max(A.y)];
+	%if we are zooming on a basin, don't take the mesh for the boundaries!
+	if exist(options,'basin'),
+		[mdx mdy]=basinzoom(options);
+	else
+		offset=3*10^4;
+		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
+
+%backgroundcolor
+set(gca,'color',getfieldvalue(options,'backgroundcolor','none'));
+
+%figurebackgrounbcolor
+set(gcf,'color',getfieldvalue(options,'figurebackgroundcolor','w'));
+
+%lighting
+if strcmpi(getfieldvalue(options,'light','off'),'on'),
+	set(gca,'FaceLighting','gouraud','FaceColor','interp','AmbientStrength',0.5);
+	light('Position',[0 0.1 0.1],'Style','infinite');
+end
+
+%cloud of points: 
+if exist(options,'cloud'),
+	field=getfieldvalue(options,'cloud');
+	x=field(:,1);
+	y=field(:,2);
+	%unit multiplier:
+	if exist(options,'unit'),
+		unit=getfieldvalue(options,'unit');
+		x=x*unit;
+		y=y*unit;
+	end
+	hold on,p=plot(x,y,'k.');
+	markersize=getfieldvalue(options,'markersize',5);
+	color=getfieldvalue(options,'cloudcolor','k');
+	set(p,'Color',color);
+end
+
+%========================%
+%OK VERY LAST STEP: INSET|
+%========================%
+if exist(options,'inset'),
+
+	%Keep pointer of main axis
+	maingca=gca;
+	%get inset relative position (x,y,width,height)
+	insetpos=getfieldvalue(options,'insetpos',[0.56 0.55 0.35 0.35]);
+	%get current plot position
+	cplotpos=get(gca,'pos');
+	%compute inset position
+	PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
+	%show pos
+	X1=getfieldvalue(options,'insetx',xlim);
+	Y1=getfieldvalue(options,'insety',ylim);
+	if strcmpi(getfieldvalue(options,'showinset','off'),'on')
+		line(X1([1 2 2 1 1]),Y1([1 1 2 2 1]),zeros(1,5),'Color','k','LineWidth',2);
+	end
+
+	%Get current figure
+	ax1=gca;
+
+	%plot inset
+	axes('pos',PosInset);
+	copyobj(get(ax1,'children'),gca);
+	patch('Faces',[1 2 3 4 1],'Vertices',[X1([1 2 2 1])' Y1([1 1 2 2])'],'FaceColor','None','EdgeColor','k','LineWidth',2);
+
+	%applay options
+	options=removefield(options,'text',0);
+	options=removefield(options,'title',0);
+	options=removefield(options,'xlabel',0);
+	options=removefield(options,'ylabel',0);
+	options=removefield(options,'inset',0);
+	options=removefield(options,'offsetaxispos',0);
+	options=removefield(options,'showregion',0);
+	options=changefieldvalue(options,'colorbar',0);
+	options=changefieldvalue(options,'latlon','off');
+	options=changefieldvalue(options,'axis','equal off');
+	options=changefieldvalue(options,'xlim',getfieldvalue(options,'insetx',xlim));
+	options=changefieldvalue(options,'ylim',getfieldvalue(options,'insety',ylim));
+	applyoptions(md,data,options);
+
+	%back to main gca
+	set(gcf,'CurrentAxes',maingca)
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/arrow.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/arrow.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/arrow.m	(revision 11330)
@@ -0,0 +1,60 @@
+function arrow(x0,y0,x1,y1,varargin)
+%ARROW - plot arrow, using (x0,y0) and (x1,y1) as initial and end points. options can be specified.
+%
+%   Usage:
+%      arrow(x1,y1,x2,y2,options)
+%      where options is a lit of paired arguments of string OR enums
+%      options can be: 
+%            'ratio': default .5 (ratio headarrow/length)
+%            'widthratio': default is 1/10 of length
+
+
+%recover options
+options=pairoptions(varargin{:});
+ratio=getfieldvalue(options,'ratio',.5);
+widthratio=getfieldvalue(options,'widthratio',.1);
+color=getfieldvalue(options,'color','k');
+
+%compute some values out of (x1,y1) and (x2,y2)
+length=sqrt((x1-x0)^2+(y1-y0)^2);
+width=length*widthratio;
+
+%Build the two points Ap and Bp
+x=zeros(2,1);
+y=zeros(2,1);
+x(1)=x0; y(1)=y0;
+x(2)=x1; y(2)=y1;
+
+Ap=[x(1)
+   y(1)];
+Bp=[x(2)
+   y(2)];
+
+%Build arrowhead first
+ang2=150*2*pi/360;
+rotation=[cos(ang2), sin(ang2); -sin(ang2), cos(ang2)];
+
+E=ratio*rotation*(Bp-Ap)+Bp;
+F=Bp;
+G=ratio*rotation'*(Bp-Ap)+Bp;
+H=Bp/4+E*3/8+G*3/8;
+
+%Build rectangle
+u=Bp-Ap;
+alpha=atan2(u(2),u(1));
+
+A=Ap-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+ B=H-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+C=H+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+D=Ap+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+
+%Plot arrow
+hold on
+p1=patch([A(1) B(1) C(1) D(1)],[A(2) B(2) C(2) D(2)],color);
+set(p1,'EdgeColor',color); set(p1,'FaceColor',color);
+p2=patch([E(1) F(1) G(1) H(1)],[E(2) F(2) G(2) H(2)],color);
+set(p2,'EdgeColor',color); set(p2,'FaceColor',color);
Index: /issm/trunk-jpl-damage/src/m/model/plot/checkplotoptions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/checkplotoptions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/checkplotoptions.m	(revision 11330)
@@ -0,0 +1,206 @@
+function options=checkplotoptions(md,options);
+%PARSE_OPTIONS - build a structure that holds all plot options
+%
+%   Usage:
+%      options=checkplotoptions(md,options);
+%
+%   See also: PLOTMODEL
+
+%units
+if exist(options,'unit'),
+	if strcmpi(getfieldvalue(options,'unit'),'km')
+		options=changefieldvalue(options,'unit',10^-3);
+	end
+	if strcmpi(getfieldvalue(options,'unit'),'100km')
+		options=changefieldvalue(options,'unit',10^-5);
+	end
+
+end
+
+%density
+if exist(options,'density'),
+	density=getfieldvalue(options,'density');
+	options=changefieldvalue(options,'density',abs(ceil(density)));
+end
+
+%Show section
+if exist(options,'showsection'),
+	if strcmpi(getfieldvalue(options,'showsection'),'on')
+		options=changefieldvalue(options,'showsection',4);
+	end
+end
+
+%smooth values
+if exist(options,'smooth'),
+	if strcmpi(getfieldvalue(options,'smooth'),'on')
+		options=changefieldvalue(options,'smooth',0);
+	end
+end
+
+%contouronly values
+if exist(options,'contouronly'),
+	if strcmpi(getfieldvalue(options,'contouronly'),'on')
+		options=changefieldvalue(options,'contouronly',1);
+	end
+end
+
+%Colorbar;
+if exist(options,'colorbar'),
+	if strcmpi(getfieldvalue(options,'colorbar'),'on')
+		options=changefieldvalue(options,'colorbar',1);
+	elseif strcmpi(getfieldvalue(options,'colorbar'),'off')
+			options=changefieldvalue(options,'colorbar',0);
+	end
+end
+	
+%text
+if exist(options,'text'),
+	%1: textvalue
+	textvalues=getfieldvalue(options,'text');
+	%ischar if only one expstyle -> create a cell
+	if ischar(textvalues),
+		textvalues={textvalues};
+		numtext=1;
+	elseif iscell(textvalues),
+		numtext=length(textvalues);
+	else
+		error('plot error message: ''text'' option should be either a string or a cell');
+	end
+
+	%2: textweight
+	if exist(options,'textweight'),
+		textweightvalues=getfieldvalue(options,'textweight');
+		%ischar if only one textweight -> create a cell
+		if ischar(textweightvalues),
+			textweightvalues={textweightvalues};
+		elseif ~iscell(textweightvalues);
+			error('plot error message: ''textweight'' option should be either a string or a cell');
+		end
+	else
+		textweightvalues={'n'};
+	end
+	textweightvalues=repmat(textweightvalues,1,numtext); textweightvalues(numtext+1:end)=[];
+	%3: textsize
+	if exist(options,'textsize'),
+		textsizevalues=getfieldvalue(options,'textsize');
+		%ischar if only one textsize -> create a cell
+		if isnumeric(textsizevalues),
+			textsizevalues={textsizevalues};
+		elseif ~iscell(textsizevalues);
+			error('plot error message: ''textsize'' option should be either a number or a cell');
+		end
+	else
+		textsizevalues={14};
+	end
+	textsizevalues=repmat(textsizevalues,1,numtext); textsizevalues(numtext+1:end)=[];
+	%4: textcolor
+	if exist(options,'textcolor'),
+		textcolorvalues=getfieldvalue(options,'textcolor');
+		%ischar if only one textcolor -> create a cell
+		if ischar(textcolorvalues),
+			textcolorvalues={textcolorvalues};
+		elseif ~iscell(textcolorvalues);
+			error('plot error message: ''textcolor'' option should be either a string or a cell');
+		end
+	else
+		textcolorvalues={'k'};
+	end
+	textcolorvalues=repmat(textcolorvalues,1,numtext); textcolorvalues(numtext+1:end)=[];
+	%4: textposition
+	if exist(options,'textposition'),
+		textpositionvalues=getfieldvalue(options,'textposition');
+		%ischar if only one textposition -> create a cell
+		if isnumeric(textpositionvalues),
+			textpositionvalues={textpositionvalues};
+		elseif ~iscell(textpositionvalues);
+			error('plot error message: ''textposition'' option should be either a string or a cell');
+		end
+	else
+		error('plot error message: ''textposition'' option is missing');
+	end
+	%6: textrotation
+	if exist(options,'textrotation'),
+		textrotationvalues=getfieldvalue(options,'textrotation');
+		%ischar if only one textsize -> create a cell
+		if isnumeric(textrotationvalues),
+			textrotationvalues={textrotationvalues};
+		elseif ~iscell(textrotationvalues);
+			error('plot error message: ''textrotation'' option should be either a number or a cell');
+		end
+	else
+		textrotationvalues={0};
+	end
+	textrotationvalues=repmat(textrotationvalues,1,numtext); textrotationvalues(numtext+1:end)=[];
+	options=changefieldvalue(options,'text',textvalues);
+	options=changefieldvalue(options,'textsize',textsizevalues);
+	options=changefieldvalue(options,'textweight',textweightvalues);
+	options=changefieldvalue(options,'textcolor',textcolorvalues);
+	options=changefieldvalue(options,'textposition',textpositionvalues);
+	options=changefieldvalue(options,'textrotation',textrotationvalues);
+end
+
+%expdisp
+expdispvaluesarray=cell(0,0);
+expstylevaluesarray=cell(0,0);
+expstylevalues=cell(0,0);
+if exist(options,'expstyle'),
+	expstylevalues=getfieldvalue(options,'expstyle');
+	%ischar if only one expstyle -> create a cell
+	if ischar(expstylevalues),
+		expstylevalues={expstylevalues};
+	end
+end
+if exist(options,'expdisp'),
+	expdispvalues=getfieldvalue(options,'expdisp');
+	%ischar if only one expstyle -> create a cell
+	if ischar(expdispvalues),
+		expdispvalues={expdispvalues};
+	end
+	for i=1:length(expdispvalues)
+		expdispvaluesarray{end+1}=expdispvalues{i};
+		if (length(expstylevalues)>=i),
+			expstylevaluesarray{end+1}=expstylevalues{i};
+		else
+			expstylevaluesarray{end+1}='g-';
+		end
+	end
+end
+options=changefieldvalue(options,'expstyle',expstylevaluesarray);
+options=changefieldvalue(options,'expdisp',expdispvaluesarray);
+
+%latlonnumbering
+if exist(options,'latlonclick'),
+	if strcmpi(getfieldvalue(options,'latlonclick'),'on')
+		options=changefieldvalue(options,'latlonclick',1);
+	end
+end
+
+%north arrow
+if exist(options,'northarrow'),
+	if strcmpi(getfieldvalue(options,'northarrow'),'on')
+		%default values
+		Lx=max(md.mesh.y)-min(md.mesh.y);
+		Ly=max(md.mesh.y)-min(md.mesh.y);
+		%default values
+		options=changefieldvalue(options,'northarrow',[min(md.mesh.x)+1/6*Lx   min(md.mesh.y)+5/6*Ly   1/15*Ly   0.25   1/250*Ly]);
+	end
+end
+
+%scale ruler
+if exist(options,'scaleruler'),
+	if strcmpi(getfieldvalue(options,'scaleruler'),'on')
+		%default values
+		Lx=max(md.mesh.y)-min(md.mesh.y);
+		Ly=max(md.mesh.y)-min(md.mesh.y);
+		%default values
+		options=changefieldvalue(options,'scaleruler',[min(md.mesh.x)+6/8*Lx   min(md.mesh.y)+1/10*Ly   10^(ceil(log10(Lx)))/5 floor(Lx/100) 5]);
+	end
+end
+
+%Log scale (LOTS of changes to be performed
+if exist(options,'log'),
+	if exist(options,'caxis')
+		options=changefieldvalue(options,'caxis',log(getfieldvalue(options,'caxis'))/log(getfieldvalue(options,'log')));
+	end
+	options=changefieldvalue(options,'cutoff',log(getfieldvalue(options,'cutoff',1.5))/log(getfieldvalue(options,'log')));
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/imagescnan.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/imagescnan.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/imagescnan.m	(revision 11330)
@@ -0,0 +1,303 @@
+function [h,hcb] = imagescnan(x,y,U,varargin)
+%IMAGESCNAN Scale data and display as image with uncolored NaNs.
+%
+%   Syntax
+%               imagescnan(x,y,U)
+%               imagescnan(x,y,U,...,colormask)
+%               imagescnan(x,y,U,...,color)
+%               imagescnan(x,y,U,...,cbfit_opt)
+%           h = imagescnan(...);
+%     [h,hcb] = imagescnan(...,cbfit_opt);
+%
+%   Input:
+%     x          - X-axis vector data. Optional, i.e., can be empty.
+%                  Default: 1:n (rows index).
+%     y          - Y-axis vector data. Optional, i.e., can be empty.
+%                  Default: 1:m (column index).
+%     U          - Matrix [m x n] data or an RGB image [m x n x 3] (with/
+%                  without NaNs). 
+%     colormask  - Logical matrix indicating the U elements to be
+%                  uncolored, if is empty then ISNAN(U) is used. Or it can
+%                  be a single value which will be uncolored.
+%                  Default: ~isfinite(U) (NaNs and Infs elements uncolored)
+%     color      - A vector with 3 elements specifying the [R G B] color
+%                  for the NaNs color. It can be specified by the known
+%                  char colors: 'k', etcerera. Optional.  
+%                  Default: get(gca,'color') (axes background color)
+%     cbfit_opt  - Cell array with the options to call COLORBARFIT.
+%                  Default: COLORBARFIT function is not used by default.
+%
+%   Output:
+%     h   - Image handle. Optional
+%     hcb - Colorbar handle. Optional
+%
+%   Description:
+%      This function draws a matrix data as an image with uncolored NaN's
+%      elements using IMAGESC. The difference between IMAGESC and the
+%      PCOLOR, MESH or SURF function is that EVERY element is colored and
+%      no one is interpolated, besides, the pixels are centered with the
+%      axis value, although it is a flat image.
+%
+%      The color mask is added because IMAGESC do not work with NaN's, in
+%      fact it colors them with the lower value of the current colormap.
+%      
+%      The cbfit_opt is include in order to be able to define a diferent
+%      color map with the COLORBARFIT function which can be found at:
+%           http://www.mathworks.com/matlabcentral/fileexchange/.
+%      If this function is not found, a normal COLORBAR is generated.
+%
+%      The data and the colorbar are scaled with the current colormap, so,
+%      the use of COLORMAP after this function doesn't affects the
+%      generated image and colorbar! Therefore, COLORMAP and CAXIS should
+%      be used before this function.
+%
+%      Notes: * The inputs arguments for the COLORBARFIT function are 3
+%               plus the normal COLORBAR function options, for this reason,
+%               if the former is not found, the latter is used ignoring
+%               these first 3 options. Anyway, to generate a colorbar, at
+%               least an empty cell is needed for cbfit_opt = {[]}.
+%   
+%   Examples:
+%
+%      % Compares with normal IMAGESC:
+%       N = 100;
+%       PNaNs = 0.10;
+%       X = peaks(N);
+%       X(round(1 + (N^2-1).*rand(N^2*PNaNs,1))) = NaN;
+%       subplot(221), imagesc(X)
+%        title('With IMAGESC: ugly NaNs')
+%       subplot(222), imagescnan([],[],X) 
+%        title('With IMAGESCNAN: uncolored NaNs')
+%
+%      % Compares with SPY:
+%       subplot(223), spy(isnan(X))
+%        title('SPY NaNs')
+%       subplot(224), imagescnan([],[],isnan(X),0), axis equal tight
+%        title('No-NaNs with IMAGESCNAN')
+%
+%   See also IMAGE, IMAGESC, COLORBAR, IMREAD, IMWRITE and COLORBARFIT by
+%   Carlos Vargas. 
+
+%   Copyright 2008 Carlos Adrian Vargas Aguilera
+%   $Revision: 1.1 $  $Date: 2009/04/03 22:56:05 $
+
+%   Written by
+%   M.S. Carlos Adrian Vargas Aguilera
+%   Physical Oceanography PhD candidate
+%   CICESE 
+%   Mexico, 2008
+%   nubeobscura@hotmail.com
+%
+%   Download from:
+%   http://www.mathworks.com/matlabcentral/fileexchange/loadAuthor.do?objec
+%   tType=author&objectId=1093874
+
+%   1.0     Released (30/06/2008)
+%   1.1     Fixed bug when CAXIS used.
+%   1.2     Colorbar freezed colormap.
+%   1.3     Fixed bug in color vector input (Found by Greg King) and now
+%           accets RGB image as input.
+
+%% INPUTS:
+
+% Error checking:
+% Note: At least 3 inputs and no more than 6:
+if nargin<3 || nargin>6
+ error('Imagescnan:IncorrectInputNumber',...
+       'Input arguments must be at least 3 and less than 7.')
+end
+
+% Check the x,y,U:
+% Note: x,y should be the axes data.
+m = size(U);
+if numel(m)>3
+ error('Imagescnan:IncorrectInputSize',...
+       'Input image must be a matrix or an RGB image.')
+else
+ if isempty(x) || numel(x)~=m(2)
+  %warning('Imagescnan:IncorrectInputSize',...
+  %        'Index column axis has been used.')
+  x = 1:m(2); 
+ end
+ if isempty(y) || numel(y)~=m(1)
+  %warning('Imagescnan:IncorrectInputSize',...
+  %        'Index row axis has been used.')
+  y = 1:m(1); 
+ end
+end
+
+% Get color limits:
+% Note: If you would like to use specific color limits, use CAXIS before
+%       this function.
+switch get(gca,'CLimMode')
+ case 'manual'
+  clim = caxis;
+ otherwise
+  clim = [min(U(:)) max(U(:))];
+end
+
+% Parse inputs and defaults:
+% Note: * Mask color will be the not-finite elements plus the elements
+%         indicated by the user.
+%       * Default colormask is the current axes background.
+%       * Default currentmap is current figure colormap (probably JET).
+colormask = ~isfinite(U);
+color_nan = get(gca,'color');
+color_map = get(gcf,'colormap'); 
+cbfit_opt = [];
+ycolorbarfit = (exist('colorbarfit','file')==2);
+if nargin>3
+ while ~isempty(varargin)
+  if     iscell(varargin{1})
+   if length(varargin{1})<3
+    error('Imagescnan:IncorrectInputType',...
+     'Options for COLORBARFIT must be at least 3, although empty.')
+   end
+   caxis(clim)
+   cbfit_opt = varargin{1};
+   if ycolorbarfit
+    colorbarfit(cbfit_opt{:})
+    color_map = get(gcf,'colormap');
+   else
+    % warning('Imagescnan:ColorBarFitNotFound',...
+    %  'COLORBARFIT function not found, used default COLORBAR.') 
+   end
+   varargin(1) = [];
+  elseif ischar(varargin{1})
+   switch varargin{1}
+    case 'y', color_nan = [1 1 0];
+    case 'm', color_nan = [1 0 0];
+    case 'c', color_nan = [0 1 1];
+    case 'r', color_nan = [1 0 0];
+    case 'g', color_nan = [0 1 0];
+    case 'b', color_nan = [0 0 1];
+    case 'w', color_nan = [1 1 1];
+    case 'k', color_nan = [0 0 0];
+   otherwise
+   error('Imagescnan:InvalidColor',...
+    'Color char must be one of: ''ymcrgbwk''.')
+   end
+   varargin(1) = [];
+  elseif islogical(varargin{1})
+   if numel(varargin{1})~=numel(U)
+    error('Imagescnan:InvalidMask',...
+     'The logical mask must have the same elements as the matrix.')
+   end
+   colormask = varargin{1} | colormask;
+   varargin(1) = [];
+  elseif length(varargin{1})==3
+   if (max(varargin{1})>1) || (min(varargin{1})<0) % Fixed BUG 2008/07/11
+    error('Imagescnan:InvalidColor',...
+     'The color must be on the range of [0 1].')
+   end
+   color_nan = varargin{1};
+   varargin(1) = [];
+  elseif length(varargin{1})==1
+   colormask = (U==varargin{1}) | colormask;
+   varargin(1) = [];
+  else
+   error('Imagescnan:IncorrectInputType',...
+    'Incorrect optional(s) argument(s).')
+  end
+ end
+end
+
+
+%% MAIN:
+
+% Matrix data to RGB:
+if numel(m)==2
+
+ % Sets to double data:
+ if ~isfloat(U)
+  U = double(U);
+ end
+
+ % Normalizes and rounds data to range [0 N]:
+ N = size(color_map,1);
+ U = (U - clim(1))/diff(clim);          % Fixed bug when CAXIS used
+ U = U*N;
+ if N<=256
+  U = uint8(U);
+ else
+  U = uint16(U);
+ end
+
+ % Scales data with colormap:
+ U = ind2rgb(U,color_map);              % 2D to 3D RGB values [0 1]
+else
+ % Already is an RGB image, so do nothing.
+end
+
+ % Set mask color to color_nan:
+ mn = prod(m(1:2));
+ ind = find(colormask);
+ U(ind)      = color_nan(1); % Red color
+ U(ind+mn)   = color_nan(2); % Green color
+ U(ind+mn*2) = color_nan(3); % Blue color
+
+ % Draws the RGB image:
+ h = imagesc(x,y,U,clim);
+
+%% OUTPUTS:
+
+% Calls to colorbarfit and freezes his colormap:
+if ~isempty(cbfit_opt)
+ % Creates a temporary colorbar:
+ if ycolorbarfit
+  hcb   = colorbarfit(cbfit_opt{:});
+ else
+  Nopt = min([3 length(cbfit_opt)]);
+  cbfit_opt(1:Nopt) = [];
+  hcb   = colorbar(cbfit_opt{:});
+ end
+ % Save image position:
+ ha    = gca; position = get(ha,'Position'); 
+ % Gets colorbar axes properties:
+ ghcb  = get(hcb);
+ CData = ind2rgb(get(ghcb.Children,'CData'),color_map);
+ XData = get(ghcb.Children,'XData');
+ YData = get(ghcb.Children,'YData');
+ % Move ticks because IMAGESC draws them like centered pixels:
+ XTick = ghcb.XTick;
+ YTick = ghcb.YTick;
+ if ~isempty(XTick)
+  XTick = XTick(1:end-1) + diff(XTick(1:2))/2;
+ end
+ if ~isempty(YTick)
+  YTick = YTick(1:end-1) + diff(YTick(1:2))/2;
+ end
+ % Deletes the colorbar:
+ delete(hcb)            
+ % Generates other colorbar:
+ hcb = axes('Position',ghcb.Position);
+ hcbim = imagesc(XTick,YTick,CData,'Parent',hcb); axis tight
+ set(hcbim,...
+  'HitTest','off',...
+  'Interruptible','off',...
+  'SelectionHighlight','off',...
+  'Tag','TMW_COLORBAR',...
+  'XData',XData,...
+  'YData',YData)
+ set(hcb,...
+  'XAxisLocation',ghcb.XAxisLocation,...
+  'YAxisLocation',ghcb.YAxisLocation,...
+  'XLim',ghcb.XLim,...
+  'YLim',ghcb.YLim,...
+  'XDir',ghcb.XDir,...
+  'YDir',ghcb.YDir,...
+  'XTick',ghcb.XTick,...
+  'YTick',ghcb.YTick,...
+  'XTickLabel',ghcb.XTickLabel,...
+  'YTickLabel',ghcb.YTickLabel,...
+  'ButtonDownFcn',@resetCurrentAxes,...
+  'Interruptible','off',...
+  'Tag','Colorbar')
+ % Returns the image position:
+ axes(ha), set(ha,'Position',position)
+end
+
+% Sets output:
+if ~nargout
+ clear h
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/kmlgroundoverlay.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/kmlgroundoverlay.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/kmlgroundoverlay.m	(revision 11330)
@@ -0,0 +1,61 @@
+function kmlgroundoverlay(md,options);
+%KMLGROUNDOVERLAY: create ground overlay image in kml format
+%
+%
+%    options: 
+%         kmlfilename
+%         imagename
+%
+%    Usage: 
+%         kmlgroundoverlay(md,'kmlfilename','temp.kml','imagename','greenland.jpeg');
+%
+
+%first figure out if lat and long were computed!
+if (isempty(md.mesh.lat) | isempty(md.mesh.long)),
+	error('kmlgroundoverlay error message: project x,y onto lat,long fields of model!');
+end
+
+%process kml options
+kmlfilename=getfieldvalue(options,'kmlfilename','tempfile.kml');
+kmlroot=getfieldvalue(options,'kmlroot','./');
+kmlimagename=getfieldvalue(options,'kmlimagename','tempimage');
+kmlimagetype=getfieldvalue(options,'kmlimagetype','png');
+kmlresolution=getfieldvalue(options,'kmlresolution',1);
+kmlfolder=getfieldvalue(options,'kmlfolder','Ground Overlay');
+kmlfolderdescription=getfieldvalue(options,'kmlfolderdescription','');
+kmlgroundoverlayname=getfieldvalue(options,'kmlgroundoverlayname','');
+kmlgroundoverlaydescription=getfieldvalue(options,'kmlgroundoverlaydescription','');
+
+%figure out  min and max for lat and long of this image:
+west=min(md.mesh.long);
+east=max(md.mesh.long);
+south=min(md.mesh.lat);
+north=max(md.mesh.lat);
+
+%print image at high resolution
+printmodel([kmlroot '/' kmlimagename],kmlimagetype,'trim','on','resolution',kmlresolution,'margin','off','frame','off');
+
+%now write kml file
+fid=fopen([kmlroot '/' kmlfilename],'w');
+
+fprintf(fid,'%s\n','<?xml version="1.0" encoding="UTF-8"?>');
+fprintf(fid,'%s\n','<kml xmlns="http://www.opengis.net/kml/2.2">');
+fprintf(fid,'%s\n','<Folder>');
+fprintf(fid,'%s%s%s\n','<name>',kmlfolder,'</name>');
+fprintf(fid,'%s%s%s\n','<description>',kmlfolderdescription,'</description>');
+fprintf(fid,'%s\n','<GroundOverlay>');
+fprintf(fid,'%s%s%s\n','<name>',kmlgroundoverlayname,'</name>');
+fprintf(fid,'%s\n','<description>',kmlgroundoverlaydescription,'</description>');
+fprintf(fid,'%s%s.%s%s\n','<Icon>',kmlimagename,kmlimagetype,'</Icon>');
+fprintf(fid,'%s\n','<LatLonBox>');
+fprintf(fid,'%s%f%s\n','<north>',north,'</north>');
+fprintf(fid,'%s%f%s\n','<south>',south,'</south>');
+fprintf(fid,'%s%f%s\n','<east>',east,'</east>');
+fprintf(fid,'%s%f%s\n','<west>',west,'</west>');
+fprintf(fid,'%s\n','<rotation>0</rotation>');
+fprintf(fid,'%s\n','</LatLonBox>');
+fprintf(fid,'%s\n','</GroundOverlay>');
+fprintf(fid,'%s\n','</Folder>');
+fprintf(fid,'%s\n','</kml>');
+
+fclose(fid);
Index: /issm/trunk-jpl-damage/src/m/model/plot/latlonoverlay.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/latlonoverlay.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/latlonoverlay.m	(revision 11330)
@@ -0,0 +1,149 @@
+function latlonoverlay(md,options)
+%LATLONOVERLAY - overlay latitude and longitude lines on current figure
+%
+%   latstep,lonstep, in latitude and longitude degreees, between two latitudinal, longitudinal profiles.
+%   color: [1 1 1] for example
+%   resolution: profile resolution ( in lat,lon degrees) 
+%   gap: gap (in meters) to plug lat,lon degree numbers;
+%
+%   Usage:
+%      latlonoverlay(options)
+
+%get options
+latlon=getfieldvalue(options,'latlon');
+numbering=getfieldvalue(options,'latlonnumbering','off');
+latlonclick=getfieldvalue(options,'latlonclick',0);
+fontsize=getfieldvalue(options,'fontsize',16);
+
+%recover arguments (set default parameters if needed)
+%1: latlon
+if ~iscell(latlon),
+	if ischar(latlon) & strcmpi(latlon,'on'),
+		%defaults
+		latstep=3; lonstep=3;
+		resolution=0.1;
+		color=[1 0 1];
+	else return; end
+else
+	if length(latlon)<2
+		error('latlonoverlay error message: at least 2 arguments are required, or use ''on'' option.');
+	end
+	if length(latlon)>3, color=latlon{4};      else color=[1 1 1]; end
+	if length(latlon)>2, resolution=latlon{3}; else resolution=0.1;end
+	latstep=latlon{1};
+	lonstep=latlon{2};
+end
+
+%2: numbering
+if ~iscell(numbering) & isnan(numbering),
+	numbering=false;
+else
+	if ~iscell(numbering),
+		if strcmpi(char(numbering),'on'),
+			%defaults
+			latgap=2; longap=2;
+			colornumber=color;
+			latangle=0; lonangle=0;
+			numbering=true;
+		else
+			numbering=false;
+		end
+	else
+		latgap=numbering{1}; longap=numbering{2};
+		colornumber=numbering{3};
+		latangle=numbering{4}; lonangle=numbering{5};
+		numbering=true;
+	end
+end
+
+%what are the x and y limits
+xlimits=getfieldvalue(options,'xlim',xlim);
+ylimits=getfieldvalue(options,'ylim',ylim);
+
+%lat
+for lat=-90:latstep:90
+	longitudes=0:resolution:360;
+	latitudes =lat*ones(size(longitudes));
+
+	if strcmpi(md.mesh.hemisphere,'n'),
+		if lat<0, continue; end
+		[x,y]=ll2xy(latitudes,longitudes,+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		if lat>0, continue; end
+		[x,y]=ll2xy(latitudes,longitudes,-1, 0,71);
+	else error('field hemisphere should either be ''n'' or ''s'''); end
+
+	pos=find(x<=xlimits(2) & x>=xlimits(1) & y<=ylimits(2) & y>=ylimits(1));
+	if length(pos)<=1, continue; end
+	x=x(pos);y=y(pos);
+	l=line(x,y,'Color',color);
+
+	if numbering
+		ind=length(x)-2*latgap;
+		if (ind<=0), continue; end
+		xcorner=x(ind);            ycorner=y(ind);
+		xcorner2=x(max(ind-10,1)); ycorner2=y(max(ind-10,1));
+
+		if (xcorner>xlimits(1) & xcorner<xlimits(2) & ycorner>ylimits(1) & ycorner<ylimits(2)),
+			angle=mod((180)/pi*atan2((ycorner2-ycorner),(xcorner2-xcorner))+latangle,360);
+			if lat<0, label=[num2str(abs(lat)) '^{\circ}S'];
+			else      label=[num2str(abs(lat)) '^{\circ}N']; end
+			th=text(xcorner,ycorner,label);
+			set(th,'Color',colornumber,'Rotation',angle,'FontSize',fontsize,'HorizontalAlignment','center','VerticalAlignment','middle','Clipping','on');
+
+			%erase line and redraw it in two parts, to leave space for latitude number
+			delete(l);
+			line(x(1:ind-latgap),y(1:ind-latgap),'Color',color);hold on;
+			line(x(ind+latgap:end),y(ind+latgap:end),'Color',color);
+			set(gcf,'InvertHardcopy','off');
+		end
+
+	end
+end
+
+%lon
+for lon=-180:lonstep:180
+
+	if strcmpi(md.mesh.hemisphere,'n'),
+		latitudes =0:resolution:90;
+		longitudes=lon*ones(size(latitudes));
+		[x,y]=ll2xy(latitudes,longitudes,+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		latitudes =-90:resolution:0;
+		longitudes=lon*ones(size(latitudes));
+		[x,y]=ll2xy(latitudes,longitudes,-1, 0,71);
+	else
+		error('field hemisphere should either be ''n'' or ''s'''); 
+	end
+
+
+	pos=find(x<=xlimits(2) & x>=xlimits(1) & y<=ylimits(2) & y>=ylimits(1));
+	if length(pos)<=1, continue; end
+	x=x(pos);y=y(pos);
+	l=line(x,y,'Color',color);
+
+	if numbering,
+		ind=length(x)-2*longap;
+		if (ind<=0), continue; end
+		xcorner=x(ind);            ycorner=y(ind);
+		xcorner2=x(max(ind-10,1)); ycorner2=y(max(ind-10,1));
+
+		if (xcorner>xlimits(1) & xcorner<xlimits(2) & ycorner>ylimits(1) & ycorner<ylimits(2)),
+			angle=mod((180)/pi*atan2((ycorner2-ycorner),(xcorner2-xcorner))+lonangle,360);
+			if lon<0, label=[num2str(abs(lon)) '^{\circ}W'];
+			else      label=[num2str(abs(lon)) '^{\circ}E']; end
+			th=text(xcorner,ycorner,label);
+			set(th,'Color',colornumber,'Rotation',angle,'FontSize',fontsize,'HorizontalAlignment','center','VerticalAlignment','middle','Clipping','on');
+
+			%erase line and redraw it in two parts, to leave space for latitude number
+			delete(l);
+			line(x(1:ind-longap),y(1:ind-longap),'Color',color);hold on;
+			line(x(ind+longap:end),y(ind+longap:end),'Color',color);
+		end
+
+	end
+end
+
+%Back to original limits
+xlim(xlimits);
+ylim(ylimits);
Index: /issm/trunk-jpl-damage/src/m/model/plot/northarrow.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/northarrow.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/northarrow.m	(revision 11330)
@@ -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]]]');
+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*lengtharrow;
+yN=mean([A(2) F(2) H(2)]);
+text(xN,yN,'North','FontSize',fontsize,'FontWeight','b');
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_BC.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_BC.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_BC.m	(revision 11330)
@@ -0,0 +1,41 @@
+function plot_BC(md,options,width,i,data);
+
+%plot neuman
+plot_icefront(md,options,width,i,data)
+
+hold on
+
+%plot dirichlets
+h1=plot3(...
+	md.mesh.x(find(~isnan(md.diagnostic.spcvx(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.y(find(~isnan(md.diagnostic.spcvx(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.z(find(~isnan(md.diagnostic.spcvx(1:md.mesh.numberofvertices,1)))),...
+	'ro','MarkerSize',14,'MarkerFaceColor','r');
+h2=plot3(...
+	md.mesh.x(find(~isnan(md.diagnostic.spcvy(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.y(find(~isnan(md.diagnostic.spcvy(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.z(find(~isnan(md.diagnostic.spcvy(1:md.mesh.numberofvertices,1)))),...
+	'bo','MarkerSize',10,'MarkerFaceColor','b');
+h3=plot3(...
+	md.mesh.x(find(~isnan(md.diagnostic.spcvz(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.y(find(~isnan(md.diagnostic.spcvz(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.z(find(~isnan(md.diagnostic.spcvz(1:md.mesh.numberofvertices,1)))),...
+	'yo','MarkerSize',6 ,'MarkerFaceColor','y');
+
+%update legend
+[legend_h,object_h,plot_h,text_strings]=legend();
+legend('off');
+text_strings{end+1}='vx Dirichlet';
+text_strings{end+1}='vy Dirichlet';
+if h3, text_strings{end+1}='vz Dirichlet'; end
+plot_h(end+1)=h1;
+plot_h(end+1)=h2;
+if h3, plot_h(end+1)=h3; end
+legend(plot_h,text_strings,'location','NorthEast')
+
+hold off
+
+%apply options
+options=addfielddefault(options,'title','Boundary conditions');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_basaldrag.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_basaldrag.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_basaldrag.m	(revision 11330)
@@ -0,0 +1,53 @@
+function plot_basaldrag(md,options,width,i,type);
+
+%PLOT_BASALDRAG - plot basal drag
+%
+%   Usage:
+%      plot_basaldrag(md,options,width,i,type);
+%
+%   See also: PLOTMODEL
+
+%check layer
+if md.mesh.dimension==3,
+	if getfieldvalue(options,'layer',1)~=1;
+		disp('plot_basaldrag warning: basal drag is displayed in the lower layer')
+		changefieldvalue(options,'layer',1);
+	end
+end
+
+%compute exponents
+s=averaging(md,1./md.friction.p,0);
+r=averaging(md,md.friction.q./md.friction.p,0);
+
+%compute horizontal velocity
+if strcmpi(type,'basal_drag')
+	ub=sqrt(md.initialization.vx.^2+md.initialization.vy.^2)/md.constants.yts;
+elseif strcmpi(type,'basal_dragx')
+	ub=md.initialization.vx/md.constants.yts;
+elseif strcmpi(type,'basal_dragy')
+	ub=md.initialization.vy/md.constants.yts;
+end
+
+%compute basal drag
+drag=(max(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed),0)).^r.*(md.friction.coefficient).^2.*ub.^s/1000;
+
+%Figure out if this is a Section plot
+if exist(options,'sectionvalue')
+	plot_section(md,drag,options,width,i);
+	return;
+else
+
+	%process data and model
+	[x y z elements is2d isplanet]=processmesh(md,[],options);
+	[basal_drag datatype]=processdata(md,drag,options);
+
+	%plot basaldrag
+	subplot(width,width,i); 
+	plot_unit(x,y,z,elements,basal_drag,is2d,isplanet,datatype,options);
+
+	%apply options
+	options=addfielddefault(options,'title','Basal drag [kPa]');
+	options=addfielddefault(options,'view',2);
+	applyoptions(md,basal_drag,options);
+
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_boundaries.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_boundaries.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_boundaries.m	(revision 11330)
@@ -0,0 +1,39 @@
+function plot_boundaries(md,options,width,i);
+%PLOT_BOUNDARIES - plot mesh boundaries
+%
+%   Usage:
+%      plot_boundaries(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+subplot(width,width,i); 
+
+%process data and model
+if getfieldvalue(options,'layer',0)
+	options=removefield(options,'layer',1);
+end
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');hold on;
+end
+
+%plot rifts if present: 
+if isstruct(md.rifts.riftstruct),
+	for i=1:size(md.rifts.riftstruct,1),
+		segments=md.rifts.riftstruct(i).segments;
+		for j=1:size(segments,1),
+			plot(x(segments(j,1:2)),y(segments(j,1:2)),'r.-');
+		end
+		text(x(segments(floor(size(segments,1)/4),1)),y(segments(floor(size(segments,1)/4),1)),['Rift #' num2str(i)]);
+		%point out the tips
+		plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'b*');
+		plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'b*');
+	end
+end
+
+%apply options
+options=addfielddefault(options,'title','Mesh boundaries');
+options=addfielddefault(options,'colorbar',0);
+options=addfielddefault(options,'view',2);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_contour.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_contour.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_contour.m	(revision 11330)
@@ -0,0 +1,244 @@
+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);
+[data datatype]=processdata(md,datain,options);
+
+%check is2d
+if ~is2d,
+	error('plot_contour error message: contour not supported for 3d meshes, project on a layer');
+end
+
+%first, process data: must be on nodes
+if datatype==1,
+	%elements -> take average
+	data=averaging(md,data,0);
+elseif datatype==2,
+	%nodes -> do nothing
+elseif datatype==3,
+	%quiver -> take norm
+	data=sqrt(sum(datain.*datain,2));
+else
+	error('datatype not supported yet');
+end
+
+%prepare colors
+if exist(options,'contouronly')
+	%remove the previous plots
+	cla
+end
+color=getfieldvalue(options,'contourcolor','y');
+linewidth=getfieldvalue(options,'linewidth',1);
+
+%get contours levels
+contourlevels=getfieldvalue(options,'contourlevels');
+if isnumeric(contourlevels),
+	levels=round_ice(linspace(max(data),min(data),contourlevels),2);
+else
+	levels=[];
+	for i=1:length(contourlevels)
+		levels(end+1)=contourlevels{i};
+	end
+	levels=sort(unique(levels),'descend');
+end
+numlevels=length(levels);
+
+%initialization of some variables
+numberofelements=size(index,1);
+elementslist=1:numberofelements;
+c=[];
+h=[];
+
+%get unique edges in mesh
+%1: list of edges
+edges=[index(:,[1,2]); index(:,[2,3]); index(:,[3,1])];
+%2: find unique edges
+[edges,I,J]=unique(sort(edges,2),'rows');
+%3: unique edge numbers
+vec=J;
+%4: unique edges numbers in each triangle (2 triangles sharing the same edge will have
+%   the same edge number)
+edges_tria=[vec(elementslist), vec(elementslist+numberofelements), vec(elementslist+2*numberofelements)];
+
+%segments [nodes1 nodes2]
+Seg1=index(:,[1 2]);
+Seg2=index(:,[2 3]);
+Seg3=index(:,[3 1]);
+
+%segment numbers [1;4;6;...]
+Seg1_num=edges_tria(:,1);
+Seg2_num=edges_tria(:,2);
+Seg3_num=edges_tria(:,3);
+
+%value of data on each tips of the segments
+Data1=data(Seg1);
+Data2=data(Seg2);
+Data3=data(Seg3);
+
+%get the ranges for each segment
+Range1=sort(Data1,2);
+Range2=sort(Data2,2);
+Range3=sort(Data3,2);
+
+for i=1:numlevels
+
+	level=levels(i);
+
+	%find the segments that contain this value
+	pos1=(Range1(:,1)<level & Range1(:,2)>level);
+	pos2=(Range2(:,1)<level & Range2(:,2)>level);
+	pos3=(Range3(:,1)<level & Range3(:,2)>level);
+
+	%get elements
+	poselem12=(pos1 & pos2);
+	poselem13=(pos1 & pos3);
+	poselem23=(pos2 & pos3);
+	poselem=find(poselem12 | poselem13 | poselem23);
+	numelems=length(poselem);
+
+	%if no element has been flagged, skip to the next level
+	if numelems==0,
+		continue,
+	end
+
+	%go through the elements and build the coordinates for each segment (1 by element)
+	x1=zeros(numelems,1);
+	x2=zeros(numelems,1);
+	y1=zeros(numelems,1);
+	y2=zeros(numelems,1);
+	edge_l=zeros(numelems,2);
+
+	for j=1:numelems,
+
+		weight1=(level-Data1(poselem(j),1))/(Data1(poselem(j),2)-Data1(poselem(j),1));
+		weight2=(level-Data2(poselem(j),1))/(Data2(poselem(j),2)-Data2(poselem(j),1));
+		weight3=(level-Data3(poselem(j),1))/(Data3(poselem(j),2)-Data3(poselem(j),1));
+
+		if poselem12(poselem(j));
+
+			x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
+			x2(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
+			y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
+			y2(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
+			edge_l(j,1)=Seg1_num(poselem(j));
+			edge_l(j,2)=Seg2_num(poselem(j));
+
+		elseif poselem13(poselem(j)),
+
+			x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
+			x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
+			y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
+			y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
+			edge_l(j,1)=Seg1_num(poselem(j));
+			edge_l(j,2)=Seg3_num(poselem(j));
+
+		elseif poselem23(poselem(j)),
+
+			x1(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
+			x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
+			y1(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
+			y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
+			edge_l(j,1)=Seg2_num(poselem(j));
+			edge_l(j,2)=Seg3_num(poselem(j));
+		else
+			%it shoud not go here
+		end
+	end
+
+	%now that we have the segments, we must try to connect them...
+
+	%loop over the subcontours
+	while ~isempty(edge_l),
+
+		%take the right edge of the second segment and connect it to the next segments if any
+		e1=edge_l(1,1);   e2=edge_l(1,2);
+		xc=[x1(1);x2(1)]; yc=[y1(1);y2(1)];
+
+		%erase the lines corresponding to this edge
+		edge_l(1,:)=[];
+		x1(1)=[]; x2(1)=[];
+		y1(1)=[]; y2(1)=[];
+
+		[ro1,co1]=find(edge_l==e1);
+
+		while ~isempty(ro1)
+
+			if co1==1,
+				xc=[x2(ro1);xc]; yc=[y2(ro1);yc];
+
+				%next edge:
+				e1=edge_l(ro1,2);
+
+			else
+				xc=[x1(ro1);xc]; yc=[y1(ro1);yc];
+
+				%next edge:
+				e1=edge_l(ro1,1);
+			end
+
+			%erase the lines of this
+			edge_l(ro1,:)=[];
+			x1(ro1)=[]; x2(ro1)=[];
+			y1(ro1)=[]; y2(ro1)=[];
+
+			%next connection
+			[ro1,co1]=find(edge_l==e1);
+		end
+
+		%same thing the other way (to the right)
+		[ro2,co2]=find(edge_l==e2);
+
+		while ~isempty(ro2)
+
+			if co2==1,
+				xc=[xc;x2(ro2)]; yc=[yc;y2(ro2)];
+
+				%next edge:
+				e2=edge_l(ro2,2);
+			else
+				xc=[xc;x1(ro2)]; yc=[yc;y1(ro2)];
+
+				%next edge:
+				e2=edge_l(ro2,1);
+			end
+
+			%erase the lines of this
+			edge_l(ro2,:)=[];
+			x1(ro2)=[]; x2(ro2)=[];
+			y1(ro2)=[]; y2(ro2)=[];
+
+			%next connection
+			[ro2,co2]=find(edge_l==e2);
+		end
+
+		%we now have one subcontour ready to be plotted
+		zc=level*ones(length(xc)+1,1);
+		if getfieldvalue(options,'contouronly',0),
+			h=[h;patch('Xdata',[xc;NaN],'Ydata',[yc;NaN],'Zdata',zc,'Cdata',zc,'facecolor','none','edgecolor','flat','linewidth',linewidth)];
+			hold on      
+		else
+			h=[h;patch('Xdata',[xc;NaN],'Ydata',[yc;NaN],'facecolor','none','edgecolor',color,'linewidth',linewidth)];
+			hold on
+		end
+
+		% Update the CS data structure as per "contours.m"
+		% so that clabel works
+		c = horzcat(c,[level, xc'; length(xc), yc']);
+
+	end
+end
+
+%labels?
+if (~strcmpi(getfieldvalue(options,'contourticks','on'),'off') & ~isempty(c) & ~isempty(h))
+	if exist(options,'contouronly')
+		clabel(c,h);
+	else
+		clabel(c,h,'color',color,'FontSize',14);
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_drivingstress.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_drivingstress.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_drivingstress.m	(revision 11330)
@@ -0,0 +1,24 @@
+function plot_drivingstress(md,options,width,i);
+%PLOT_DRIVINGSTRESS - plot driving stress
+%
+%   Usage:
+%      plot_drivingstress(md,options,width,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+%get driving stress
+[sx sy s]=drivingstress(md);
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[dstress datatype]=processdata(md,s,options);
+dstress=dstress/1000;
+
+%plot mesh quivervel
+subplot(width,width,i); 
+plot_unit(x,y,z,elements,dstress,is2d,isplanet,datatype,options)
+
+%apply options
+options=addfielddefault(options,'title','Driving stress [kPa]');
+options=addfielddefault(options,'view',2);
+applyoptions(md,dstress,options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_edges.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_edges.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_edges.m	(revision 11330)
@@ -0,0 +1,34 @@
+function plot_edges(md,options,width,i,datai);
+%PLOT_SEGMENTS - plot edges, with different colors according to segment markers.
+%
+%   Usage:
+%      plot_edges(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+edges=md.mesh.edges;
+if isnan(edges)
+	error('edges in NaN')
+end
+
+if (md.mesh.dimension==2),
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+	text(sum(x(edges(:,1:2)),2)/2,sum(y(edges(:,1:2)),2)/2,sum(z(edges(:,1:2)),2)/2,...
+		num2str(transpose(1:size(edges,1))),...
+		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	error('plot_edges: 3d plot of edges not supported yet!');
+end
+
+%apply options
+options=addfielddefault(options,'title','Edges');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_elementnumbering.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_elementnumbering.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_elementnumbering.m	(revision 11330)
@@ -0,0 +1,57 @@
+function plot_elementnumbering(md,options,width,i);
+%PLOT_ELEMENTNUMBERING - plot element numbering
+%
+%   Usage:
+%      plot_elementnumbering(md,options,width,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+subplot(width,width,i); 
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[elementnumbers datatype]=processdata(md,[1:md.mesh.numberofelements]',options);
+
+%plot
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+
+	%numbering
+	text(sum(x(elements(:,1:3)),2)/3,sum(y(elements(:,1:3)),2)/3,sum(z(elements(:,1:3)),2)/3,...
+		num2str(transpose(1:size(elements,1))),...
+		'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+
+	%numbering
+	text(sum(x(elements(:,1:6)),2)/6,sum(y(elements(:,1:6)),2)/6,sum(z(elements(:,1:6)),2)/6,...
+		num2str(transpose(1:size(elements,1))),...
+		'HorizontalAlignment','center','VerticalAlignment','middle');
+end
+
+%apply options
+options=addfielddefault(options,'title','Element numbering');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_elementstype.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_elementstype.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_elementstype.m	(revision 11330)
@@ -0,0 +1,131 @@
+function plot_elementstype(md,options,width,i);
+%PLOT_ELEMENTSTYPE - plot elements type
+%
+%   Usage:
+%      plot_elementstype(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[data datatype]=processdata(md,md.flowequation.element_equation,options);
+
+%edgecolor?
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%plot
+subplot(width,width,i);
+
+if is2d
+	%Hutter elements
+	posH=find(data==1);
+	A=elements(posH,1); B=elements(posH,2); C=elements(posH,3); 
+	p1=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',1,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyeal element
+	posM=find(data==2);
+	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); 
+	p2=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',2,'FaceColor','flat','EdgeColor',edgecolor);
+	%Pattyn element
+	posP=find(data==3);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); 
+	p3=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',3,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyealPattyn element
+	posMP=find(data==5);
+	A=elements(posMP,1); B=elements(posMP,2); C=elements(posMP,3); 
+	p5=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',5,'FaceColor','flat','EdgeColor',edgecolor);
+	%Stokes elements
+	posS=find(data==4);
+	A=elements(posS,1); B=elements(posS,2); C=elements(posS,3); 
+	p6=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',4,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyealStokes elements
+	posMS=find(data==6);
+	A=elements(posMS,1); B=elements(posMS,2); C=elements(posMS,3); 
+	p7=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',6,'FaceColor','flat','EdgeColor',edgecolor);
+	%PattynStokes elements
+	posPS=find(data==7);
+	A=elements(posPS,1); B=elements(posPS,2); C=elements(posPS,3); 
+	p8=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',7,'FaceColor','flat','EdgeColor',edgecolor);
+	%None elements
+	posNONE=find(data==0);
+	A=elements(posNONE,1); B=elements(posNONE,2); C=elements(posNONE,3); 
+	p9=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',0,'FaceColor','flat','EdgeColor',edgecolor);
+
+	legend([p1 p2 p3 p5 p6 p7 p8 p9],...
+		'Hutter''s elements','MacAyeal''s elements','Pattyn''s elements',...
+		'MacAyealPattyn''s elements','Stokes''s elements','MacAyealStokes''s elements','PattynStokes''s elements','None element');
+
+else
+	%Hutter elements
+	posH=find(data==1);
+	A=elements(posH,1); B=elements(posH,2); C=elements(posH,3); D=elements(posH,4); E=elements(posH,5); F=elements(posH,6);
+	p1=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyeal elements
+	posM=find(data==2);
+	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); D=elements(posM,4); E=elements(posM,5); F=elements(posM,6);
+	p2=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	%Pattyn elements
+	posP=find(data==3);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
+	p3=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	%Stokes elements
+	posS=find(data==4);
+	A=elements(posS,1); B=elements(posS,2); C=elements(posS,3); D=elements(posS,4); E=elements(posS,5); F=elements(posS,6);
+	p4=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyealPattyn elements
+	posP=find(data==5);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
+	p5=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	%PattynStokes elements
+	PosPS=find(data==7);
+	A=elements(PosPS,1); B=elements(PosPS,2); C=elements(PosPS,3); D=elements(PosPS,4); E=elements(PosPS,5); F=elements(PosPS,6);
+	p6=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyealStokes elements
+	PosMS=find(data==6);
+	A=elements(PosMS,1); B=elements(PosMS,2); C=elements(PosMS,3); D=elements(PosMS,4); E=elements(PosMS,5); F=elements(PosMS,6);
+	p7=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	%None elements
+	PosNONE=find(data==0);
+	A=elements(PosNONE,1); B=elements(PosNONE,2); C=elements(PosNONE,3); D=elements(PosNONE,4); E=elements(PosNONE,5); F=elements(PosNONE,6);
+	p8=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+
+	legend([p1 p2 p3 p4 p5 p6 p7 p8],...
+		'Hutter''s elements','MacAyeal''s elements','Pattyn''s elements','Stokes''s elements',...
+		'MacAyealPattyn''s elements','PattynStokes''s elements','MacAyealStokes''s elements','None elements');
+end
+
+%apply options
+options=addfielddefault(options,'title','Elements type');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_gridded.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_gridded.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_gridded.m	(revision 11330)
@@ -0,0 +1,72 @@
+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
+
+whitepos=getfieldvalue(options,'whitepos',2); %1: up, 2: down, else: none
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[data datatype]=processdata(md,data,options);
+
+%check is2d
+if ~is2d, 
+	error('buildgridded error message: gridded not supported for 3d meshes, project on a layer');
+end
+
+%Get xlim and ylim (used to extract radar image)
+xlim=getfieldvalue(options,'xlim',[min(x) max(x)]);
+ylim=getfieldvalue(options,'ylim',[min(y) max(y)]);
+post=getfieldvalue(options,'posting',diff(xlim)/1000);
+
+%Interpolating data on grid
+[x_m y_m data_grid]=InterpFromMeshToGrid(elements,x,y,data,xlim(1),ylim(2),post,post,round(diff(ylim)/post),round(diff(xlim)/post),NaN);
+if size(data_grid,1)<3 | size(data_grid,2)<3,
+	error('data_grid size too small in plot_gridded, check posting and uni');
+end
+
+%Process data_grid: add white in NaN and correct caxis accordingly
+if exist(options,'caxis'),
+	caxis_opt=getfieldvalue(options,'caxis');
+	data_grid(find(data_grid<caxis_opt(1)))=caxis_opt(1);
+	data_grid(find(data_grid>caxis_opt(2)))=caxis_opt(2);
+	data_min=caxis_opt(1);
+	data_max=caxis_opt(2);
+else
+	data_min=min(data_grid(:));
+	data_max=max(data_grid(:));
+end
+if whitepos==1,
+	white  =data_max + (data_max-data_min)/55;
+	options=changefieldvalue(options,'caxis',[data_min white]);
+	data_grid(isnan(data_grid))=white;
+elseif whitepos==2,
+	white  =data_min - (data_max-data_min)/55;
+	options=changefieldvalue(options,'caxis',[white data_max]);
+	data_grid(isnan(data_grid))=white;
+end
+
+%Select plot area 
+subplot(plotlines,plotcols,i);
+
+%shading interp;
+h=imagesc(xlim,ylim,data_grid);set(gca,'YDir','normal');
+map=getfieldvalue(options,'colormap',jet);
+if whitepos==1,
+	map(end,:)=[1 1 1];
+elseif whitepos==2,
+	map(1,:)=[1 1 1];
+end
+options=changefieldvalue(options,'colormap',map);
+
+%last step: mesh gridded?
+if exist(options,'edgecolor'),
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch('Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',data_grid(1)*ones(size(x)),'FaceColor','none','EdgeColor',getfieldvalue(options,'edgecolor'));
+end
+
+%Apply options
+applyoptions(md,data,options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_highlightelements.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_highlightelements.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_highlightelements.m	(revision 11330)
@@ -0,0 +1,51 @@
+function plot_highlightelements(md,options,width,i);
+%PLOT_HIGHLIGHTELEMENTS - plot selected elements
+%
+%   Usage:
+%      plot_highlightelements(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[elementnumbers datatype]=processdata(md,[1:md.mesh.numberofelements]',options);
+
+%plot
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+end
+
+%apply options
+if ~exist(options,'highlight')
+	disp('highlightelements warning : highlight option empty, not element highlighted');
+end
+options=addfielddefault(options,'title','Highlighted Elements');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_highlightvertices.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_highlightvertices.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_highlightvertices.m	(revision 11330)
@@ -0,0 +1,46 @@
+function plot_highlightvertices(md,options,width,i);
+%PLOT_HIGHLIGHTVERTICES - plot selected vertices
+%
+%   Usage:
+%      plot_highlightvertices(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[nodenumbers datatype]=processdata(md,[1:md.mesh.numberofvertices]',options);
+
+%plot
+subplot(width,width,i); 
+
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+end
+
+%apply options
+if ~exist(options,'highlight')
+	disp('highlightvertices warning : highlight option empty, not node highlighted');
+end
+options=addfielddefault(options,'title','Highlighted Nodes');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_icefront.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_icefront.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_icefront.m	(revision 11330)
@@ -0,0 +1,106 @@
+function plot_icefront(md,options,width,i,data);
+%PLOT_ICEFRONT - plot segment on neumann BC
+%
+%   Usage:
+%      plot_icefront(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+icefront=md.diagnostic.icefront;
+
+if (md.mesh.dimension==2),
+
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	%highlight elements on neumann
+	pos=find(icefront(:,end)==1);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h2=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	pos=find(icefront(:,end)==0);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h3=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+
+	pos=find(icefront(:,end)==2);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h3bis=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+
+	%display arrows pointing outward
+	xstart=mean(x(icefront(:,1:end-2)),2);
+	ystart=mean(y(icefront(:,1:end-2)),2);
+	length=sqrt((x(icefront(:,1))-x(icefront(:,2))).^2 + (y(icefront(:,1))-y(icefront(:,2))).^2 );
+	normal(:,1)=cos(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
+	normal(:,2)=sin(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
+	xend=xstart+length.*normal(:,1);
+	yend=ystart+length.*normal(:,2);
+	q=quiver(xstart,ystart,xend-xstart,yend-ystart); hold on;
+	h4=plot(xstart,ystart,'r*');
+else
+
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	h1=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	%highlight elements on neumann
+	pos=find(icefront(:,end)==1);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	h2=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	pos=find(icefront(:,end)==0);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	h3=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	pos=find(icefront(:,end)==2);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	h3bis=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+
+	%display arrows pointing outward
+	xstart=mean(x(icefront(:,1:end-2)),2);
+	ystart=mean(y(icefront(:,1:end-2)),2);
+	zstart=mean(z(icefront(:,1:end-2)),2);
+	length=sqrt((x(icefront(:,1))-x(icefront(:,2))).^2 + (y(icefront(:,1))-y(icefront(:,2))).^2 );
+	normal(:,1)=cos(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
+	normal(:,2)=sin(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
+	xend=xstart+length.*normal(:,1);
+	yend=ystart+length.*normal(:,2);
+	q=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zeros(numel(xstart),1)); hold on;
+	h4=plot3(xstart,ystart,zstart,'r*');
+end
+
+%legend (disable warnings)
+warning off
+legend([h2,h3,h3bis,q],'element on ice front (Water)','element on ice front (Air)','element on ice front (Ice)','normal vectors')
+warning on
+
+%apply options
+options=addfielddefault(options,'title','Neumann boundary conditions');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_importancefactors.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_importancefactors.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_importancefactors.m	(revision 11330)
@@ -0,0 +1,83 @@
+function plot_importancefactors(md,options,width,ii);
+%PLOT_IMPORTANCEFACTORS - plot importance factors
+%
+%   Usage:
+%      plot_importancefactors(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%first recover design variable descriptor
+if exist(options,'designvariable'),
+	descriptor=getfieldvalue(options,'designvariable');
+else
+	error('plot_importancefactors error message: Need to supply design variable descriptor');
+end
+descriptorlength=length(descriptor);
+
+%then recover responsfunction name
+if exist(options,'responsefunction'),
+	responsefunctiondescriptor=getfieldvalue(options,'responsefunction');
+else
+	error('plot_importancefactors error message: Need to supply response function descriptor');
+end
+
+%go through all response functions and find the one corresponding to the correct responsefunctiondescriptor
+responsefunctions=md.qmu.results{2};
+found=0;
+for i=1:length(responsefunctions),
+	if strcmpi(responsefunctions(i).descriptor,responsefunctiondescriptor),
+		found=i;
+		break;
+	end
+end
+if ~found,
+	error('plot_importancefactors error message: could not find correct response function');
+end
+responsefunctions=responsefunctions(found);
+nfun=size(responsefunctions.desvar,1);
+
+%Now recover response to the correct desgin variable
+importancefactors=zeros(md.qmu.numberofpartitions,1);
+count=0;
+for i=1:nfun,
+	desvar=responsefunctions.desvar{i};
+	if strncmpi(desvar,descriptor,descriptorlength),
+		count=count+1;
+		importancefactors(count)=responsefunctions.impfac(i);
+	end
+end
+if count==0,
+	error('plot_importancefactors error message: could not find to response functions with corresponding design variable');
+end
+
+%log?
+if exist(options,'log'),
+	logvalue=getfieldvalue(options,'log');
+	importancefactors=log(importancefactors)/log(logvalue);
+end
+
+%Ok, get partitioning.
+[epart npart]=MeshPartition(md,md.qmu.numberofpartitions);
+
+%distribute importance factor
+nodeimportance=importancefactors(npart);
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%standard plot:
+subplot(width,width,ii);
+
+%ok, plot nodeimportance now.
+if is2d,
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', nodeimportance,'FaceColor','interp','EdgeColor',edgecolor);
+else
+	error('plot_importancefactors error message: 3d meshes not supported yet');
+end
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_manager.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_manager.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_manager.m	(revision 11330)
@@ -0,0 +1,198 @@
+function plot_manager(md,options,subplotwidth,nlines,ncols,i);
+%PLOT__MANAGER - distribute the plots, called by plotmodel
+%
+%   Usage:
+%      plot_manager(md,options,subplotwidth,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT
+
+%parse options and get a structure of options. 
+options=checkplotoptions(md,options);
+
+%get data to be displayed
+data=getfieldvalue(options,'data');
+
+%figure out if this is a special plot
+if ischar(data),
+
+	switch data,
+
+		case 'boundaries',
+			plot_boundaries(md,options,subplotwidth,i);
+			return;
+		case 'BC',
+			plot_BC(md,options,subplotwidth,i,data);
+			return;
+		case 'edges'
+			plot_edges(md,options,subplotwidth,i,data)
+			return
+		case 'elementnumbering',
+			plot_elementnumbering(md,options,subplotwidth,i);
+			return;
+		case 'highlightelements',
+			plot_highlightelements(md,options,subplotwidth,i);
+			return;
+		
+		case 'qmumean',
+			plot_qmumean(md,options,nlines,ncols,i);
+			return;
+		
+		case 'qmustddev',
+			plot_qmustddev(md,options,nlines,ncols,i);
+			return;
+		
+		case 'qmuhistnorm',
+			plot_qmuhistnorm(md,options,nlines,ncols,i);
+			return;
+
+		case 'qmu_mass_flux_segments',
+			plot_qmu_mass_flux_segments(md,options,nlines,ncols,i);
+			return;
+
+		case 'part_hist',
+			plot_parthist(md,options,nlines,ncols,i);
+			return;
+		case 'part_hist_n',
+			plot_parthistn(md,options,nlines,ncols,i);
+			return;
+		case 'part_hist_w',
+			plot_parthistw(md,options,nlines,ncols,i);
+			return;
+		case 'elements_type',
+			plot_elementstype(md,options,subplotwidth,i);
+			return;
+		case 'vertexnumbering',
+			plot_vertexnumbering(md,options,subplotwidth,i);
+			return;
+		case 'highlightvertices',
+			plot_highlightvertices(md,options,subplotwidth,i);
+			return;
+		case {'basal_drag','basal_dragx','basal_dragy'},
+			plot_basaldrag(md,options,subplotwidth,i,data);
+			return;
+		case 'driving_stress',
+			plot_drivingstress(md,options,subplotwidth,i);
+			return;
+		case 'mesh',
+			plot_mesh(md,options,nlines,ncols,i);
+			return;
+		case 'none',
+			if ~exist(options,'overlay'),
+				plot_none(md,options,nlines,ncols,i);
+				return;
+			end
+		case 'penalties',
+			plot_penalties(md,options,subplotwidth,i);
+			return;
+		case 'partition',
+			plot_partition(md,options,nlines,ncols,i);
+			return;
+		case 'referential',
+			plot_referential(md,options,nlines,ncols,i);
+			return;
+		case 'riftvel',
+			plot_riftvel(md,options,nlines,ncols,i);
+			return;
+		case 'riftnumbering',
+			plot_riftnumbering(md,options,nlines,ncols,i);
+			return;
+		case 'rifts',
+			plot_rifts(md,options,nlines,ncols,i);
+			return;
+		case 'riftrelvel',
+			plot_riftrelvel(md,options,nlines,ncols,i);
+			return;
+		case 'riftpenetration',
+			plot_riftpenetration(md,options,nlines,ncols,i);
+			return;
+		case 'riftfraction',
+			plot_riftfraction(md,options,nlines,ncols,i);
+			return;
+		case 'sarpwr',
+			plot_sarpwr(md,options,subplotwidth,i)
+			return
+		case 'icefront'
+			plot_icefront(md,options,subplotwidth,i,data)
+			return
+		case 'segments'
+			plot_segments(md,options,subplotwidth,i,data)
+			return
+		
+		case 'quiver'
+			data=[md.initialization.vx md.initialization.vy]; %Go ahead and try plot_unit
+
+		case {'strainrate_tensor','strainrate','strainrate_principal','strainrate_principalaxis1','strainrate_principalaxis2','strainrate_principalaxis3',...
+				'stress_tensor','stress','stress_principal','stress_principalaxis1','stress_principalaxis2','stress_principalaxis3',...
+				'deviatoricstress_tensor','deviatoricstress','deviatoricstress_principal','deviatoricstress_principalaxis1','deviatoricstress_principalaxis2','deviatoricstress_principalaxis3'},
+			plot_tensor(md,options,subplotwidth,i,data);
+			return;
+		case 'thermaltransient_results',
+			plot_thermaltransient_results(md,options,subplotwidth,i);
+			return;
+		case 'transient_movie',
+			plot_transient_movie(md,options,subplotwidth,i);
+			return;
+		case 'transient_results',
+			plot_transient_results(md,options,subplotwidth,i);
+
+		case 'transient_field',
+			plot_transient_field(md,options,subplotwidth,i);
+			return;
+
+	otherwise,
+
+		if ismember(data,properties('model')),
+			data=eval(['md.' data ';']);
+		else
+			error('plot error message: data provided not supported yet. Type plotdoc for help');
+		end
+	end
+end
+
+%Figure out if this is a semi-transparent plot.
+if exist(options,'overlay'),
+	plot_overlay(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%Figure out if this is a semi-transparent plot.
+if exist(options,'gridded'),
+	plot_gridded(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%Figure out if this is a Section plot
+if exist(options,'sectionvalue')
+	plot_section(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,data,options);
+[data2 datatype]=processdata(md,data,options);
+
+%standard plot:
+subplot(nlines,ncols,i);
+
+%plot unit
+plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options);
+
+%apply all options
+if datatype==3,
+	options=changefieldvalue(options,'colorbar',2);
+	if exist(options,'contourlevels'),
+		data2=data;
+	end
+end
+
+applyoptions(md,data2,options);
+
+%do ground overlay on kml plot_unit? 
+if (strcmpi(getfieldvalue(options,'kmlgroundoverlay','off'),'on')),
+	if ((nlines*ncols~=1) | (i~=1)),
+		error('cannot kmlgroundoverlay on multi-plots');
+	end
+	
+	%call routine to build kml file and image that goes with it.
+	kmlgroundoverlay(md,options);
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_mesh.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_mesh.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_mesh.m	(revision 11330)
@@ -0,0 +1,41 @@
+function plot_mesh(md,options,nlines,ncols,i);
+%PLOT_MESH - plot model mesh
+%
+%   Usage:
+%      plot_mesh(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+%retrieve some options
+linewidth=getfieldvalue(options,'linewidth',1);
+edgecolor=getfieldvalue(options,'edgecolor','black');
+
+%plot mesh
+if is2d
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+else
+	if ~isplanet,
+		A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+		patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+	else
+		A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+		if (size(elements,2)==4), D=elements(:,4); else D=C; end
+		patch( 'Faces', [A B C D],  'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+	end
+end
+
+%apply options
+options=addfielddefault(options,'title','Mesh');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_none.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_none.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_none.m	(revision 11330)
@@ -0,0 +1,20 @@
+function plot_none(md,options,nlines,ncols,i);
+%PLOT_NONE - plot nothing, just apply options
+%
+%   Usage:
+%      plot_mesh(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+return;
+
+options=addfielddefault(options,'colorbar','none');
+options=addfielddefault(options,'map','none');
+options=addfielddefault(options,'axis','equal');
+
+if exist(options,'overlay'),
+	plot_overlay(md,'none',options,nlines,ncols,i);
+	return;
+end
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_overlay.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_overlay.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_overlay.m	(revision 11330)
@@ -0,0 +1,141 @@
+function plot_overlay(md,data,options,plotlines,plotcols,i)
+%PLOT_OVERLAY - superimpose radar image to a given field
+%
+%   Usage:
+%      plot_overlay(md,options,plotlines,plotcols,i)
+%
+%   See also: PLOTMODEL
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+if strcmpi(data,'none'),
+	radaronly=1;
+	data=NaN*ones(md.mesh.numberofvertices,1);
+	datatype=1;
+else
+	radaronly=0;
+	[data datatype]=processdata(md,data,options);
+end
+
+%check is2d
+if ~is2d, 
+	error('buildoverlay error message: overlay not supported for 3d meshes, project on a layer');
+end
+if datatype==3,
+	error('buildoverlay error message: overlay not supported for quiver plots');
+end
+
+
+%radar power
+if ~any(isnan(md.radaroverlay.x)) & ~any(isnan(md.radaroverlay.y)) & ~any(isnan(md.radaroverlay.pwr)),
+	disp('plot_overlay info: the radar image held by the model is being used');
+	xlim=[min(md.radaroverlay.x) max(md.radaroverlay.x)];
+	ylim=[min(md.radaroverlay.y) max(md.radaroverlay.y)];
+else
+	disp('Extracting radar image...');
+	%Get xlim and ylim (used to extract radar image)
+	xlim=getfieldvalue(options,'xlim',[min(x) max(x)])/getfieldvalue(options,'unit',1);
+	ylim=getfieldvalue(options,'ylim',[min(y) max(y)])/getfieldvalue(options,'unit',1);
+	options=addfielddefault(options,'xlim',xlim);
+	options=addfielddefault(options,'ylim',ylim);
+	md=radarpower(md,options);
+end
+
+%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...');
+[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);
+
+%Process data_grid
+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));
+
+%Generate HSV image
+contrast=getfieldvalue(options,'contrast',1);  
+transparency=getfieldvalue(options,'alpha',1);
+data_grid(data_nan)=data_min; 
+
+colorm=getfieldvalue(options,'colormap','Rignot');
+if strcmpi(colorm,'Rignot'),
+	%hue (H)
+	h_data=(data_grid-data_min)/(data_max-data_min+eps);
+	if radaronly,
+		h_data(:)=0;
+	end
+	%saturation (S)
+	s_data=max(min((0.1+h_data).^(1/transparency),1),0);
+elseif strcmpi(colorm,'Seroussi'),
+	%hue (H)
+	h_data=1-(data_grid-data_min)/(data_max-data_min+eps)*0.7;
+	%h_data=(data_grid-data_min)/(data_max-data_min)*2/3;
+	if radaronly,
+		h_data(:)=0;
+	end
+	%saturation (S)
+	s_data=max(min((0.1+h_data).^(1/transparency),1),0);
+elseif strcmpi(colorm,'redblue')
+	data_mean=data_min+(data_max-data_min)/2;
+	%hue (H)
+	%h_data=0.7*ones(size(data_grid));
+	%h_data(find(data_grid>data_mean))=1;
+	h_data=1*ones(size(data_grid));
+	h_data(find(data_grid>data_mean))=0.7;
+	%saturation (S)
+	s_data=max(min(abs(data_grid-data_mean)/(data_max-data_mean) ,1),0);
+else
+	error('colormap not supported yet. (''Rignot'' and ''redblue'' are the only cupported colormaps)');
+end
+
+%Saturation is 0 in NaNs
+s_data(data_nan)=0;
+%intensity (V)
+radar=(md.radaroverlay.pwr).^(contrast);
+v_data=radar/max(radar(:)); %use radar power as intensity
+
+%Transform HSV to RGB
+image_hsv=zeros(size(data_grid,1),size(data_grid,2),3);
+image_hsv(:,:,1)=h_data;
+image_hsv(:,:,2)=s_data;
+image_hsv(:,:,3)=v_data;
+image_rgb=hsv2rgb(image_hsv);
+
+%Select plot area 
+subplot(plotlines,plotcols,i);
+
+%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'));
+end
+
+%Apply options, without colorbar and without grid
+options=changefieldvalue(options,'colormap',colorm);           %We used an HSV colorbar
+if ~isnan(data_min),
+	options=changefieldvalue(options,'caxis',[data_min data_max]); %force caxis so that the colorbar is ready
+end
+options=addfielddefault(options,'axis','equal off');           %default axis
+applyoptions(md,data,options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_parthist.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_parthist.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_parthist.m	(revision 11330)
@@ -0,0 +1,34 @@
+function plot_parthist(md,options,nlines,ncols,i);
+%PLOT_PARTHIST - plot partitioning histogram
+%
+%   Usage:
+%      plot_parthist(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+imin=min(md.qmu.partition);
+imax=max(md.qmu.partition);
+
+part=zeros(imax-imin+1,2);
+
+for i=imin:imax
+    ind=find(md.qmu.partition == i);
+    part(i-imin+1,1)=length(ind);
+	part(i-imin+1,2)=sum(md.vertex_weight(ind));
+end
+
+subplot(2,1,1)
+bar(imin:imax,part(:,1));
+xlim([imin-0.5 imax+0.5])
+title('Number of Nodes in Each Partition')
+
+subplot(2,1,2)
+bar(imin:imax,part(:,2));
+xlim([imin-0.5 imax+0.5])
+title('Total Weight in Each Partition')
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_parthistn.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_parthistn.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_parthistn.m	(revision 11330)
@@ -0,0 +1,43 @@
+function plot_parthist(md,options,nlines,ncols,i);
+%PLOT_PARTHIST - plot partitioning histogram
+%
+%   Usage:
+%      plot_parthist(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+imin=min(md.qmu.partition);
+imax=max(md.qmu.partition);
+
+part=zeros(imax-imin+1,2);
+
+for i=imin:imax
+    ind=find(md.qmu.partition == i);
+    part(i-imin+1,1)=length(ind);
+	part(i-imin+1,2)=sum(md.vertex_weight(ind));
+end
+
+%subplot(2,1,1)
+bar(imin:imax,part(:,1));
+%xlim([imin-0.5 imax+0.5])
+%title('Number of Nodes in Each Partition')
+options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+options=addfielddefault(options,'title','Number of Nodes in Each Partition');
+options=addfielddefault(options,'colorbar','off');
+
+%subplot(2,1,2)
+%bar(imin:imax,part(:,2));
+%xlim([imin-0.5 imax+0.5])
+%title('Total Weight in Each Partition')
+%options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+%options=addfielddefault(options,'title','Total Weight in Each Partition');
+%options=addfielddefault(options,'colorbar','off');
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_parthistw.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_parthistw.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_parthistw.m	(revision 11330)
@@ -0,0 +1,43 @@
+function plot_parthist(md,options,nlines,ncols,i);
+%PLOT_PARTHIST - plot partitioning histogram
+%
+%   Usage:
+%      plot_parthist(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+imin=min(md.qmu.partition);
+imax=max(md.qmu.partition);
+
+part=zeros(imax-imin+1,2);
+
+for i=imin:imax
+    ind=find(md.qmu.partition == i);
+    part(i-imin+1,1)=length(ind);
+	part(i-imin+1,2)=sum(md.vertex_weight(ind));
+end
+
+%subplot(2,1,1)
+%bar(imin:imax,part(:,1));
+%xlim([imin-0.5 imax+0.5])
+%title('Number of Nodes in Each Partition')
+%options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+%options=addfielddefault(options,'title','Number of Nodes in Each Partition');
+%options=addfielddefault(options,'colorbar','off');
+
+%subplot(2,1,2)
+bar(imin:imax,part(:,2));
+%xlim([imin-0.5 imax+0.5])
+%title('Total Weight in Each Partition')
+options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+options=addfielddefault(options,'title','Total Weight in Each Partition');
+options=addfielddefault(options,'colorbar','off');
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_penalties.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_penalties.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_penalties.m	(revision 11330)
@@ -0,0 +1,48 @@
+function plot_penalties(md,options,width,i);
+%PLOT_PENALTIES - plot penalties
+%
+%   Usage:
+%      plot_penalties(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh penalties
+subplot(width,width,i); 
+
+%units
+if exist(options,'unit'),
+	unit=getfieldvalue(options,'unit');
+	x=x*unit;
+	y=y*unit;
+	z=z*unit;
+end
+
+if ~md.mesh.dimension==3,
+	error('no penalties to plot for ''2d'' model');
+elseif isempty(md.penalties),
+	disp('no penalty applied in this model');
+	return;
+else
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	hold on;
+	for (i=1:size(md.penalties,1)),
+		P1=plot3(x(md.penalties(i,1)),y(md.penalties(i,1)),z(md.penalties(i,1)),'ro','MarkerSize',15,'MarkerFaceColor','r');
+		P2=plot3(x(md.penalties(i,:)),y(md.penalties(i,:)),z(md.penalties(i,:)),'bo-','LineWidth',2,'MarkerSize',8,'MarkerFaceColor','b');
+	end
+	legend([P1 P2],'MacAyeal''s penalized nodes','Pattyn''s penalized nodes');
+end
+
+%apply options
+options=addfielddefault(options,'title','Penalties');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_qmu_mass_flux_segments.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_qmu_mass_flux_segments.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_qmu_mass_flux_segments.m	(revision 11330)
@@ -0,0 +1,49 @@
+function plot_qmu_mass_flux_segments(md,options,nlines,ncols,i);
+%PLOT_QMU_MASS_FLUX_SEGMENTS - plot segments from the qmu analysis of mass fluxes
+%
+%   Usage:
+%      plot_qmu_mass_flux_segments(md,options,nlines,ncols,i);
+%
+
+subplot(nlines,ncols,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+allsegments=md.qmu.mass_flux_segments;
+
+if (md.mesh.dimension==2),
+
+	%recover segments
+	hold on
+	for i=1:length(allsegments),
+		segments=allsegments{i};
+
+		%plot semgnets
+		for j=1:length(segments),
+			plot([segments(j,1) segments(j,3)],[segments(j,2) segments(j,4)]);
+		end
+		text(segments(j,1),segments(j,2),['Profile #' num2str(i)]);
+
+		%plot normals
+		
+		for j=1:length(segments),
+			xstart=mean([segments(j,1) segments(j,3)]);
+			ystart=mean([segments(j,2) segments(j,4)]);
+			length1=sqrt((segments(j,1)-segments(j,3)).^2 + (segments(j,2)-segments(j,4)).^2);
+			normal(:,1)=cos(atan2(segments(j,1)-segments(j,3) , segments(j,4)-segments(j,2)));
+			normal(:,2)=sin(atan2(segments(j,1)-segments(j,3) , segments(j,4)-segments(j,2)));
+			xend=xstart+length1.*normal(:,1);
+			yend=ystart+length1.*normal(:,2);
+			plot([xstart xend],[ystart yend],'r-');
+		end
+
+	end
+else
+	error('plot_qmu_mass_flux_segments: 3d plot of segments not supported yet!');
+end
+
+%apply options
+options=addfielddefault(options,'title','Mass Flux segments and normals');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_qmuhistnorm.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_qmuhistnorm.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_qmuhistnorm.m	(revision 11330)
@@ -0,0 +1,48 @@
+function plot_qmuhistnorm(md,options,nlines,ncols,index);
+
+%prepare plot
+subplot(nlines,ncols,index); 
+hold on
+
+
+%recover histnorm data
+if ~exist(options,'qmudata')
+	error('plot_qmuhistnorm error message: option qmudata is required');
+else
+	qmudata=getfieldvalue(options,'qmudata');
+end
+
+%process options for the qmu plot: 
+
+%    hmin          (numeric, minimum for histogram)
+%    hmax          (numeric, maximum for histogram)
+%    hnint         (numeric, number of intervals for histogram)
+%    ymin1         (numeric, minimum of histogram y-axis)
+%    ymax1         (numeric, maximum of histogram y-axis)
+%    ymin2         (numeric, minimum of cdf y-axis)
+%    ymax2         (numeric, maximum of cdf y-axis)
+%    cdfplt        (char, 'off' to turn off cdf line plots)
+%    cdfleg        (char, 'off' to turn off cdf legends)
+%
+
+qmuoptions='';
+
+if exist(options,'hmin'), hmin=getfieldvalue(options,'hmin'); qmuoptions=[qmuoptions ',''hmin'',' num2str(hmin)]; end
+if exist(options,'hmax'), hmax=getfieldvalue(options,'hmax'); qmuoptions=[qmuoptions ',''hmax'',' num2str(hmax)]; end
+if exist(options,'hnint'), hnint=getfieldvalue(options,'hnint'); qmuoptions=[qmuoptions ',''hnint'',' num2str(hnint)]; end
+if exist(options,'ymin1'), ymin1=getfieldvalue(options,'ymin1'); qmuoptions=[qmuoptions ',''ymin1'',' num2str(ymin1)]; end
+if exist(options,'ymax1'), ymax1=getfieldvalue(options,'ymax1'); qmuoptions=[qmuoptions ',''ymax1'',' num2str(ymax1)]; end
+if exist(options,'ymin2'), ymin2=getfieldvalue(options,'ymin2'); qmuoptions=[qmuoptions ',''ymin2'',' num2str(ymin2)]; end
+if exist(options,'ymax2'), ymax2=getfieldvalue(options,'ymax2'); qmuoptions=[qmuoptions ',''ymax2'',' num2str(ymax2)]; end
+if exist(options,'cdfplt'), cdfplt=getfieldvalue(options,'cdfplt'); qmuoptions=[qmuoptions ',''cdfplt'',''' cdfplt '''']; end
+if exist(options,'cdfleg'), cdfleg=getfieldvalue(options,'cdfleg'); qmuoptions=[qmuoptions ',''cdfleg'',''' cdfleg '''']; end
+if exist(options,'nrmplt'), nrmplt=getfieldvalue(options,'nrmplt'); qmuoptions=[qmuoptions ',''nrmplt'',''' nrmplt '''']; end
+if exist(options,'EdgeColor'), EdgeColor=getfieldvalue(options,'EdgeColor'); qmuoptions=[qmuoptions ',''EdgeColor'',''' EdgeColor '''']; end
+if exist(options,'FaceColor'), FaceColor=getfieldvalue(options,'FaceColor'); qmuoptions=[qmuoptions ',''FaceColor'',''' FaceColor '''']; end
+
+%use qmu plot
+eval(['plot_hist_norm(qmudata' qmuoptions ');']);
+
+%apply options
+options=changefieldvalue(options,'colorbar','off');
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_qmumean.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_qmumean.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_qmumean.m	(revision 11330)
@@ -0,0 +1,59 @@
+function plot_qmumean(md,options,nlines,ncols,i);
+%PLOT_QMUMEAN - plot mean of a scaled response 
+%
+%   Usage:
+%      plot_qmumean(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%find response function
+if exist(options,'qmudata'), 
+	descriptor=getfieldvalue(options,'qmudata'); 
+	if ~ischar(descriptor),
+		error('plot_qmumean error message:  descriptor should be a string');
+	end
+else 
+	error('plot_qmumean error message:  provide descriptor of response function in ''qmudata'' option');
+end
+
+%go pick up the response: 
+allresponses=md.qmu.results.dresp_out;
+responses=zeros(md.qmu.numberofpartitions,1);
+
+count=1;
+for i=1:length(allresponses),
+	d=allresponses(i).descriptor;
+	if strncmpi(d,'scaled_',7),
+		d=d(8:end);
+		if strncmpi(d,descriptor,length(descriptor)),
+			responses(count)=allresponses(i).mean;
+			count=count+1;
+		end
+	end
+end
+
+%log?
+if exist(options,'log'),
+	responses=log(responses)/log(getfieldvalue(options,'log'));
+end
+
+%now, project onto vertices
+responses_on_node=responses(md.qmu.partition+1);
+
+%plot
+A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', responses_on_node,'FaceColor','interp','EdgeColor',edgecolor);
+
+%apply options
+options=addfielddefault(options,'title',['Mean distribution of ' descriptor]);
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_qmunormplot.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_qmunormplot.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_qmunormplot.m	(revision 11330)
@@ -0,0 +1,45 @@
+%
+%  plot a normal probability plot of the response functions.
+%
+%  []=plot_normplot(rfunc)
+%
+function []=plot_qmunormplot(rfunc,width,ii)
+
+if ~nargin
+    help plot_normplot
+    return
+end
+
+%%  assemble the data into a matrix
+
+desc=cell (1,length(rfunc));
+for i=1:length(rfunc)
+    ldata(i)=length(rfunc(i).sample);
+end
+data=zeros(max(ldata),length(rfunc));
+
+for i=1:length(rfunc)
+    desc(i)=cellstr(rfunc(i).descriptor);
+    data(1:ldata(i),i)=rfunc(i).sample;
+end
+
+%standard plot:
+subplot(width,width,ii);
+
+%%  draw the plot
+
+%  draw normal probability plot
+
+normplot(data)
+ax1=gca;
+
+%  add the annotation
+
+title('Normal Probability Plot of Design Variables and/or Response Functions')
+xlabel('Value')
+ylabel('Probability')
+
+hleg1=legend(ax1,desc,'Location','EastOutside',...
+             'Orientation','vertical','Interpreter','none');
+
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_qmustddev.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_qmustddev.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_qmustddev.m	(revision 11330)
@@ -0,0 +1,60 @@
+function plot_qmustddev(md,options,nlines,ncols,i);
+%PLOT_QMUMEAN - plot stddev of a scaled response 
+%
+%   Usage:
+%      plot_qmustddev(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%find response function
+if exist(options,'qmudata'), 
+	descriptor=getfieldvalue(options,'qmudata'); 
+	if ~ischar(descriptor),
+		error('plot_qmustddev error message:  descriptor should be a string');
+	end
+else 
+	error('plot_qmustddev error message:  provide descriptor of response function in ''qmudata'' option');
+end
+
+%go pick up the response: 
+allresponses=md.qmu.results.dresp_out;
+responses=zeros(md.qmu.numberofpartitions,1);
+
+count=1;
+for i=1:length(allresponses),
+	d=allresponses(i).descriptor;
+	if strncmpi(d,'scaled_',7),
+		d=d(8:end);
+		if strncmpi(d,descriptor,length(descriptor)),
+			responses(count)=allresponses(i).stddev/allresponses(i).mean*100;
+			count=count+1;
+		end
+	end
+end
+
+%log?
+if exist(options,'log'),
+	responses=log(responses)/log(getfieldvalue(options,'log'));
+end
+
+
+%now, project onto vertices
+responses_on_node=responses(md.qmu.partition+1);
+
+%plot
+A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', responses_on_node,'FaceColor','interp','EdgeColor',edgecolor);
+
+%apply options
+options=addfielddefault(options,'title',['Stddev  distribution of ' descriptor ' in %']);
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_quiver.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_quiver.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_quiver.m	(revision 11330)
@@ -0,0 +1,26 @@
+function plot_quiver(x,y,u,v,options),
+%PLOT_QUIVER - quiver plot with colors
+%
+%   to be perfected tomorrow
+%
+%   Usage:
+%      plot_quiver(x,y,u,v,options)
+%
+%   Example:
+%      plot_quiver(md.mesh.x,md.mesh.y,md.initialization.vx,md.initialization.vy,options);
+
+%process fields
+[quivers,palette]=quiver_process(x,y,u,v,options);
+
+%loop over the number of colors
+hold on
+h=[];
+for i=1:quivers.numcolors
+	pos=find(quivers.colorind==i);
+	hprime=quiver(quivers.x(pos),quivers.y(pos),quivers.u(pos),quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	h=[h;hprime];
+end
+
+%take care of colorbar
+quiver_colorbar(quivers,options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_quiver3.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_quiver3.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_quiver3.m	(revision 11330)
@@ -0,0 +1,104 @@
+function plot_quiver3(x,y,z,u,v,w,options),
+%PLOT_QUIVER3 - 3d quiver plot with colors
+%
+%   to be perfected tomorrow
+%
+%   Usage:
+%      plot_quiver3(x,y,z,u,v,w,options)
+%
+%   Example:
+%      plot_quiver(md.mesh.x,md.mesh.y,md.mesh.z,md.initialization.vx,md.initialization.vy,md.initialization.vz,options);
+
+%keep only non NaN elements
+pos=find(~isnan(x) & ~isnan(y) & ~isnan(z) & ~isnan(u) & ~isnan(v) & ~isnan(w));
+x=x(pos); y=y(pos); z=z(pos);
+u=u(pos); v=v(pos); w=w(pos);
+
+%get norm Min and Max
+Norm=sqrt(u.^2+v.^2+w.^2);
+Min=min(Norm);
+Max=max(Norm);
+
+%process options: scaling factor?
+scalingfactor=getfieldvalue(options,'scaling',0.40);
+
+%number of colors?
+colorlevels=getfieldvalue(options,'colorlevels',NaN);
+if isnumeric(colorlevels),
+	if isnan(colorlevels),
+		numcolors=30;
+	else
+		numcolors=colorlevels;
+	end
+	levels=round_ice(linspace(Min,Max,numcolors+1),2);
+else
+	levels=zeros(1,length(colorlevels)+2);
+	levels(1)=Min;
+	for i=1:length(colorlevels)
+		levels(i+1)=colorlevels{i};
+	end
+	levels(end)=Max;
+	levels=sort(unique(levels));
+	numcolors=length(levels)-1;
+end
+
+%set the colormap 
+if numcolors==2;
+	%blue and red
+	c=[0 0 1;1 0 0];
+elseif numcolors==3,
+	%blue yellow and red
+	c=[0 0 1;1 1 0;1 0 0];
+else
+	%let jet choose
+	c=colormap(jet(numcolors));
+end
+
+%Scale data
+if strcmpi(getfieldvalue(options,'autoscale','on'),'off'),
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./Norm;
+	v=scalingfactor*sqrt(delta)*v./Norm;
+else
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./max(Norm);
+	v=scalingfactor*sqrt(delta)*v./max(Norm);
+end
+
+%loop over the number of colors
+hold on
+h=[];
+for i=1:numcolors
+	pos=find( (Norm>=levels(i)) & (Norm<=levels(i+1)) );
+	hprime=quiver3(x(pos),y(pos),z(pos),u(pos),v(pos),w(pos),'Color',c(i,:),'ShowArrowHead','on','AutoScale','off');
+	h=[h;hprime];
+end
+
+%take care of colorbar
+if  ~strcmpi(getfieldvalue(options,'colorbar','on'),'off'),
+
+	%build ticks
+	hcb=colorbar('peer',gca,'location','EastOutside');
+	ticklabel=cell(1,length(levels));
+	for i=1:length(levels),
+		ticklabel{i}=num2str(round_ice(levels(i),3));
+	end
+	tickpos=1:numcolors+1;
+
+	%remove ticks if to many have been created
+	proportion=round(length(levels)/10);
+	if proportion>1,
+		ticklabel=ticklabel(1:proportion:end);
+		tickpos=tickpos(1:proportion:end);
+	end
+
+	%draw colorbar
+	set(hcb,'YTickLabel',ticklabel,'YTick',tickpos);
+	%position
+	if exist(options,'colorbarpos'),
+		set(hcb,'Position',getfieldvalue(options,'colorbarpos'));
+	end
+	%fontsize
+	fontsize=getfieldvalue(options,'fontsize',14);
+	set(hcb,'FontSize',fontsize);
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_referential.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_referential.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_referential.m	(revision 11330)
@@ -0,0 +1,91 @@
+function plot_referential(md,options,width,i,data);
+%PLOT_PRESSURELOAD - plot segment on neumann BC
+%
+%   Usage:
+%      plot_referential(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+referential=md.diagnostic.referential;
+
+Xhat=md.diagnostic.referential(:,1:3);
+pos=find(sum(isnan(Xhat),2));
+Xhat(pos,:)=repmat([1 0 0],size(pos,1),1);
+Xhatnorm=sqrt(Xhat(:,1).^2+Xhat(:,2).^2+Xhat(:,3).^2);
+Xhat=Xhat./[Xhatnorm Xhatnorm Xhatnorm];
+
+Zhat=md.diagnostic.referential(:,4:6);
+pos=find(sum(isnan(Zhat),2));
+Zhat(pos,:)=repmat([0 0 1],size(pos,1),1);
+Zhatnorm=sqrt(Zhat(:,1).^2+Zhat(:,2).^2+Zhat(:,3).^2);
+Zhat=Zhat./[Zhatnorm Zhatnorm Zhatnorm];
+
+Yhat=cross(Zhat,Xhat);
+
+if (md.mesh.dimension==2),
+
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	xstart=x;
+	ystart=y;
+	zstart=z;
+	edgex=max(md.mesh.x(elements),[],2)-min(md.mesh.x(elements),[],2);
+	len=min(edgex)/1.5;
+	%plot X axis
+	xend=xstart+len*Xhat(:,1);
+	yend=ystart+len*Xhat(:,2);
+	hx=quiver(xstart,ystart,xend-xstart,yend-ystart,'Color','blue','ShowArrowHead','on','AutoScale','off');
+	%plot Y axis
+	xend=xstart+len*Yhat(:,1);
+	yend=ystart+len*Yhat(:,2);
+	hy=quiver(xstart,ystart,xend-xstart,yend-ystart,'Color','red','ShowArrowHead','on','AutoScale','off');
+
+	legend([hx,hy],'local X direction','local Y direction')
+else
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	h1=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	xstart=x;
+	ystart=y;
+	zstart=z;
+	edgex=max(md.mesh.x(elements),[],2)-min(md.mesh.x(elements),[],2);
+	edgez=max(md.mesh.z(elements),[],2)-min(md.mesh.z(elements),[],2);
+	len=min(edgex)/1.5;
+	lenz=min(edgez)/1.5;
+	%plot X axis
+	xend=xstart+len*Xhat(:,1);
+	yend=ystart+len*Xhat(:,2);
+	zend=zstart+len*Xhat(:,3);
+	hx=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zend-zstart,'Color','blue','ShowArrowHead','on','AutoScale','off');
+	%plot Y axis
+	xend=xstart+len*Yhat(:,1);
+	yend=ystart+len*Yhat(:,2);
+	zend=zstart+len*Yhat(:,3);
+	hy=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zend-zstart,'Color','red','ShowArrowHead','on','AutoScale','off');
+	%plot Z axis
+	xend=xstart+lenz*Zhat(:,1);
+	yend=ystart+lenz*Zhat(:,2);
+	zend=zstart+lenz*Zhat(:,3);
+	hz=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zend-zstart,'Color','green','ShowArrowHead','on','AutoScale','off');
+
+	legend([hx,hy,hz],'local X direction','local Y direction','local Z direction')
+end
+
+%apply options
+options=addfielddefault(options,'title','Diagnostic referential');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_riftfraction.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_riftfraction.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_riftfraction.m	(revision 11330)
@@ -0,0 +1,48 @@
+function plot_riftfraction(md,options,nlines,ncols,index);
+%PLOT_RIFTFRACTION - plot rift fractions
+%
+%   Usage:
+%      plot_riftfraction(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%check that there is something in riftproperties
+if isnan(md.rifts.riftstruct.riftproperties),
+	error('plot_riftfraction error message: field riftproperies is empty, run the model first')
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');
+end
+
+%first, build a vector of fractions, over all nodes. 
+fractions=zeros(md.mesh.numberofvertices,1);
+
+%complete the tips.
+for i=1:length(md.rifts.riftstruct), 
+	tips=md.rifts.riftstruct(i).tips;
+	fractions(tips)=1;
+end
+
+hold on;
+for i=1:length(md.rifts.riftstruct), 
+	segments=md.rifts.riftstruct(i).segments(:,1:2)';
+	xc=x(segments(:));
+	yc=y(segments(:));
+	zc=fractions(segments(:));
+	h2=patch('Xdata',xc,'Ydata',yc,'Zdata',zc,'Cdata',zc,'facecolor','none','edgecolor','flat');
+end
+legend([h1,h2],'mesh boundaries','rifts')
+hold off
+
+%apply options
+options=addfielddefault(options,'title','Rift ice/water fraction ???????'); %Eric, could you enter a better title?
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_riftnumbering.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_riftnumbering.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_riftnumbering.m	(revision 11330)
@@ -0,0 +1,94 @@
+function plot_riftnumbering(md,options,nlines,ncols,index);
+%PLOT_RIFTNUMBERING - plot rift penetration + numbering of all rift vertices, as well as rift numbers.
+%
+%   Usage:
+%      plot_riftnumbering(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+fontsize=getfieldvalue(options,'FontSize',8);
+
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');
+end
+
+isp1=0;
+isp2=0;
+
+if isstruct(md.rifts.riftstruct),
+	%plot mesh boundaries
+	for i=1:size(md.mesh.segments,1),
+		h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+	end
+	for i=1:size(md.rifts.riftstruct,1),
+		penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+		segments=md.rifts.riftstruct(i).segments;
+		for j=1:size(segments,1),
+			plot(x(segments(j,1:2)),y(segments(j,1:2)),'b-');
+		end
+
+		normal=zeros(2,1);
+		for j=1:size(penaltypairs,1),
+			normal(1)=penaltypairs(j,5);
+			normal(2)=penaltypairs(j,6);
+
+			vx1=md.initialization.vx(penaltypairs(j,1)); 
+			vx2=md.initialization.vx(penaltypairs(j,2));
+			vy1=md.initialization.vy(penaltypairs(j,1)); 
+			vy2=md.initialization.vy(penaltypairs(j,2));
+			penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+			%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+			if(penetration>0),
+				p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ro-','LineWidth',1);
+				set(p2,'MarkerSize',3);
+				isp2=1;
+			else
+				p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ko-','LineWidth',1);
+				set(p1,'MarkerSize',3);
+				isp1=1;
+			end
+		end
+
+		%point out the tips
+		h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+		plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	end
+	if strcmpi(getfieldvalue(options,'legend','on'),'on'),
+		if isp1 & isp2
+			l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips','faults','rifts');
+		elseif isp1
+			l=legend([h1,h2,p1],'mesh boundaries','crack tips','faults');
+		elseif isp2
+			l=legend([h1,h2,p2],'mesh boundaries','crack tips','rifts');
+		else
+			l=legend([h1,h2],'mesh boundaries','crack tips');
+		end
+		set(l,'Location',getfieldvalue(options,'legend_location','NorthEast'));
+	end
+else
+	error('plot error message: no rifts available!');
+end
+
+%Now, plot rift vertices numbers.
+for i=1:size(md.rifts.riftstruct,1),
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+	for j=1:size(penaltypairs,1),
+		node=penaltypairs(j,1);
+		t=text(x(node),y(node),[num2str(i) '.' num2str(j)]);
+		set(t,'FontSize',fontsize);
+	end
+end
+
+
+%apply options
+options=addfielddefault(options,'title','Rift/Fault location');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_riftpenetration.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_riftpenetration.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_riftpenetration.m	(revision 11330)
@@ -0,0 +1,82 @@
+function plot_rifpenetration(md,options,nlines,ncols,index);
+%PLOT_RIFTPENETRATION - plot rift penetration
+%
+%   Usage:
+%      plot_rifpenetration(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k-');
+end
+
+isp1=0;
+isp2=0;
+
+if isstruct(md.rifts.riftstruct),
+	%plot mesh boundaries
+	for i=1:size(md.mesh.segments,1),
+		h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+	end
+	for i=1:size(md.rifts.riftstruct,1),
+		penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+		segments=md.rifts.riftstruct(i).segments;
+		for j=1:size(segments,1),
+			plot(x(segments(j,1:2)),y(segments(j,1:2)),'b-');
+		end
+
+		normal=zeros(2,1);
+		for j=1:size(penaltypairs,1),
+			normal(1)=penaltypairs(j,5);
+			normal(2)=penaltypairs(j,6);
+
+			vx1=md.initialization.vx(penaltypairs(j,1)); 
+			vx2=md.initialization.vx(penaltypairs(j,2));
+			vy1=md.initialization.vy(penaltypairs(j,1)); 
+			vy2=md.initialization.vy(penaltypairs(j,2));
+			penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+			%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+			if(penetration>0),
+				p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ro-','LineWidth',1);
+				set(p2,'MarkerSize',3);
+				isp2=1;
+			else
+				p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ko-','LineWidth',1);
+				set(p1,'MarkerSize',3);
+				isp1=1;
+			end
+		end
+
+		%point out the tips
+		h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+		plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	end
+	if strcmpi(getfieldvalue(options,'legend','on'),'on'),
+		if isp1 & isp2
+			l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips','faults','rifts');
+		elseif isp1
+			l=legend([h1,h2,p1],'mesh boundaries','crack tips','faults');
+		elseif isp2
+			l=legend([h1,h2,p2],'mesh boundaries','crack tips','rifts');
+		else
+			l=legend([h1,h2],'mesh boundaries','crack tips');
+		end
+		set(l,'Location',getfieldvalue(options,'legend_location','NorthEast'));
+	end
+else
+	error('plot error message: no rifts available!');
+end
+hold off
+
+%apply options
+options=addfielddefault(options,'title','Rift/Fault location');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_riftrelvel.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_riftrelvel.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_riftrelvel.m	(revision 11330)
@@ -0,0 +1,115 @@
+function plot_riftrelvel(md,options,nlines,ncols,index);
+%PLOT_RIFTRELVEL - plot rift relative velocities
+%
+%   Usage:
+%      plot_riftrelvel(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%some checks
+if (length(md.initialization.vx)~=md.mesh.numberofvertices | length(md.initialization.vy)~=md.mesh.numberofvertices),
+	error('plot_riftvel error message: vx and vy do not have the right size'),
+end
+if ~isstruct(md.rifts.riftstruct),
+	error('plot error message: no rifts available!');
+end
+options=addfielddefault(options,'scaling',2);
+
+%recover vx and vy:
+vx=getfieldvalue(options,'riftrelvel_vx',md.initialization.vx);
+vy=getfieldvalue(options,'riftrelvel_vy',md.initialization.vy);
+
+%set as NaN all velocities not on rifts
+u=NaN*ones(md.mesh.numberofvertices,1);
+v=NaN*ones(md.mesh.numberofvertices,1);
+for i=1:md.rifts.numrifts,
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs(:,[1 2]);
+	u(md.rifts.riftstruct(i).penaltypairs(:,1))=vx(penaltypairs(:,1))-vx(penaltypairs(:,2));
+	v(md.rifts.riftstruct(i).penaltypairs(:,1))=vy(penaltypairs(:,1))-vy(penaltypairs(:,2));
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[vel datatype]=processdata(md,[u v],options);
+[quivers,palette]=quiver_process(x,y,vel(:,1),vel(:,2),options);
+
+%prepare plot
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k-');
+end
+
+%plot rifts vel
+h3=[];
+for i=1:quivers.numcolors
+	pos=find(quivers.colorind==i);
+	hprime=quiver(quivers.x(pos),quivers.y(pos),quivers.u(pos),quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	hprime=quiver(quivers.x(pos),quivers.y(pos),-quivers.u(pos),-quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	h3=[h3;hprime];
+end
+
+%plot rift velocities
+isp1=0;
+isp2=0;
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+end
+for i=1:md.rifts.numrifts,
+	
+	%get nodes on rift
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+	segments=md.rifts.riftstruct(i).segments;
+	for j=1:size(segments,1),
+		plot(x(segments(j,1:2)),y(segments(j,1:2)),'k-');
+	end
+
+	normal=zeros(2,1);
+	for j=1:size(penaltypairs,1),
+		normal(1)=penaltypairs(j,5);
+		normal(2)=penaltypairs(j,6);
+
+		vx1=vx(penaltypairs(j,1)); vx2=vx(penaltypairs(j,2)); vy1=vy(penaltypairs(j,1)); vy2=vy(penaltypairs(j,2));
+		penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+		%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+		if(penetration>0),
+			p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'*'); set(p2,'Color',[140 140 140]/255);
+			isp2=1;
+		else
+			p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'k*');
+			isp1=1;
+		end
+	end
+
+	%point out the tips
+	h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+	plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	segments=md.rifts.riftstruct(i).segments(:,1:2);
+end
+%legend
+if strcmpi(getfieldvalue(options,'legend','on'),'on'),
+	if isp1 & isp2
+		l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips','faults','rifts');
+	elseif isp1
+		l=legend([h1,h2,p1],'mesh boundaries','crack tips','faults');
+	elseif isp2
+		l=legend([h1,h2,p2],'mesh boundaries','crack tips','rifts');
+	else
+		l=legend([h1,h2],'mesh boundaries','crack tips');
+	end
+set(l,'Location',getfieldvalue(options,'legend_location','NorthEast'));
+end
+hold off
+
+%apply options
+quiver_colorbar(quivers,options);
+options=changefieldvalue(options,'colorbar',2);
+options=addfielddefault(options,'title','Rift/Fault Relative Velocity');
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_rifts.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_rifts.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_rifts.m	(revision 11330)
@@ -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:md.rifts.numrifts,
+		penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+		normal=zeros(2,1);
+		for j=1:size(penaltypairs,1),
+			normal(1)=penaltypairs(j,5);
+			normal(2)=penaltypairs(j,6);
+			x(penaltypairs(j,1))=x(penaltypairs(j,1))-normal(1)*offset;
+			y(penaltypairs(j,1))=y(penaltypairs(j,1))-normal(2)*offset;
+		end
+		if length(md.rifts.riftstruct(i).tips)==3,
+			tip=md.rifts.riftstruct(i).tips(3);
+			%who is tip connected to? 
+			if isconnected(md.mesh.elements,penaltypairs(1,1),tip),
+				normal(1)=penaltypairs(1,5);
+				normal(2)=penaltypairs(1,6);
+				x(tip)=x(tip)-normal(1)*offset;
+				y(tip)=y(tip)-normal(2)*offset;
+			end
+
+			if isconnected(md.mesh.elements,penaltypairs(1,2),tip),
+				normal(1)=penaltypairs(1,5);
+				normal(2)=penaltypairs(1,6);
+				x(tip)=x(tip)+normal(1)*offset;
+				y(tip)=y(tip)+normal(2)*offset;
+			end
+			if isconnected(md.mesh.elements,penaltypairs(end,1),tip),
+				normal(1)=penaltypairs(end,5);
+				normal(2)=penaltypairs(end,6);
+				x(tip)=x(tip)-normal(1)*offset;
+				y(tip)=y(tip)-normal(2)*offset;
+			end
+			if isconnected(md.mesh.elements,penaltypairs(end,2),tip),
+				normal(1)=penaltypairs(end,5);
+				normal(2)=penaltypairs(end,6);
+				x(tip)=x(tip)+normal(1)*offset;
+				y(tip)=y(tip)+normal(2)*offset;
+			end
+		end
+	end
+end
+
+%plot mesh
+if is2d
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+else
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C ], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F ], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+end
+
+%apply options
+options=addfielddefault(options,'title','Rifts');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_riftvel.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_riftvel.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_riftvel.m	(revision 11330)
@@ -0,0 +1,108 @@
+function plot_riftvel(md,options,nlines,ncols,index);
+%PLOT_RIFTVEL - plot rift velocity
+%
+%   Usage:
+%      plot_riftvel(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%some checks
+if (length(md.initialization.vx)~=md.mesh.numberofvertices | length(md.initialization.vy)~=md.mesh.numberofvertices),
+	error('plot_riftvel error message: vx and vy do not have the right size'),
+end
+if ~isstruct(md.rifts.riftstruct),
+	error('plot error message: no rifts available!');
+end
+options=addfielddefault(options,'scaling',2);
+
+%set as NaN all velocities not on rifts
+u=NaN*ones(md.mesh.numberofvertices,1);
+v=NaN*ones(md.mesh.numberofvertices,1);
+for i=1:md.rifts.numrifts,
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs(:,[1 2]);
+	u(penaltypairs(:))=md.initialization.vx(penaltypairs(:));
+	v(penaltypairs(:))=md.initialization.vy(penaltypairs(:));
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[vel datatype]=processdata(md,[u v],options);
+[quivers,palette]=quiver_process(x,y,vel(:,1),vel(:,2),options);
+
+%prepare plot
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');
+end
+
+%plot rifts vel
+h3=[];
+for i=1:quivers.numcolors
+	pos=find(quivers.colorind==i);
+	hprime=quiver(quivers.x(pos),quivers.y(pos),quivers.u(pos),quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	h3=[h3;hprime];
+end
+
+%plot rift velocities
+isp1=0;
+isp2=0;
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+end
+
+for i=1:size(md.rifts.riftstruct,1),
+	%get nodes on rift
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+	segments=md.rifts.riftstruct(i).segments;
+	for j=1:size(segments,1),
+		plot(x(segments(j,1:2)),y(segments(j,1:2)),'b-');
+	end
+
+	normal=zeros(2,1);
+	for j=1:size(penaltypairs,1),
+		normal(1)=penaltypairs(j,5);
+		normal(2)=penaltypairs(j,6);
+
+		vx1=md.initialization.vx(penaltypairs(j,1)); vx2=md.initialization.vx(penaltypairs(j,2)); vy1=md.initialization.vy(penaltypairs(j,1)); vy2=md.initialization.vy(penaltypairs(j,2));
+		penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+		%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+		if(penetration>0),
+			p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'*'); set(p2,'Color',[140 140 140]/255);
+			isp2=1;
+		else
+			p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'k*');
+			isp1=1;
+		end
+	end
+
+	%point out the tips
+	h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+	plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	segments=md.rifts.riftstruct(i).segments(:,1:2);
+end
+
+
+%legend
+if isp1 & isp2
+	legend([h1,h2,p1,p2],'mesh boundaries','rift tips',' rifts closing','rifts opening')
+elseif isp1
+	legend([h1,h2,p1],'mesh boundaries','rift tips',' rifts closing')
+elseif isp2
+	legend([h1,h2,p2],'mesh boundaries','rift tips','rifts opening')
+else
+	legend([h1,h2],'mesh boundaries','rift tips')
+end
+hold off
+
+%apply options
+quiver_colorbar(quivers,options);
+options=changefieldvalue(options,'colorbar',2);
+options=addfielddefault(options,'title','Rift Velocities');
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_sarpwr.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_sarpwr.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_sarpwr.m	(revision 11330)
@@ -0,0 +1,26 @@
+function plot_sarpwr(md,options,width,i);
+%PLOT_SARPWR - plot radar image
+%
+%   Usage:
+%      plot_sarpwr(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh sarpwr
+subplot(width,width,i); 
+
+%units
+if exist(options,'unit'),
+	unit=getfieldvalue(options,'unit');
+	md.mesh.x=md.mesh.x*unit;
+	md.mesh.y=md.mesh.y*unit;
+	md.mesh.z=md.mesh.z*unit;
+end
+					
+imagesc(md.radaroverlay.x,md.radaroverlay.y,double(md.radaroverlay.pwr)),set(gca,'YDir','normal');colormap(gray);
+
+%apply options
+options=addfielddefault(options,'colorbar',0);
+options=changefieldvalue(options,'colormap','gray');
+
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_scatter.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_scatter.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_scatter.m	(revision 11330)
@@ -0,0 +1,74 @@
+function plot_scatter(x,y,mksize,level),
+
+%check input
+if numel(x)~=numel(y) | numel(x)~=numel(level),
+	error('x, y and data should have the same size');
+end
+
+%Some processing
+Min=min(level);
+Max=max(level);
+Siz=length(level);
+nlab=10;
+
+%OK, should we create a new colorbar for the occasion?
+if isempty(findobj(gcf,'tag','TMW_COLORBAR')),
+	alreadyplot=false;
+else
+	alreadyplot=true;
+end
+
+%generate levels
+if (alreadyplot),
+	phch = get(findall(gcf,'type','image','tag','TMW_COLORBAR'),{'parent'});
+	h    = phch{1};
+	ylim=get(h,'YLim');
+	palette=colormap;
+	numcolors=size(palette,1);
+	levels=round_ice(linspace(ylim(1),ylim(2),numcolors+1),2);
+else
+	numcolors=30;
+	levels=round_ice(linspace(Min,Max,numcolors+1),2);
+	palette=colormap(jet(numcolors));
+end
+
+colorind=ones(Siz,1);
+for i=1:numcolors
+	pos=find((level>=levels(i)) & (level<=levels(i+1)) );
+	colorind(pos)=i;
+end
+colorind(find(level>levels(end)))=numcolors;
+
+%loop over the number of colors
+hold on
+hp=[];
+for i=1:numcolors
+	pos=find(colorind==i);
+	hprime=plot(x(pos),y(pos),...
+		'o','MarkerSize',mksize,'MarkerEdgeColor',palette(i,:),...
+		'MarkerFaceColor',palette(i,:));
+	hp=[hp;hprime];
+end
+
+if ~alreadyplot,
+	% format the colorbar
+	h    = colorbar;
+	nlab = abs(nlab);                       % number of labels must be positive
+	set(h,'YLim',[1 numcolors]);                  % set colorbar limits
+	set(h,'YTick',linspace(1,numcolors,nlab));    % set tick mark locations
+
+	labels = cell(1,nlab);
+	tick_vals = linspace(Min,Max,nlab);
+	warning off MATLAB:log:logOfZero;
+	for i = 1:nlab
+		if min(log10(abs(tick_vals))) <= 3, fm = '%-4.0f';   % fixed
+		else                                fm = '%-4.0E';   % floating
+		end
+		labels{i} = sprintf(fm,tick_vals(i));
+	end
+	warning on MATLAB:log:logOfZero;
+
+	% set tick label strings
+	set(h,'YTickLabel',labels);
+	%colorbar %one last time required sometimes
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_section.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_section.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_section.m	(revision 11330)
@@ -0,0 +1,211 @@
+function plot_section(md,data,options,nlines,ncols,i)
+%PLOT_SECTION - plot a given field on a section
+%
+%   Usage:
+%      plot_section(md,data,options,nlines,ncols,i)
+%
+%   See also: PLOTMODEL
+
+%How many subplots?
+if exist(options,'showsection')
+
+	%Compute the indexes of the 2 plots (one for the sectionvalue and one for showsection
+	upperplots=floor((i-1)/ncols);
+	if upperplots==0, leftplots=i-1; else leftplots=i-ncols*upperplots-1; end
+	index1=4*ncols*upperplots+2*leftplots+1;
+	index2=index1+1;
+	ncols=2*ncols;
+else
+	index1=i;
+end
+
+%process model
+[x_m y_m z_m elements_m is2d isplanet]=processmesh(md,[],options);
+
+%Get number of curves and generate random colors
+numcurves=size(data,2);
+colorm=getfieldvalue(options,'colormap','lines');
+color=eval([ colorm '(numcurves);']);
+options=removefield(options,'colormap',0); %back to default colormap
+
+%replug x and y onto model so that SectionValue treats the problem correctly
+md3d=md;
+if exist(options,'layer')
+	md.mesh.x=md.mesh.x2d; md.mesh.y=md.mesh.y2d; md.mesh.elements=md.mesh.elements2d; md.mesh.dimension=2;
+end
+
+%read contours: 
+profiles=expread(getfieldvalue(options,'sectionvalue'),1);
+numprofiles=length(profiles);
+
+%Loop over number of profiles: 
+for profile_i=1:numprofiles,
+	profile=profiles(profile_i);
+
+	%Loop over number of curves
+	for i=1:numcurves,
+
+		[datai datatype]=processdata(md3d,data(:,i),options);
+
+		%resolution
+		if exist(options,'resolution'),
+			resolution=getfieldvalue(options,'resolution');
+		else %Default resolution
+			resolution=[1000 10*md.mesh.numberoflayers];
+			disp(['plot_section warning: no resolution specified, use default resolution: [horizontal_resolution vertical_resolution]=[' num2str(resolution)  ']']);
+		end
+
+		%Compute section value
+		[elements,x,y,z,s,data_s]=SectionValues(md,datai,profile,resolution);
+
+		%units
+		if exist(options,'unit'),
+			unit=getfieldvalue(options,'unit');
+			x=x*unit;
+			y=y*unit;
+			z=z*unit;
+			s=s*unit;
+		end
+
+		%2D
+		if is2d,
+%		%plot section value
+%		hold on;
+%		subplot(nlines,ncols,index1)
+%		%subplot(1,3,[2 3])
+%		plot(s,data_s,'color',color(i,:),'LineWidth',getfieldvalue(options,'linewidth',1))
+%		%3D
+%	else
+%		%plot section value
+%		%if user requested view2: 2d plot with curvilinear coordinate
+%		if (getfieldvalue(options,'view',3)==2 )
+
+			%Show Section if requested by user
+			if exist(options,'showsection')
+
+				%compute number of labels
+				numlabels=min(getfieldvalue(options,'showsection'),length(s));
+				shift=fix(length(s)/numlabels);
+
+				%plot labels on current graph
+				hold on
+				text(s(1),data_s(1),'1','backgroundcolor',[0.8 0.9 0.8])
+				for i=2:numlabels-1
+					text(s(1+(i-1)*shift),data_s(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+				end
+				text(s(end),data_s(end),'end','backgroundcolor',[0.8 0.9 0.8])
+
+				%plot section only with labels
+				subplot(nlines,ncols,index2)
+				plot_unit(x_m,y_m,z_m,elements_m,data(:,i),is2d,isplanet,datatype,options)
+				hold on
+				text(x(1),y(1),'1','backgroundcolor',[0.8 0.9 0.8])
+				for i=2:numlabels-1
+					text(x(1+(i-1)*shift),y(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+				end
+				text(x(end),y(end),'end','backgroundcolor',[0.8 0.9 0.8])
+				plot(x,y,'-r')
+				axis([min(md.mesh.x)-1 max(md.mesh.x)+1 min(md.mesh.y)-1 max(md.mesh.y)+1])
+				view(2)
+			end
+
+			%plot section value
+			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),z(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(s(1+(i-1)*shift),z(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(s(end),z(end),'end','backgroundcolor',[0.8 0.9 0.8])
+
+					%plot section only with labels
+					subplot(nlines,ncols,index2)
+					plot_unit(x_m,y_m,z_m,elements_m,data(:,i),is2d,datatype,options)
+					hold on
+					text(x(1),y(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(x(1+(i-1)*shift),y(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(x(end),y(end),'end','backgroundcolor',[0.8 0.9 0.8])
+					plot(x,y,'-r')
+					axis([min(md.mesh.x)-1 max(md.mesh.x)+1 min(md.mesh.y)-1 max(md.mesh.y)+1])
+					view(2)
+				end
+
+				subplot(nlines,ncols,index1)
+				A=elements(:,1); B=elements(:,2); C=elements(:,3);  D=elements(:,4); 
+				patch( 'Faces', [A B C D], 'Vertices', [s z zeros(length(s),1)],'FaceVertexCData',data_s,'FaceColor','interp','EdgeColor','none');
+
+			else
+
+				%Show Section if requested by user
+				if exist(options,'showsection')
+
+					%compute number of labels
+					numlabels=min(getfieldvalue(options,'showsection'),length(s));
+					shift=fix(length(x)/numlabels);
+
+					%plot labels on current graph
+					hold on
+					text(x(1),y(1),z(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(x(1+(i-1)*shift),y(1+(i-1)*shift),z(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(x(end),y(end),z(end),'end','backgroundcolor',[0.8 0.9 0.8])
+
+					%plot section only with labels
+					subplot(nlines,ncols,index2)
+					plot_unit(x_m,y_m,z_m,elements_m,data,is2d,datatype,options)
+					hold on
+					text(x(1),y(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(x(1+(i-1)*shift),y(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(x(end),y(end),'end','backgroundcolor',[0.8 0.9 0.8])
+					plot(x,y,'-r')
+					axis([min(md.mesh.x)-1 max(md.mesh.x)+1 min(md.mesh.y)-1 max(md.mesh.y)+1])
+					view(2)
+				end
+
+				subplot(nlines,ncols,index1)
+				A=elements(:,1); B=elements(:,2); C=elements(:,3);  D=elements(:,4); 
+				patch( 'Faces', [A B C D], 'Vertices', [x y z],'FaceVertexCData',data_s,'FaceColor','interp','EdgeColor','none');
+				view(3)
+
+			end
+		end
+	end
+end
+
+%apply options
+options=addfielddefault(options,'title','Section value');
+if (md.mesh.dimension==2)
+	options=addfielddefault(options,'colorbar',0);
+end
+if ((md.mesh.dimension==2) | getfieldvalue(options,'view')==2 )
+	options=addfielddefault(options,'xlabel','Curvilinear coordinate');
+	options=addfielddefault(options,'axis','auto');
+end
+if (md.mesh.dimension==3 & getfieldvalue(options,'view')==2 )
+	options=addfielddefault(options,'ylabel','z');
+end
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_segments.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_segments.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_segments.m	(revision 11330)
@@ -0,0 +1,57 @@
+function plot_segments(md,options,width,i,datai);
+%PLOT_SEGMENTS - plot segments, with different colors according to segment markers.
+%
+%   Usage:
+%      plot_segments(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+segments=md.mesh.segments;
+
+if (md.mesh.dimension==2),
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	%highlight elements on neumann
+	pos=segments(:,end);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h2=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+
+	if strcmpi(getfieldvalue(options,'segmentnumbering','off'),'on'),
+		text(sum(x(segments(:,1:2)),2)/2,sum(y(segments(:,1:2)),2)/2,sum(z(segments(:,1:2)),2)/2+1,...
+			num2str(md.mesh.segmentmarkers),...
+			'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+	end
+
+	%display arrows pointing outward
+	xstart=mean(x(segments(:,1:end-1)),2);
+	ystart=mean(y(segments(:,1:end-1)),2);
+	length=sqrt((x(segments(:,1))-x(segments(:,2))).^2 + (y(segments(:,1))-y(segments(:,2))).^2 );
+	normal(:,1)=cos(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+	normal(:,2)=sin(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+	xend=xstart+length.*normal(:,1);
+	yend=ystart+length.*normal(:,2);
+	q=quiver(xstart,ystart,xend-xstart,yend-ystart); hold on;
+	h3=plot(xstart,ystart,'r*');
+
+
+else
+	error('plot_segments: 3d plot of segments not supported yet!');
+end
+
+%legend (disable warnings)
+warning off
+legend([h2,q],'element on segment','normal vectors')
+warning on
+
+%apply options
+options=addfielddefault(options,'title','Segment boundaries');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_streamlines.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_streamlines.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_streamlines.m	(revision 11330)
@@ -0,0 +1,41 @@
+function plot_streamlines(md,options)
+%PLOT_STREAMLINES - plot stream lines on a figure
+%
+%   Usage:
+%      plot_streamlines(md,options)
+
+%process data and model
+[x y z index is2d isplanet]=processmesh(md,[],options);
+[u datatype]=processdata(md,md.initialization.vx,options);
+[v datatype]=processdata(md,md.initialization.vy,options);
+
+%some checks
+if ~is2d,
+	disp('plot_streamlines error: streamlines option not supported for 3d plots. Project on a layer')
+	return
+end
+
+%initialize flowpath
+streamlines=getfieldvalue(options,'streamlines');
+if ischar(streamlines) & strcmpi(streamlines,'on');
+	streamlines=60;
+end
+if iscell(streamlines)
+	x0=[]; y0=[];
+	for i=1:size(streamlines,2)
+		coord=streamlines{i};
+		x0=[x0;coord(1)]; y0=[y0;coord(2)];
+	end
+else
+	x0=x(1:ceil(length(x)/streamlines):end);
+	y0=y(1:ceil(length(x)/streamlines):end);
+end
+
+%Get flow lines
+flowpath=flowlines(index,x,y,u,v,x0,y0);
+
+%plot
+hold on
+for i=1:length(flowpath)
+	patch('Xdata',[flowpath(i).x;NaN],'Ydata',[flowpath(i).y;NaN],'facecolor','none','edgecolor','y');
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_tensor.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_tensor.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_tensor.m	(revision 11330)
@@ -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.strainrate;
+elseif strncmpi(type,'stress',6),
+	tensor=md.stress;
+elseif strncmpi(type,'deviatoricstress',16),
+	tensor=md.deviatoricstress;
+else
+	error('plot_tensor error message: unsupported type of tensor');
+end
+
+%Figure out type of plot being requested
+if strncmpi(fliplr(type),fliplr('tensor'),6) | strcmpi(type,'strainrate') | strcmpi(type,'deviatoricstress') | strcmpi(type,'stress'),
+	plot_tensor_components(md,options,width,i,tensor,type,plot_options);
+	return;
+elseif strncmpi(fliplr(type),fliplr('principal'),9),
+	plot_tensor_principal(md,options,width,i,tensor,type,plot_options);
+	return;
+elseif strncmpi(fliplr(type(1:end-1)),fliplr('principalaxis'),13),
+	plot_tensor_principalaxis(md,options,width,i,tensor,type,plot_options);
+	return;
+else
+	error('plot_tensor error message: unsurported type of plot');
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_tensor_components.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_tensor_components.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_tensor_components.m	(revision 11330)
@@ -0,0 +1,78 @@
+function plot_tensor_components(md,options,width,i,tensor,type,plot_options);
+%PLOT_TENSOR_COMPONENT - plot component of a tensor
+%
+%   Usage:
+%      plot_tensor_components(md,options,width,i,tensor,type,plot_option);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+%Compute the indexes of the components plots
+upperplots=fix((i-1)/width);
+if upperplots==0, leftplots=i-1; else leftplots=i-width*upperplots-1; end
+if (md.mesh.dimension==2)%3 components -> 3 indexes
+	index1=4*width*upperplots+2*leftplots+1;
+	index2=index1+1;
+	index3=index1+width*2;
+elseif md.mesh.dimension==3%6 components -> 6 indexes
+	index1=3*3*width*upperplots+3*leftplots+1;
+	index2=index1+1;
+	index3=index1+2;
+	index4=index1+width*3;
+	index5=index4+1;
+	index6=index4+2;
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[tensor.xx datatype]=processdata(md,tensor.xx,options);
+[tensor.yy datatype]=processdata(md,tensor.yy,options);
+[tensor.xy datatype]=processdata(md,tensor.xy,options);
+if  md.mesh.dimension==3
+	[tensor.xz datatype]=processdata(md,tensor.xz,options);
+	[tensor.yz datatype]=processdata(md,tensor.yz,options);
+	[tensor.zz datatype]=processdata(md,tensor.zz,options);
+end
+
+if ((md.mesh.dimension==2)),
+	subplot(2*width,2*width,index1),
+	plot_unit(x,y,z,elements,tensor.xx,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xx')
+	subplot(2*width,2*width,index2),
+	plot_unit(x,y,z,elements,tensor.yy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'yy')
+	subplot(2*width,2*width,index3),
+	plot_unit(x,y,z,elements,tensor.xy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xy')
+else
+	subplot(3*width,3*width,index1),
+	plot_unit(x,y,z,elements,tensor.xx,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xx')
+	subplot(3*width,3*width,index2),
+	plot_unit(x,y,z,elements,tensor.yy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'yy')
+	subplot(3*width,3*width,index3),
+	plot_unit(x,y,z,elements,tensor.zz,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'zz')
+	subplot(3*width,3*width,index4),
+	plot_unit(x,y,z,elements,tensor.xy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xy')
+	subplot(3*width,3*width,index5),
+	plot_unit(x,y,z,elements,tensor.xz,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xz')
+	subplot(3*width,3*width,index6),
+	plot_unit(x,y,z,elements,tensor.yz,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'yz')
+end
+end
+
+function Apply_options_tensor(md,options,type,component)
+	%apply options
+	if ismember('_',type) %user plotet stress_tensor
+		strings=strsplit(type,'_');
+		string=strings{1};
+	else %default plot: user requested stress
+		string=type;
+	end
+	options=addfielddefault(options,'title',[upper(string(1)) string(2:end) ' ' component]);
+	applyoptions(md,[],options);
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_tensor_principal.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_tensor_principal.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_tensor_principal.m	(revision 11330)
@@ -0,0 +1,77 @@
+function plot_tensor_principal(md,options,width,i,tensor,type,plot_options);
+%PLOT_TENSOR_PRINCIPAL - plot principal values
+%
+%   Usage:
+%      plot_tensor_principal(md,options,width,i,tensor,type,plot_options);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+%Compute the indexes of the components plots
+upperplots=fix((i-1)/width);
+if upperplots==0, leftplots=i-1; else leftplots=i-width*upperplots-1; end
+if (md.mesh.dimension==2)%3 components -> 3 indexes
+	index1=4*width*upperplots+2*leftplots+1;
+	index2=index1+1;
+	index3=index1+width*2;
+	index4=index3+1;
+	newwidth=2*width;
+elseif md.mesh.dimension==3%6 components -> 6 indexes
+	index1=3*3*width*upperplots+3*leftplots+1;
+	index2=index1+1;
+	index3=index1+2;
+	index4=index1+width*3;
+	index5=index4+1;
+	index6=index4+2;
+	newwidth=3*width;
+end
+
+%plot principal axis
+type1=[type 'axis1'];
+plot_tensor_principalaxis(md,options,newwidth,index1,tensor,type1,plot_options);
+type2=[type 'axis2'];
+plot_tensor_principalaxis(md,options,newwidth,index2,tensor,type2,plot_options);
+if  md.mesh.dimension==3
+	type3=[type 'axis3'];
+	plot_tensor_principalaxis(md,options,newwidth,index3,tensor,type3,plot_options);
+end
+
+%now plot principal values
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[tensor.principalvalue1 datatype]=processdata(md,tensor.principalvalue1,options);
+[tensor.principalvalue2 datatype]=processdata(md,tensor.principalvalue2,options);
+if  md.mesh.dimension==3
+	[tensor.principalvalue3 datatype]=processdata(md,tensor.principalvalue3,options);
+end
+
+if ((md.mesh.dimension==2)),
+	subplot(2*width,2*width,index3)
+	plot_unit(x,y,z,elements,tensor.principalvalue1,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 1')
+	subplot(2*width,2*width,index4)
+	plot_unit(x,y,z,elements,tensor.principalvalue2,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 2')
+else
+	subplot(3*width,3*width,index4)
+	plot_unit(x,y,z,elements,tensor.principalvalue1,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 1')
+	subplot(3*width,3*width,index5)
+	plot_unit(x,y,z,elements,tensor.principalvalue2,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 2')
+	subplot(3*width,3*width,index6)
+	plot_unit(x,y,z,elements,tensor.principalvalue3,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 3')
+end
+end
+
+function Apply_options_tensor(md,options,type,component)
+%apply options
+if ismember('_',type) %user plotet stress_tensor
+	strings=strsplit(type,'_');
+	string=strings{1};
+else %default plot: user requested stress
+	string=type;
+end
+options=addfielddefault(options,'title',[upper(string(1)) string(2:end) ' ' component]);
+options=changefieldvalue(options,'colorbar',2);
+applyoptions(md,[],options);
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_tensor_principalaxis.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_tensor_principalaxis.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_tensor_principalaxis.m	(revision 11330)
@@ -0,0 +1,95 @@
+function plot_tensor_principalaxis(md,options,width,i,tensor,type,plot_options);
+%PLOT_TENSOR_PRINCIPALAXIS - plot ytensor principal axis
+%
+%   Usage:
+%      plot_tensor_principalaxis(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%prepare subplot
+subplot(width,width,i); 
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+if ((md.mesh.dimension==2)),
+	eval(['Vx=tensor.principalaxis' type(end) '(:,1); Vy=tensor.principalaxis' type(end) '(:,2);'])
+	eval(['value=tensor.principalvalue' type(end) ';']);
+	[Vx datatype]=processdata(md,Vx,options);
+	[Vy datatype]=processdata(md,Vy,options);
+	[value datatype]=processdata(md,value,options);
+else
+	eval(['Vx=tensor.principalaxis' type(end) '(:,1); Vy=tensor.principalaxis' type(end) '(:,2); Vz=tensor.principalaxis' type(end) '(:,3);'])
+	[Vx datatype]=processdata(md,Vx,options);
+	[Vy datatype]=processdata(md,Vy,options);
+	[Vz datatype]=processdata(md,Vz,options);
+	[value datatype]=processdata(md,value,options);
+end
+
+%take the center of each element if ~isonnode
+if datatype==1,
+	x=mean(md.mesh.x(md.mesh.elements'))'; y=mean(md.mesh.y(md.mesh.elements'))'; z=mean(md.mesh.z(md.mesh.elements'))';
+end
+
+%plot quivers
+if (md.mesh.dimension==2),
+
+	%density
+	if exist(options,'density')
+		density=getfieldvalue(options,'density');
+		x=x(1:density:end);
+		y=y(1:density:end);
+		Vx=Vx(1:density:end);
+		Vy=Vy(1:density:end);
+		value=value(1:density:end);
+	end
+
+	%scaling:
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	scale=0.5/max(sqrt((Vx.^2+Vy.^2)/delta));
+	Vx=scale*Vx; Vy=scale*Vy;
+
+	pos=find(value>=0);
+	q1=quiver(x(pos),y(pos),Vx(pos),Vy(pos),'Color','r','ShowArrowHead','off','AutoScale','off');
+	hold on
+	pos=find(value<0);
+	q2=quiver(x(pos),y(pos),Vx(pos),Vy(pos),'Color','b','ShowArrowHead','off','AutoScale','off');
+
+else
+	%density
+	if exist(options,'density')
+		density=getfieldvalue(options,'density');
+		x=x(1:density:end);
+		y=y(1:density:end);
+		z=z(1:density:end);
+		Vx=Vx(1:density:end);
+		Vy=Vy(1:density:end);
+		Vz=Vz(1:density:end);
+		value=value(1:density:end);
+	end
+
+	%scaling:
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	scale=0.5/max(sqrt((Vx.^2+Vy.^2)/delta));
+	Vx=scale*Vx; Vy=scale*Vy; Vz=scale*Vz;
+
+	pos=find(value>=0);
+	q1=quiver3(x(pos),y(pos),z(pos),Vx(pos),Vy(pos),Vz(pos),'Color','r','ShowArrowHead','off','AutoScale','off');
+	hold on
+	pos=find(value<0);
+	q2=quiver3(x(pos),y(pos),z(pos),Vx(pos),Vy(pos),Vz(pos),'Color','b','ShowArrowHead','off','AutoScale','off');
+end
+
+%legend
+if strcmpi(type(1:6),'strain')
+	legend([q1 q2],'extension','compression')
+elseif strcmpi(type(1:6),'stress')
+	legend([q1 q2],'compression','traction')
+end
+
+%apply options
+strings=strsplit(type,'_');
+string=strings{1};
+options=addfielddefault(options,'title',[upper(string(1)) string(2:end) ' principal axis ' type(end)]);
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_thermaltransient_results.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_thermaltransient_results.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_thermaltransient_results.m	(revision 11330)
@@ -0,0 +1,24 @@
+function plot_thermaltransient_results(md,options,width,i)
+%PLOT_THERMALTRANSIENT_RESULTS - plot  results of a thermal transient solution
+%
+%   Usage:
+%      plot_thermaltransient_results(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+string='plot(md';
+for i=1:length(md.thermaltransient_results),
+	string=[string ',''data'',''thermaltransient_results(' num2str(i) ').temperature'',''view'',3,''title'',''Temperature at time ' num2str(md.thermaltransient_results(i).time) ' a'''];
+end
+string=[string ',''figure'',1,''colorbar#all'',''on'',''view'',3,''fontsize'',' num2str(options.fontsize) ',''fontweight'',' options.fontweight ');'];
+eval(string);
+clear string;
+
+string='plot(md';
+for i=2:length(md.thermaltransient_results),
+	string=[string ',''data'',md.thermaltransient_results(' num2str(i) ').temperature-md.thermaltransient_results(' num2str(i-1) ').temperature,''view'',3,''title'',''Delta temperature at time ' num2str(md.thermaltransient_results(i).time) ' a'''];
+end
+string=[string ',''figure'',2,''colorbar#all'',''on'',''fontsize'',' num2str(options.fontsize) ',''fontweight'',' options.fontweight ');'];
+eval(string);
+clear string;
+
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_transient_field.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_transient_field.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_transient_field.m	(revision 11330)
@@ -0,0 +1,43 @@
+function plot_transient_field(md,options,width,i,data)
+%PLOT_TRANSIENT_FIELD - plot transient results
+%
+%   Usage:
+%      plot_transient_field(md,options,width,i,data);
+%
+%   See also: PLOTMODEL
+
+%Check that they are transient results
+if (~isfield(md.results,'TransientSolution')),
+	error('plot_transient_field error message: no transient results in the model');
+end
+
+%Figure out the iterations to plot and check if it is possible
+transient=md.results.TransientSolution;
+maxiteration=size(transient,2);
+steps=getfieldvalue(options,'steps',1:1:maxiteration);
+
+if max(steps)>maxiteration | min(steps)<1,
+	error(['plot_transient_field error message: problem with the steps requested, must be an interger between 0 and ' num2str(maxiteration)]);
+end
+subplotwidth=ceil(sqrt(length(steps)));
+
+%Figure out the field to plot
+
+field=getfieldvalue(options,'field','Vel');
+
+%process mes only once
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot data for all steps
+for i=1:length(steps),
+
+	%process data and change title if needed
+	[data datatype]=processdata(md,transient(steps(i)).(field),options);
+	options=changefieldvalue(options,'title',[field ' at time ' num2str(transient(steps(i)).time/md.constants.yts) ' a']);
+
+	%create plot of step i
+	subplot(subplotwidth,subplotwidth,i);
+	plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
+	applyoptions(md,data,options);
+
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_transient_movie.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_transient_movie.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_transient_movie.m	(revision 11330)
@@ -0,0 +1,70 @@
+function plot_transient_movie(md,options,width,i);
+%PLOT_TRANSIENT_MOVIE - plot a transient result as a movie
+%   Usage:
+%      plot_transient_movie(md,options,width,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+	%prepare subplot
+	subplot(width,width,i); 
+
+	%xlim
+	if exist(options,'transient_movie_field'),
+		field=getfieldvalue(options,'transient_movie_field');
+	else
+		error('specify transient_movie_field in options list');
+	end
+
+	results=md.results.TransientSolution;
+	%loop over the time steps
+	if exist(options,'transient_movie_limit'),
+		limit=getfieldvalue(options,'transient_movie_limit');
+		steps=[limit(1):limit(end)];
+	else
+		steps=1:length(results);
+	end
+	results=md.results.TransientSolution;
+	nstep=1;
+	for i=steps
+
+		if ~isempty(results(i).(field)),
+			%process data
+			[x y z elements is2d isplanet]=processmesh(md,results(i).(field),options);
+			[data datatype]=processdata(md,results(i).(field),options);
+
+			titlestring=[field ' at time ' num2str(results(i).time/md.constants.yts) ' year'];
+			plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
+			apply_options_movie(md,options,titlestring);
+
+			if exist(options,'transient_movie_output'),
+				set(gcf,'Renderer','zbuffer','color','white'); %fixes a bug on Mac OS X (not needed in future Matlab version)
+				if nstep==1,
+					%initialize images and frame
+					frame=getframe(gcf);
+					[images,map]=rgb2ind(frame.cdata,256,'nodither');
+					images(1,1,1,length(steps))=0;
+				else
+					frame=getframe(gcf);
+					images(:,:,1,nstep) = rgb2ind(frame.cdata,map,'nodither');
+				end
+			else
+				pause(0.1)
+			end
+			nstep=nstep+1;
+		end
+	end
+
+	%output movie if requested.
+	if exist(options,'transient_movie_output'),
+		filename=getfieldvalue(options,'transient_movie_output');
+		imwrite(images,map,filename,'DelayTime',getfieldvalue(options,'transient_movie_time',2),'LoopCount',inf)
+	end
+
+end %function
+
+function apply_options_movie(md,options,titlestring)
+	%apply options
+	options=addfielddefault(options,'title',titlestring);
+	options=addfielddefault(options,'colorbar',1);
+	applyoptions(md,[],options);
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_transient_results.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_transient_results.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_transient_results.m	(revision 11330)
@@ -0,0 +1,77 @@
+function plot_transient_results(md,options,width,i)
+%PLOT_TRANSIENT_RESULTS - plot transient results
+%
+%   Usage:
+%      plot_transient_results(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+fontsize=getfieldvalue(options,'fontsize',14);
+fontweight=getfieldvalue(options,'fontweight','n');
+
+%Prepare window distribution
+%Get screen geometry
+mp = get(0, 'MonitorPositions');
+%Build window sizes
+if size(mp,1)>=2        %several monitors, use the second one
+	bdwidth=mp(2,1)+5; topbdwidth=mp(2,2)+20; W=mp(2,3)/3; H=mp(2,4)/2;
+else                    %only one monitor
+	bdwidth=5;         topbdwidth=20;         W=mp(1,3)/3; H=mp(1,4)/2;
+end
+pos1=[bdwidth  H+bdwidth  W-2*bdwidth  H-bdwidth-topbdwidth];
+pos2=pos1+[W 0 0 0]; pos3=pos1+[2*W 0 0 0]; pos4=pos1+[0 -H 0 0]; pos5=pos1+[W -H 0 0]; pos6=pos1+[2*W -H 0 0];
+%Create windows
+figure(1);close;
+figure('Position',pos1); figure('Position',pos2);figure('Position',pos3);figure('Position',pos4);figure('Position',pos5);figure('Position',pos6);
+
+string='plotmodel(md';
+for i=1:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').thickness,''title'',''Thickness at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',1,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight ''');'];
+eval(string);
+clear string;
+
+string='plotmodel(md';
+for i=1:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').vel,''view'',3,''title'',''Velocity at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',2,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+eval(string);
+clear string;
+
+if md.mesh.dimension==3,
+	string='plotmodel(md';
+	for i=1:length(md.results.transient),
+		string=[string ',''data'',md.results.transient(' num2str(i) ').temperature,''view'',3,''title'',''Temperature at time ' num2str(md.results.transient(i).time) ' a'''];
+	end
+	string=[string ',''figure'',3,''colorbar#all'',''on'',''view'',3,''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+	eval(string);
+	clear string;
+end
+
+string='plotmodel(md';
+for i=2:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').thickness-md.results.transient(' num2str(i-1) ').thickness,''title'',''Delta thickness at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',4,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+eval(string);
+clear string;
+
+string='plotmodel(md';
+for i=2:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').vel-md.results.transient(' num2str(i-1) ').vel,''view'',3,''title'',''Delta velocity at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',5,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+eval(string);
+clear string;
+
+if md.mesh.dimension==3,
+	string='plotmodel(md';
+	for i=2:length(md.results.transient),
+		string=[string ',''data'',md.results.transient(' num2str(i) ').temperature-md.results.transient(' num2str(i-1) ').temperature,''view'',3,''title'',''Delta temperature at time ' num2str(md.results.transient(i).time) ' a'''];
+	end
+	string=[string ',''figure'',6,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+	eval(string);
+	clear string;
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_unit.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_unit.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_unit.m	(revision 11330)
@@ -0,0 +1,92 @@
+function plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
+%PLOT_UNIT - unit plot, display data
+%
+%   Usage:
+%      plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options);
+%
+%   See also: PLOTMODEL, PLOT_MANAGER
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+switch datatype,
+
+	%element plot
+	case 1,
+
+		pos=find(~isnan(data)); %needed for element on water
+		if is2d,
+			A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+		else
+			A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+			patch( 'Faces', [A B C],  'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+		end
+
+	%node plot
+	case 2,
+
+		if is2d,
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+			patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+		else
+			if ~isplanet,
+				A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+				patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+				patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+				patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+				patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+				patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+			else
+				A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+				if size(elements,2)==4, D=elements(:,4); else D=C; end
+				patch( 'Faces', [A B C D],  'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+			end
+		end
+
+	%quiver plot
+	case 3,
+
+		if is2d,
+			plot_quiver(x,y,data(:,1),data(:,2),options);
+		else
+			plot_quiver3(x,y,z,data(:,1),data(:,2),data(:,3),options);
+		end
+
+	%Patch plot P1
+	case 4,
+
+		if is2d,
+			patch( 'Faces',elements,'Vertices',[x y],'CData',data,'FaceColor','interp','EdgeColor',edgecolor);
+		else
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+			patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [D E F], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [A B E D], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [B E F C ], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [C A D F ], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+		end
+
+	%Patch plot P0
+	case 5,
+
+		if is2d,
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+			patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data(:),'FaceColor','flat','EdgeColor',edgecolor);
+		else
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+			patch( 'Faces', [A B C],  'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+		end
+
+	otherwise,
+		error(['case ' num2str(datatype) ' not supported']);
+
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/plot_vertexnumbering.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plot_vertexnumbering.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plot_vertexnumbering.m	(revision 11330)
@@ -0,0 +1,51 @@
+function plot_vertexnumbering(md,options,width,i);
+%PLOT_VERTEXNUMBERING - plot vertex numbering
+%
+%   Usage:
+%      plot_vertexnumbering(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[vertexnumbers datatype]=processdata(md,[1:md.mesh.numberofvertices]',options);
+
+%plot
+subplot(width,width,i); 
+
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%numbering
+	text(x,y,z,num2str(transpose(1:size(x,1))),...
+		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%numbering
+	text(x,y,z,num2str(transpose(1:size(x,1))),...
+		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+end
+
+%apply options
+options=addfielddefault(options,'title','Node numbering');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk-jpl-damage/src/m/model/plot/plotdoc.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plotdoc.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plotdoc.m	(revision 11330)
@@ -0,0 +1,173 @@
+function plotdoc()
+%PLOTDOC - plot documentation
+%
+%   Usage:
+%      plotdoc()
+
+disp(' ');
+disp('   Plot usage: plotm(model,varargin)');
+disp('   Options: ');
+disp('       ''figure'': figure number');
+disp('       ''data'' : what we want to plot');
+disp('                Available values for ''data'' are: ');
+disp('                  - any field of the model structure. ex: plot(md,''data'',''vel''), or plot(md,''data'',md.initialization.vel)');
+disp('                  - ''basal_drag'': plot the basal drag on the bed (in kPa)');
+disp('                  - ''basal_dragx'' or ''basal_dragy'' : plot a component of the basal drag on the bed (in kPa)');
+disp('                  - ''boundaries'': this will draw all the segment boundaries to the model, including rifts.');
+disp('                  - ''icefront'': this will show segments that are used to define the icefront of the model (Neumann boundary conditions).');
+disp('                  - ''BC'': this will draw all the boundary conditions (Dirichlet and Neumann).');
+disp('                  - ''deviatoricstress_tensor'': plot the components of the deviatoric stress tensor (tauxx,tauyy,tauzz,tauxy,tauxz,tauyz) if computed');
+disp('                  - ''deviatoricstress_principal'': plot the deviatoricstress tensor principal axis and principal values');
+disp('                  - ''deviatoricstress_principalaxis1'': arrow plot the first principal axis of the deviatoricstress tensor(replace 1 by 2 or 3 if needed)');
+disp('                  - ''driving_stress'': plot the driving stress (in kPa)');
+disp('                  - ''elements_type'': model used for each element');
+disp('                  - ''elementnumbering'': numbering of elements');
+disp('                  - ''vertexnumbering'': numbering of vertices');
+disp('                  - ''highlightelements'': to highlight elements to highlight the element list');
+disp('                  - ''highlightvertices'': to highlight vertices (use highlight option to enter the vertex list');
+disp('                  - ''mesh'': draw mesh using trisurf');
+disp('                  - ''referential'': diagnostic referential');
+disp('                  - ''riftvel'': velocities along rifts');
+disp('                  - ''riftrelvel'': relative velocities along rifts');
+disp('                  - ''riftpenetration'': penetration levels for a fault');
+disp('                  - ''riftfraction'': fill fractions for every node of the rifts');
+disp('                  - ''rifts'': plot mesh with an offset so that rifts are visible');
+disp('                  - ''strainrate_tensor'': plot the components of the strainrate tensor (exx,eyy,ezz,exy,exz,eyz) if computed');
+disp('                  - ''strainrate_principal'': plot the strainrate tensor principal axis and principal values)');
+disp('                  - ''strainrate_principalaxis1'': arrow plot the first principal axis of the strainrate tensor(replace 1 by 2 or 3 if needed)');
+disp('                  - ''stress_tensor'': plot the components of stress tensor (sxx,syy,szz,sxy,sxz,syz) if computed');
+disp('                  - ''stress_principal'': plot the stress tensor principal axis and principal values');
+disp('                  - ''stress_principalaxis1'': arrow plot the first principal axis of the stress tensor(replace 1 by 2 or 3 if needed)');
+disp('                  - ''transient_results'': this will display all the time steps of a transient run (use steps to specify the steps requested)');
+disp('                  - ''transient_vel'': this will display the velocity for the time steps requested in ''steps'' of a transient run');
+disp('                  - ''transient_vel'': vel can be by any field of the transient results (vx, vy, vz, vel, temperature, melting, pressure, bed, thickness, surface)');
+disp('                  - ''transient_field'': dynamic plot of results. specify ''steps'' option, as fell as ''field'' (defaults are all steps, for ''Vel'' field)');
+disp('                  - ''transient_movie'': this will display the time steps of a given field of a transient run');
+disp('                  - ''transient_movie_field'': field to be displayed when doing  transient_movie data display');
+disp('                  - ''transient_movie_output'': filename if output is desired for movie');
+disp('                  - ''transient_movie_time'': time for each image (default 2 seconds)');
+disp('                  - ''thermaltransient_results'': this will display all the time steps of a thermal transient run');
+disp('                  - ''qmuhistnorm'': histogram normal distribution. needs option qmudata');
+disp('                  - ''qmumean'': plot of mean distribution in sampling analysis with scaled response. needs option qmudata for descriptor');
+disp('                  - ''qmustddev'': plot of stddev distribution in sampling analysis with scaled response. needs option qmudata for descriptor');
+disp('                  - ''part_hist'': partitioning node and area histogram');
+disp('                  - ''quiver'': quiver plot');
+
+disp('       ''alloptions'': apply the options to all subplots if ''on''');
+disp('       ''axis'': same as standard matlab option (''equal'',''off'',''equal on'',...)');
+disp('       ''basin'': zoom on a given basin (''pineislandglacier'',''ronneiceshelf'', use isbasin to identify a basin');
+disp('                 ''hemisphere'': specify +1 or -1');
+disp('                 ''basindeltax'': in m');
+disp('                 ''showbasins'': write lables for every existing basin name around the center of the plot');
+disp('       ''caxis'': modify  colorbar range. (array of type [a b] where b>=a)');
+disp('       ''backgroundcolor'': plot background color. (default is ''w'')');
+disp('       ''figurebackgroundcolor'': figure background color. (default is ''none'')');
+disp('       ''coord'':  ''xy'' (default) or ''latlon''');
+disp('       ''colorlevels'':  N or {value1,valu2,value3,...} used if quiver, use different colors for the given number of colors or limits');
+disp('       ''colorbar'': add colorbar (string ''on'' or ''off'')');
+disp('       ''colorbartitle'': colorbar title (string)');
+disp('       ''colorbarYlabel'': colorbar Y label (string)');
+disp('       ''colorbarpos'': [x,y,dx,dy] where x,y,dx and dy are within [0 1]');
+disp('       ''colorbarcornerposition'': ''West'',''North'',etc ...');
+disp('       ''colorbartitlerotation'': -90, etc ...');
+disp('       ''colorbarfontsize'': specify colorbar fontsize');
+disp('       ''colorbarwidth'': multiplier (default 1) to the default width colorbar');
+disp('       ''colorbarheight'': multiplier (default 1) to the default height colorbar');
+disp('       ''colormap'': same as standard matlab option (''jet'',''hsv'',''cool'',''spring'',''gray'',''Ala'',''Rignot'',...)');
+disp('       ''contourlevels'': N or {value1,valu2,value3,...} add the contours of the specified values or N contours');
+disp('       ''contourticks'': ''on'' or ''off'' to display the ticks of the contours');
+disp('       ''contouronly'': ''on'' or ''off'' to display the contours on a white background');
+disp('       ''contourcolor'': ticks and contour color');
+disp('       ''density'': density of quivers (one arrow every N nodes, N integer)');
+disp('       ''inset'': add an inset (zoom) of the current figure if 1 (use ''insetx'', ''insety'' and ''insetpos'' to determine the inset position and content)');
+disp('       ''insetx'': [min(x) max(x)] where min(x) and max(x) are values determining the inset content');
+disp('       ''insety'': [min(y) max(y)] where min(y) and max(y) are values determining the inset content');
+disp('       ''insetpos'': [x,y,dx,dy] where x,y,dx and dy are within [0 1]');
+disp('       ''streamlines'': N (number of stream lines) or {[x1 y1],...} (coordinates of seed points) add streanlines on current figure');
+disp('       ''edgecolor'': same as standard matlab option EdgeColor (color name: ''black'' or RGB array: [0.5 0.2 0.8])');
+disp('       ''fontsize'': same as standard matlab option (10,14,...)');
+disp('       ''fontweight'': same as standard matlab option (normal: ''n'',bold: ''b'',light: ''l'',demi: ''d'')');
+disp('       ''fontcolor'': same as standard matlab option');
+disp('       ''highlight'': highlights certain nodes or elements when using ''nodenumbering'' or ''elementnumbering'' or ''highlightnodes '' or ''highlightelements'' option');
+disp('       ''resolution'': resolution used by section value (array of type [horizontal_resolution vertical_resolution])');
+disp('                       horizontal_resolution must be in meter, and vertical_resolution a number of layers');
+disp('       ''showsection'': show section used by ''sectionvalue'' (string ''on'' or a number of labels)');
+disp('       ''sectionvalue'': give the value of data on a profile given by an Argus file (string ''Argusfile_name.exp'')');
+disp('       ''smooth'': smooth element data (string ''yes'' or integer)');
+disp('       ''title'': same as standard matlab option');
+disp('       ''view'': same as standard matlab option (ex: 2, 3 or [90 180]');
+disp('       ''xlim'': same as standard matlab option (ex: [0 500])');
+disp('       ''ylim'': same as standard matlab option');
+disp('       ''zlim'': same as standard matlab option');
+disp('       ''xlabel'': same as standard matlab option (ex:''km'')');
+disp('       ''ylabel'': same as standard matlab option');
+disp('       ''xticklabel'': specifiy xticklabel');
+disp('       ''yticklabel'': specifiy yticklabel');
+disp('       ''overlay'': yes or no. This will overlay a radar amplitude image behind');
+disp('       ''overlay_image'': path to overlay image. provide overlay_xlim, overlay_ylim, overlay_xposting and overlay_yposting options also');
+disp('       ''contrast'': (default 1) coefficient to add contrast to the radar amplitude image used in overlays');
+disp('       ''highres'': resolution of overlayed radar amplitude image (default is 0, high resolution is 1).');
+disp('       ''hem'': specify hemisphere ''n'' or ''s'' (default is ''s'').');
+disp('       ''alpha'': transparency coefficient (the higher, the more transparent). Default is 1.5');
+disp('       ''scaling'': scaling factor used by quiver plots. Default is 0.4');
+disp('       ''autoscale'': set to ''off'' to have all the quivers with the same size. Default is ''on''');
+disp('       ''expdisp'': plot exp file on top of a data plot. provide exp file as an argument (use a cell of strings if more than one)');
+disp('       ''expstyle'': marker style for expdisp plot (use a cell of strings if more than one)');
+disp('       ''linewidth'': line width for expdisp plot');
+disp('       ''border'': size of display border (in pixels). active only for overlay plots');
+disp('       ''text'': print string, use a cell of strings if more than one');
+disp('       ''textposition'': [x y] position of text, use a cell of strings if more than one');
+disp('       ''textsize'':  same as standard ''FontSize'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''textweight'':  same as standard ''FontWeight'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''textcolor'':  same as standard ''color'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''textrotation'':  same as standard ''Rotation'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''mask'': list of flags of size numberofnodes or numberofelements. Only ''true'' values are plotted ');
+disp('       ''nan'': value assigned to NaNs (convenient when plotting BC)');
+disp('       ''partitionedges'': ''off'' by default. overlay plot of partition edges');
+disp('       ''log'': value of log');
+disp('       ''latlon'': ''on'' or {latstep lonstep [resolution [color]]} where latstep,longstep and resolution are in degrees, color is a [r g b] array');
+disp('       ''latlonnumbering'': ''on'' or {latgap longap colornumber latangle lonangle} where latgap and longap are pixel gaps for the numbers,'); 
+disp('       ''latlonclick'': ''on'' to click on latlon ticks positions');
+disp('                   colornumber is a [r g b] array and latangle and lonangle are angles to flip the numbers');
+disp('       ''northarrow'': add an arrow pointing north, ''on'' for default value or [x0 y0 length [ratio [width]]] where (x0,y0) are the coordinates of the base, and ratio=headlength/length');
+disp('       ''offset'': mesh offset used by ''rifts'', default is 500');
+disp('       ''scaleruler'': add a scale ruler, ''on'' for default value or [x0 y0 length width numberofticks] where (x0,y0) are the coordinates of the lower left corner');
+disp('       ''showregion'': show domain in Antarctica on an inset, use ''insetpos'' properties');
+disp('       ''visible'': ''off'' to make figure unvisible, default is ''on''');
+disp('       ''wrapping'': repeat ''n'' times the colormap (''n'' must be an integer)');
+disp('       ''unit'': by default, in m, otherwise, ''km'' is available');
+disp('       ''legend_position'': by default, ''NorthEasth''');
+disp('       ''qmudata'': data for qmu  plots.');
+disp('                  {dresp1   ,dresp2  ,hmin,hmax,hnint} or {samp,desc,mu,sigma,hmin,hmax,hnint}');
+disp('                  where dresp1 is a structure array of responses (where we need samp and desc), ');
+disp('                  dresp2 is a structure array of responses (where we only need mu and sigma)');
+disp('                  hmin,hmax and hnint are the minimum, maximum and number of intervals of the histogram (optional)');
+disp('       ''figposition'': position of figure: ''fullscreen'', ''halfright'', ''halfleft'', ''portrait'', ''landscape'',... (hardcoded in applyoptions.m)');
+disp('       ''offsetaxispos'': offset of current axis position to get more space (ex: [-0.02 0  0.04 0])');
+disp('       ''axispos'': axis position to get more space');
+disp('       ''hmin'': (numeric, minimum for histogram)');
+disp('       ''hmax'': (numeric, maximum for histogram)');
+disp('       ''hnint'': (numeric, number of intervals for histogram)');
+disp('       ''ymin1'': (numeric, minimum of histogram y-axis)');
+disp('       ''ymax1'': (numeric, maximum of histogram y-axis)');
+disp('       ''ymin2'': (numeric, minimum of cdf y-axis)');
+disp('       ''ymax2'': (numeric, maximum of cdf y-axis)');
+disp('       ''cdfplt'': (char, ''off'' to turn off cdf line plots)');
+disp('       ''cdfleg'': (char, ''off'' to turn off cdf legends)');
+disp('       ''segmentnumbering'': (''off'' by default)');
+disp('       ''kmlgroundoverlay'': (''off'' by default)');
+disp('       ''kmlfilename'': (''tempfile.kml'' by default)');
+disp('       ''kmlroot'': (''./'' by default)');
+disp('       ''kmlimagename'': (''tempimage'' by default)');
+disp('       ''kmlimagetype'': (''png'' by default)');
+disp('       ''kmlresolution'': (1 by default)');
+disp('       ''kmlfolder'': (''Ground Overlay'' by default)');
+disp('       ''kmlfolderdescription'': ('''' by default)');
+disp('       ''kmlgroundoverlayname'': ('''' by default)');
+disp('       ''kmlgroundoverlaydescription'': ('''' by default)');
+
+disp('       any options (except ''data'') can be followed by ''#i'' where ''i'' is the subplot number, or ''#all'' if applied to all plots');
+disp('  ');
+disp('   Examples:');
+disp('       plotmodel(md,''data'',''vel'',''data'',''mesh'',''view#2'',3,''colorbar#all'',''on'',''axis#1'',''off equal'')');
+disp('       plotmodel(md,''data'',''highlightelements'',''highlight'',[1 4 10],''expdisp'',{''domain1.exp'' ''domain2.exp'' ''domain3.exp''})');
Index: /issm/trunk-jpl-damage/src/m/model/plot/plotmodel.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/plotmodel.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/plotmodel.m	(revision 11330)
@@ -0,0 +1,57 @@
+function plotmodel(md,varargin)
+%At command prompt, type plotdoc for help on documentation.
+
+%First process options
+options=plotoptions(varargin{:});
+
+%get number of subplots
+subplotwidth=ceil(sqrt(options.numberofplots));
+
+%if nlines and ncols specified, then bypass.
+if exist(options.list{1},'nlines'),
+	nlines=getfieldvalue(options.list{1},'nlines');
+else 
+	nlines=subplotwidth;
+end
+
+if exist(options.list{1},'ncols'),
+	ncols=getfieldvalue(options.list{1},'ncols');
+else 
+	ncols=subplotwidth;
+end
+
+%check that nlines and ncols were given at the same time!
+if ((exist(options.list{1},'ncols') & ~exist(options.list{1},'ncols')) | (~exist(options.list{1},'ncols') & exist(options.list{1},'ncols')))
+	error('plotmodel error message: nlines and ncols  need to be specified together, or not at all');
+end
+
+%Get figure number and number of plots
+figurenumber=options.figurenumber;
+numberofplots=options.numberofplots;
+
+%go through subplots
+if numberofplots,
+		
+	%Create figure 
+	if strcmpi(getfieldvalue(options.list{1},'visible','on'),'off'),
+		F=figure(figurenumber);clf;
+		set(F,'Visible','Off');
+	else
+		figure(figurenumber);clf;
+	end
+
+	%Use zbuffer renderer (snoother colors)
+	set(gcf,'Renderer','zbuffer');
+
+	%Go through all data plottable and close window if an error occurs
+	try,
+		for i=1:numberofplots,
+			plot_manager(getfieldvalue(options.list{i},'model',md),options.list{i},subplotwidth,nlines,ncols,i);
+		end
+	catch me,
+		%figure(figurenumber),close;
+		rethrow(me);
+	end
+else
+	error('plotmodel error message: no output data found. ');
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/processdata.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/processdata.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/processdata.m	(revision 11330)
@@ -0,0 +1,193 @@
+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 Patch
+if isstruct(data) 
+	if (isfield(data,'index') & isfield(data,'value')),
+		if data.interpolation(1)==P1Enum(),
+			data=data.value;
+			data=data';
+			data=data(:);
+			datatype=4;
+		elseif data.interpolation(1)==P0Enum(),
+			data=data.value;
+			datatype=5;
+		else
+			error(['interpolation ' data.interpolation(1) ' not supported yet']);
+		end
+	else
+		error('structure other than Patch not supported yet');
+	end
+else
+	%initialize datatype
+	datatype=0;
+end
+
+%get datatype
+datasize=size(data);
+
+%Process NaN if any (do not now before mask is applied)
+if exist(options,'nan')
+	data(find(isnan(data)))=getfieldvalue(options,'nan',0);
+end
+%non patch processing
+if datatype~=4 & datatype~=5,
+
+	%transpose data if necessary
+	if (size(data,2) > size(data,1)),
+		data=data';
+	end
+	datasize=size(data);
+
+	%convert to double if necessary
+	if ~isnumeric(data);
+		disp('processdata info message: data is not numeric (logical?). Converted to double');
+		data=double(data);
+	end
+
+	%check length
+	if datasize(1)~=md.mesh.numberofvertices & datasize(1)~=md.mesh.numberofelements & datasize(1)~=md.mesh.numberofvertices*6 & (md.mesh.dimension==3 & ~(datasize(1)==md.mesh.numberofelements2d | datasize(1)==md.mesh.numberofvertices2d))
+		error('plotmodel error message: data not supported yet');
+	end
+
+	%quiver?
+	if datasize(2)>1,
+		datatype=3;
+
+		%check number of columns, add zeros if necessary,
+		if (md.mesh.dimension==3)
+			if datasize(2)==2,
+				data=[data, zeros(datasize(1),1)];
+			elseif datasize(2)~=3,
+				error('plotmodel error message: data provided should have 2 or 3 columns for quiver plot, and 1 for regular plot');
+			end
+		%elseif ((md.mesh.dimension==2) & datasize(2)~=2),
+		%	error('plotmodel error message: data provided should have 2 columns for quiver plot, and 1 for regular plot');
+		end
+	end
+
+	%treat the case datasize(1)=6*nodes
+	if datasize(1)==6*md.mesh.numberofvertices
+		%keep the only norm of data
+		data1=data(1:6:md.mesh.numberofvertices*6,:);
+		data2=data(2:6:md.mesh.numberofvertices*6,:);
+		data=sqrt(data1.^2+data2.^2);
+		datasize(1)=md.mesh.numberofvertices;
+		%---> go to node data
+	end
+
+	%treat the case datasize(1)=nodes2d
+	if (md.mesh.dimension==3 & datasize(1)==md.mesh.numberofvertices2d),
+		data=project3d(md,'vector',data,'type','node');
+		datasize(1)=md.mesh.numberofvertices;
+		%---> go to node data
+	end
+
+	%treat the case datasize(1)=nodes2d
+	if (md.mesh.dimension==3 & datasize(1)==md.mesh.numberofelements2d),
+		data=project3d(md,'vector',data,'type','element');
+		datasize(1)=md.mesh.numberofelements;
+		%---> go to node data
+	end
+
+	%smoothing?
+	if exist(options,'smooth')
+		data=averaging(md,data,getfieldvalue(options,'smooth'));
+		datasize(1)=md.mesh.numberofvertices;
+		%---> go to node data
+	end
+end
+
+%element data
+if (datasize(1)==md.mesh.numberofelements & datasize(2)==1),
+
+	%Initialize datatype if non patch
+	if datatype~=4 & datatype~=5,
+		datatype=1;
+	end
+
+	%Mask?
+	if exist(options,'mask'),
+		flags=getfieldvalue(options,'mask');
+		pos=find(~flags);
+		if length(flags)==md.mesh.numberofvertices,
+			[pos2 dummy]=find(ismember(md.mesh.elements,pos));
+			data(pos2,:)=NaN;
+		elseif length(flags)==md.mesh.numberofelements
+			data(pos,:)=NaN;
+		else
+			disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+		end
+	end
+
+	%log?
+	if exist(options,'log'),
+		bounds=getfieldvalue(options,'caxis',[min(data(:)) max(data(:))]);
+		data(find(data<bounds(1)))=bounds(1);
+		if any(data<=0),
+			error('Log option cannot be applied on negative values. Use caxis option (Rignot''s settings: [1.5 max(data)])');
+		end
+		pos=find(~isnan(data));
+		data(pos)=log(data(pos))/log(getfieldvalue(options,'log'));
+	end
+end
+
+%node data
+if (datasize(1)==md.mesh.numberofvertices & datasize(2)==1),
+	datatype=2;
+
+	%Mask?
+	if exist(options,'mask'),
+		flags=getfieldvalue(options,'mask');
+		pos=find(~flags);
+		if length(flags)==md.mesh.numberofvertices,
+			data(pos,:)=NaN;
+		elseif length(flags)==md.mesh.numberofelements
+			data(md.mesh.elements(pos,:),:)=NaN;
+		else
+			disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+		end
+	end
+
+	%log?
+	if exist(options,'log'),
+		%if any(data<=0),
+		%	error('Log option cannot be applied on negative values. Use caxis option (Rignot''s settings: [1.5 max(data)])');
+		%end
+		data=log(data)/log(getfieldvalue(options,'log'));
+	end
+end
+
+%layer projection? 
+if getfieldvalue(options,'layer',0)>=1,
+	data=project2d(md,data,getfieldvalue(options,'layer')); %project onto 2d mesh
+end
+
+%control arrow density if quiverplot
+if datatype==3 & exist(options,'density')
+	databak=data;
+	data=NaN*ones(datasize);
+	density=getfieldvalue(options,'density');
+	data(1:density:end,:)=databak(1:density:end,:);
+	clear databak
+end
+
+%OK, if datatype=0 error out
+if datatype==0,
+	error(['data provided not recognized or not supported']);
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/processmesh.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/processmesh.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/processmesh.m	(revision 11330)
@@ -0,0 +1,98 @@
+function [x y z elements is2d isplanet]=processmesh(md,data,options);
+%PROCESSMESH - process mesh to be plotted
+%
+%   Usage:
+%      [x y z elements is2d]=processmesh(md,data,options)
+%
+%   See also: PLOTMODEL, PROCESSDATA
+
+%some checks
+if md.mesh.numberofvertices==0,
+	error('plot error message: mesh is empty')
+end
+if md.mesh.numberofvertices==md.mesh.numberofelements
+	error(['plot error message: the number of elements is the same as the number of nodes...']);
+end
+
+if (isempty(data) | ~isstruct(data)),
+	%first load x,y, etc ... to speed up plot
+
+	if ~strcmpi(getfieldvalue(options,'coord','xy'),'latlon'),
+		x=md.mesh.x;
+		x2d=md.mesh.x2d;
+		y=md.mesh.y;
+		y2d=md.mesh.y2d;
+	else
+		x=md.mesh.long;
+		x2d=md.mesh.x2d;
+		y=md.mesh.lat;
+		y2d=md.mesh.y2d;
+	end
+
+	z_field=getfieldvalue(options,'z',md.mesh.z);
+	if ischar(z_field),
+		z=md.(z_field);
+	elseif isnumeric(z_field),
+		z=z_field;
+	else
+		z=md.mesh.z;
+	end
+
+
+	elements2d=md.mesh.elements2d;
+	elements=md.mesh.elements;
+
+	%is it a 2d plot?
+	if (md.mesh.dimension==2);
+		is2d=1;
+	elseif (md.mesh.dimension==3),
+		if getfieldvalue(options,'layer',0)>=1,
+			is2d=1;
+		else
+			is2d=0;
+		end
+	else
+		error(['dim = ' num2str(md.mesh.dimension) ' not supported yet']);
+	end
+
+	%layer projection? 
+	if getfieldvalue(options,'layer',0)>=1,
+		if strcmpi(getfieldvalue(options,'coord','xy'),'latlon'),
+			error('processmesh error message: cannot work with 3D meshes for now');
+		end
+		%we modify the mesh temporarily to a 2d mesh from which the 3d mesh was extruded. 
+		x=x2d;
+		y=y2d;
+		z=zeros(size(x2d));
+		elements=elements2d;
+	end
+else
+	%Process Patch
+	if (md.mesh.dimension==2),
+		elements=transpose(reshape(1:3*md.mesh.numberofelements,3,md.mesh.numberofelements));
+		x=transpose(reshape(md.mesh.x(data.index)',1,3*md.mesh.numberofelements));
+		y=transpose(reshape(md.mesh.y(data.index)',1,3*md.mesh.numberofelements));
+		z=zeros(3*md.mesh.numberofelements,1);
+		is2d=1;
+	else
+		elements=transpose(reshape(1:6*md.mesh.numberofelements,6,md.mesh.numberofelements));
+		x=transpose(reshape(md.mesh.x(data.index)',1,6*md.mesh.numberofelements));
+		y=transpose(reshape(md.mesh.y(data.index)',1,6*md.mesh.numberofelements));
+		z=transpose(reshape(md.mesh.z(data.index)',1,6*md.mesh.numberofelements));
+		is2d=0;
+	end
+end
+
+%units
+if exist(options,'unit'),
+	unit=getfieldvalue(options,'unit');
+	x=x*unit;
+	y=y*unit;
+	z=z*unit;
+end
+
+if isa(md,'planet'),
+	isplanet=1;
+else
+	isplanet=0;
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/quiver_colorbar.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/quiver_colorbar.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/quiver_colorbar.m	(revision 11330)
@@ -0,0 +1,41 @@
+function quiver_colorbar(quivers,options)
+%QUIVER_COLORBAR - colorbar for quiver plots
+%
+%   Usage:
+%      quiver_colorbar(quivers,options)
+
+if  strcmpi(getfieldvalue(options,'colorbar','on'),'on'),
+
+	%build ticks
+	hcb=colorbar('peer',gca,'location','EastOutside');
+	ticklabel=cell(1,length(quivers.levels));
+	for i=1:length(quivers.levels),
+		ticklabel{i}=num2str(round_ice(quivers.levels(i),3));
+	end
+	tickpos=1:quivers.numcolors+1;
+
+	%remove ticks if to many have been created
+	proportion=round(length(quivers.levels)/4);
+	if proportion>1,
+		ticklabel=ticklabel(1:proportion:end);
+		tickpos=tickpos(1:proportion:end);
+	end
+
+	%draw colorbar
+	set(hcb,'YTickLabel',ticklabel,'YTick',tickpos);
+	%position
+	if exist(options,'colorbarpos'),
+		set(hcb,'Position',getfieldvalue(options,'colorbarpos'));
+	end
+	%fontsize
+	fontsize=getfieldvalue(options,'fontsize',14);
+	set(hcb,'FontSize',fontsize);
+	
+	if exist(options,'colorbartitle'),
+		backup=gca;
+		axes(hcb);lab=title(getfieldvalue(options,'colorbartitle'));
+		set(lab,'Rotation',getfieldvalue(options,'colorbartitlerotation',0));
+		set(lab,'VerticalAlignment','bottom');
+		axes(backup);
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/quiver_process.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/quiver_process.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/quiver_process.m	(revision 11330)
@@ -0,0 +1,70 @@
+function [quivers,palette]=quiver_process(x,y,u,v,options)
+%QUIVER_PROCESS - process data for color quiver plot
+%
+%   Usage:
+%      [quivers,palette]=quiver_process(x,y,u,v,options)
+
+%keep only non NaN elements
+pos=find(~isnan(x) & ~isnan(y) & ~isnan(u) & ~isnan(v));
+x=x(pos); y=y(pos);
+u=u(pos); v=v(pos);
+
+%get Norm Min and Max
+Norm=sqrt(u.^2+v.^2);
+Min=min(Norm);
+Max=max(Norm);
+
+%Scale data
+scalingfactor=getfieldvalue(options,'scaling',0.40);
+if strcmpi(getfieldvalue(options,'autoscale','on'),'off'),
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./Norm;
+	v=scalingfactor*sqrt(delta)*v./Norm;
+else
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./max(Norm);
+	v=scalingfactor*sqrt(delta)*v./max(Norm);
+end
+
+%number of colors?
+colorlevels=getfieldvalue(options,'colorlevels',30);
+if isnumeric(colorlevels),
+	if isnan(colorlevels),
+		numcolors=30;
+	else
+		numcolors=colorlevels;
+	end
+	levels=round_ice(linspace(Min,Max,numcolors+1),2);
+else
+	levels=zeros(1,length(colorlevels)+2);
+	levels(1)=Min;
+	for i=1:length(colorlevels)
+		levels(i+1)=colorlevels{i};
+	end
+	levels(end)=Max;
+	levels=sort(unique(levels));
+	numcolors=length(levels)-1;
+end
+
+%create colorind for colors
+colorind=ones(length(u),1);
+for i=1:numcolors
+	pos=find((Norm>=levels(i)) & (Norm<=levels(i+1)) );
+	colorind(pos)=i;
+end
+colorind(find(Norm>levels(end)))=numcolors;
+
+%build output
+quivers=struct('x',x,'y',y,'u',u,'v',v,'levels',levels,'colorind',colorind,'numcolors',numcolors);
+
+%set the colormap 
+if numcolors==2;
+	%blue and red
+	palette=colormap([0 0 1;1 0 0]);
+elseif numcolors==3,
+	%blue yellow and red
+	palette=colormap([0 0 1;1 1 0;1 0 0]);
+else
+	%let jet choose
+	palette=colormap(jet(numcolors));
+end
Index: /issm/trunk-jpl-damage/src/m/model/plot/scaleruler.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/scaleruler.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/scaleruler.m	(revision 11330)
@@ -0,0 +1,61 @@
+function scaleruler(options)
+%SCALERULER - overlay a scale ruler on current plot
+%
+%   Usage:
+%      scaleruler(options)
+
+%get options
+structure=getfieldvalue(options,'scaleruler');
+fontsize=getfieldvalue(options,'scaleruler_fontsize',16);
+
+%Go through structure and fill missing arguments
+if length(structure)~=5
+	error('plotmodel error message: bad number of input arguments for scaleruler: [x0 y0 length thickness numberofticks]');
+end
+
+%retrieve north arrow parameters
+x0=structure(1);
+y0=structure(2);
+lengthscale=structure(3);
+widthscale=structure(4);
+numberofticks=structure(5);
+
+%initialize some coordinates
+unitlength=lengthscale/(numberofticks -1);
+flag=-1;
+
+Bd=[x0 y0];
+Bu=[x0 y0+widthscale];
+Tick=0;
+
+%Text
+xt=Bu(1);
+yt=Bu(2)+widthscale;
+text(xt,yt,num2str(Tick),'FontSize',fontsize,'FontWeight','n','HorizontalAlignment','left','VerticalAlignment','baseline');
+
+%loope over the patches
+for i=1:numberofticks-1,
+	Au=Bu;
+	Ad=Bd;
+	Bu=[Au(1)+unitlength Ad(2)+widthscale];
+	Bd=[Ad(1)+unitlength Ad(2)];
+	Tick=Tick+unitlength;
+
+	%pathes
+	if flag==-1
+		p=patch([Ad(1) Bd(1) Bu(1) Au(1)],[Ad(2) Bd(2) Bu(2) Au(2)],'Black','FaceAlpha',0.5);
+	else
+		p=patch([Ad(1) Bd(1) Bu(1) Au(1)],[Ad(2) Bd(2) Bu(2) Au(2)],'White','FaceAlpha',0.3);
+	end
+
+	%flip flag
+	flag=-flag;
+
+	%Text
+	xt=Bu(1);
+	yt=Bu(2)+widthscale;
+	if i~=numberofticks-1,
+		text(xt,yt,num2str(round_ice(Tick/1000,3)),'FontSize',fontsize,'FontWeight','n','HorizontalAlignment','left','VerticalAlignment','baseline');
+	end
+end
+text(xt,yt,[num2str(round_ice(Tick/1000,3)) ' km'],'FontSize',fontsize,'FontWeight','n','HorizontalAlignment','left','VerticalAlignment','baseline');
Index: /issm/trunk-jpl-damage/src/m/model/plot/showregion.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/plot/showregion.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/plot/showregion.m	(revision 11330)
@@ -0,0 +1,34 @@
+function showregion(md,insetpos)
+%SHOWREGION - show region on plot
+%
+%   Usage:
+%      showregion(md,insetpos);
+
+%get inset relative position (x,y,width,height)
+%insetpos=getfieldvalue(options,'insetpos',[0.02 0.70 0.18 0.18]);
+
+%get current plos position
+cplotpos=get(gca,'pos');
+%compute inset position
+PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
+axes('pos',PosInset);
+axis equal off
+%box off
+if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
+	A=expread([issmdir() 'projects/Exp/Greenland.exp']);
+elseif strcmpi(md.mesh.hemisphere,'s') | strcmpi(md.mesh.hemisphere,'south'),
+	A=expread([issmdir() '/projects/Exp/Antarctica.exp']);
+else
+	error('applyoptions error message: hemisphere not defined');
+end
+
+Ax=[min(A.x) max(A.x)];
+Ay=[min(A.y) max(A.y)];
+
+mdx=[min(md.mesh.x) max(md.mesh.x)];
+mdy=[min(md.mesh.y) max(md.mesh.y)];
+
+line(A.x,A.y,'color','b');
+patch([Ax(1)  Ax(2)  Ax(2)  Ax(1) Ax(1)],[Ay(1)  Ay(1)  Ay(2)  Ay(2) Ay(1)],[1 1 1],'EdgeColor',[0 0 0],'LineWidth',1,'FaceLighting','none')
+patch( [mdx(1) mdx(2) mdx(2) mdx(1)],[mdy(1) mdy(1) mdy(2) mdy(2)],ones(4,1),'EdgeColor',[0 0 0],'FaceColor','r','FaceAlpha',0.5)
+colorbar('off');
Index: /issm/trunk-jpl-damage/src/m/model/printmodel.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/printmodel.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/printmodel.m	(revision 11330)
@@ -0,0 +1,100 @@
+function printmodel(filename,format,varargin)
+%PRINTMODEL - save an image of current figure
+%
+%   filename: output name of image file (no extension)
+%   format: image format (ex: 'tiff','jpg','pdf') 
+%
+%   List of options to printfmodel: 
+%
+%   figure: number of figure to print (default: current figure)
+%   resolution: use higher resolution to anti-alias (default 2)
+%   margin: add margin around final image  
+%   marginsize: size of margin around final image (default 5)
+%   frame: add frame around final image
+%   framesize: size of frame around final image (default 5)
+%   framecolor: color of frame around final image (default 'black')
+%   trim: trim empty space around image (default 'off')
+%   hardcopy: 'off' to impose MATLAB to use the same colors (default 'off')
+%   
+%   Usage:
+%      printmodel(filename,format,varargin);
+%
+%   Examples:
+%      printmodel('image','tiff')
+%      printmodel('image','eps','margin','on','frame','on','hardcopy','on')
+
+
+%get options: 
+options=pairoptions(varargin{:});
+
+%set defaults
+options=addfielddefault(options,'figure','gcf');
+options=addfielddefault(options,'format','tiff');
+options=addfielddefault(options,'resolution',2);
+options=addfielddefault(options,'margin','on');
+options=addfielddefault(options,'marginsize',5);
+options=addfielddefault(options,'frame','on');
+options=addfielddefault(options,'framesize',2);
+options=addfielddefault(options,'framecolor','black');
+options=addfielddefault(options,'trim','on');
+options=addfielddefault(options,'hardcopy','off');
+
+%get fig: 
+fig=getfieldvalue(options,'figure');
+if ischar(fig),
+	fig=gcf;
+else
+	figure(fig);
+	fig=gcf;
+end
+
+%In auto mode, MATLAB prints the figure the same size as it appears on the computer screen, centered on the page
+set(fig, 'PaperPositionMode', 'auto');
+
+%InvertHardcopy off imposes MATLAB to use the same colors
+set(fig, 'InvertHardcopy', getfieldvalue(options,'hardcopy'));
+
+
+%we could have several formats, as a cell array of strings.
+formats=format;
+if ~iscell(formats),
+	formats={formats};
+end
+
+%loop on formats:
+for i=1:length(formats),
+	format=formats{i};
+
+	%Use higher resolution to anti-alias and use zbuffer to have smooth colors
+	print(fig, '-zbuffer','-dtiff',['-r' num2str(get(0,'ScreenPixelsPerInch')*getfieldvalue(options,'resolution'))],filename);
+
+	%some trimming involved? 
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'trim'),'on'),
+			system(['convert -trim ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	%margin?
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'margin'),'on'),
+			marginsize=getfieldvalue(options,'marginsize');
+			system(['convert -border ' num2str(marginsize) 'x' num2str(marginsize) ' -bordercolor "white" ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	%frame?
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'frame'),'on'),
+			framesize=getfieldvalue(options,'framesize');
+			framecolor=getfieldvalue(options,'framecolor');
+			system(['convert -border ' num2str(framesize) 'x' num2str(framesize) ' -bordercolor "' framecolor '" ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	%convert image to correct format
+	if ~strcmpi(format,'tiff') & ~strcmpi(format,'tif'),
+		system(['convert ' filename '.tif ' filename '.' format]);
+		delete([ filename '.tif']);
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/process_solve_options.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/process_solve_options.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/process_solve_options.m	(revision 11330)
@@ -0,0 +1,39 @@
+function outoptions=process_solve_options(options)
+%DEFAULT_SOLVE_OPTIONS - set up default options for solve phase
+%
+%   Usage:
+%      options=process_solve_options(options)
+%
+%   See also: SOLVE
+
+%solution_type: check on this option, error out otherwise
+solution_type=getfieldvalue(options,'solution_type');
+if ~ismember(solution_type,[DiagnosticSolutionEnum,PrognosticSolutionEnum,ThermalSolutionEnum,...
+		SteadystateSolutionEnum,TransientSolutionEnum,EnthalpySolutionEnum,...
+		BalancethicknessSolutionEnum,BedSlopeSolutionEnum,SurfaceSlopeSolutionEnum,HydrologySolutionEnum,FlaimSolutionEnum]),
+	error(['process_solve_options error message: solution_type ' EnumToString(solution_type) ' not supported yet!']);
+end
+outoptions.solution_type=solution_type;
+
+outoptions.upload=getfieldvalue(options,'upload','off');
+outoptions.batch=getfieldvalue(options,'batch','no');
+outoptions.loadonly=getfieldvalue(options,'loadonly',false);
+outoptions.directory=getfieldvalue(options,'directory','');
+
+%  process qmu arguments
+outoptions.qmudir=getfieldvalue(options,'qmudir',['qmu' num2str(feature('GetPid'))]);  % qmudir =['qmu_' datestr(now,'yyyymmdd_HHMMSS')];
+outoptions.qmufile=getfieldvalue(options,'qmufile','qmu');% qmufile cannot be changed unless ????script.sh is also changed
+outoptions.overwrite=getfieldvalue(options,'overwrite','n');
+outoptions.keep=getfieldvalue(options,'keep','n');
+outoptions.ivar=getfieldvalue(options,'ivar',1);
+outoptions.iresp=getfieldvalue(options,'iresp',1);
+outoptions.imethod=getfieldvalue(options,'imethod',1);
+outoptions.iparams=getfieldvalue(options,'iparams',1);
+outoptions.runmpi=getfieldvalue(options,'runmpi',false);
+
+%  process flaim arguments
+outoptions.fmdir=getfieldvalue(options,'fmdir',['fm' num2str(feature('GetPid'))]);
+outoptions.overwrite=getfieldvalue(options,'overwrite','n');
+outoptions.keep=getfieldvalue(options,'keep','y');
+outoptions.latsgn=getfieldvalue(options,'latsgn',0);
+outoptions.cmap=getfieldvalue(options,'cmap',[]);
Index: /issm/trunk-jpl-damage/src/m/model/processgeometry.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/processgeometry.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/processgeometry.m	(revision 11330)
@@ -0,0 +1,140 @@
+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)),:)=[];
Index: /issm/trunk-jpl-damage/src/m/model/project2d.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/project2d.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/project2d.m	(revision 11330)
@@ -0,0 +1,36 @@
+function projection_value=project2d(md3d,value,layer)
+%PROJECT2D - returns the value of a field for a given layer of the mesh
+%
+%   project 'value' vector taken at layer 'layer' from extruded 2d-3d mesh onto 2d mesh 
+%   used to do the extrusion. This routine is used to compare values between a 2d-3d mesh
+%   at a certain layer, and the equivalent value (if it exists), on the original 2d mesh. 
+%   This routine relies heavily on projections (contained in 3d model md) recored during 
+%   the extrude operation.
+%
+%   Usage:
+%      projection_value=project2d(md3d,value,layer)
+%
+%   Example:
+%      vel2=project2d(md3d,md3d.vel,2);
+
+%some checks on list of arguments
+if ((nargin~=3) ),
+	help project2d
+	error('project2d error message');
+end
+
+if (md3d.mesh.dimension~=3),
+	error('wrong model type ... should be ''3d''');
+end
+
+if ((layer<1) | (layer>md3d.mesh.numberoflayers)),
+	error(['layer must be between 1 and ' num2str(md3d.mesh.numberoflayers)]);
+end
+
+if size(value,1)==md3d.mesh.numberofvertices,
+	projection_value=value((layer-1)*md3d.mesh.numberofvertices2d+1:layer*md3d.mesh.numberofvertices2d,:);
+elseif size(value,1)==md3d.mesh.numberofvertices+1,
+	projection_value=[value((layer-1)*md3d.mesh.numberofvertices2d+1:layer*md3d.mesh.numberofvertices2d,:); value(end,:)];
+else
+	projection_value=value((layer-1)*md3d.mesh.numberofelements2d+1:layer*md3d.mesh.numberofelements2d,:);
+end
Index: /issm/trunk-jpl-damage/src/m/model/project3d.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/project3d.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/project3d.m	(revision 11330)
@@ -0,0 +1,82 @@
+function projected_vector=project3d(md,varargin);
+%PROJECT3D - vertically project a vector from 2d mesh
+%
+%   vertically project a vector from 2d mesh (split in noncoll and coll areas) into a 3d mesh.
+%   This vector can be a node vector of size (md.mesh.numberofvertices2d,N/A) or an 
+%   element vector of size (md.mesh.numberofelements2d,N/A). 
+%   arguments: 
+%      'vector': 2d vector
+%      'type': 'element' or 'node'. 
+%   options: 
+%      'layer' a layer number where vector should keep its values. If not specified, all layers adopt the 
+%             value of the 2d vector.
+%      'padding': default to 0 (value adopted by other 3d layers not being projected0
+%
+%   Egs:
+%      extruded_vector=project3d(md,'vector',vector2d,'type','node','layer',1,'padding',NaN);
+%      extruded_vector=project3d(md,'vector',vector2d,'type','element','padding',0);
+%      extruded_vector=project3d(md,'vector',vector2d,'type','node');
+
+%some regular checks
+if nargin==0,
+	help project3d
+	error('bad usage');
+end
+if md.mesh.dimension~=3
+	error('input model is not 3d');
+end
+
+%retrieve parameters from options.
+options      = pairoptions(varargin{:});
+vector2d     = getfieldvalue(options,'vector');     %mandatory
+type         = getfieldvalue(options,'type');       %mandatory
+layer        = getfieldvalue(options,'layer',0);    %optional (do all layers otherwise)
+paddingvalue = getfieldvalue(options,'padding',0);  %0 by default
+
+if length(vector2d)==1,
+	projected_vector=vector2d;
+elseif strcmpi(type,'node'),
+
+	%Initialize 3d vector
+	if size(vector2d,1)==md.mesh.numberofvertices2d
+		projected_vector=paddingvalue*ones(md.mesh.numberofvertices,  size(vector2d,2));
+	elseif size(vector2d,1)==md.mesh.numberofvertices2d+1
+		projected_vector=paddingvalue*ones(md.mesh.numberofvertices+1,size(vector2d,2));
+		projected_vector(end,:)=vector2d(end,:);
+		vector2d=vector2d(1:end-1,:);
+	else
+		error('vector length not supported')
+	end
+
+	%Fill in
+	if layer==0,
+		for i=1:md.mesh.numberoflayers,
+			projected_vector(((i-1)*md.mesh.numberofvertices2d+1):(i*md.mesh.numberofvertices2d),:)=vector2d;
+		end
+	else
+		projected_vector(((layer-1)*md.mesh.numberofvertices2d+1):(layer*md.mesh.numberofvertices2d),:)=vector2d;
+	end
+elseif strcmpi(type,'element'),
+
+	%Initialize 3d vector
+	if size(vector2d,1)==md.mesh.numberofelements2d
+		projected_vector=paddingvalue*ones(md.mesh.numberofelements,  size(vector2d,2));
+	elseif size(vector2d,1)==md.mesh.numberofelements2d+1
+		projected_vector=paddingvalue*ones(md.mesh.numberofelements+1,size(vector2d,2));
+		projected_vector(end,:)=vector2d(end,:);
+		vector2d=vector2d(1:end-1,:);
+	else
+		error('vector length not supported')
+	end
+
+	if layer==0,
+		for i=1:(md.mesh.numberoflayers-1),
+			projected_vector( ((i-1)*md.mesh.numberofelements2d+1):(i*md.mesh.numberofelements2d),:)=vector2d;
+		end
+
+	else
+		projected_vector( ((layer-1)*md.mesh.numberofelements2d+1):(layer*md.mesh.numberofelements2d),:)=vector2d;
+	end
+else
+	error('project3d error message: unknown projection type');
+end
Index: /issm/trunk-jpl-damage/src/m/model/qpr.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/qpr.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/qpr.m	(revision 11330)
@@ -0,0 +1,7 @@
+function qpr(name,format)
+%QPR: quick print of a model
+%
+% Usage: qpr(name,format)
+
+printmodel(name,format,'trim','on','resolution',1,'margin','on','marginsize',25,'frame','on','framesize',3);
+
Index: /issm/trunk-jpl-damage/src/m/model/qstat.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/qstat.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/qstat.m	(revision 11330)
@@ -0,0 +1,8 @@
+function qstat(md)
+%QSTAT - check job status on remote cluster
+%
+%   Usage:
+%      qstat(md)
+
+%run qstat command on remote cluster
+issmssh(md.cluster,['qstat -a']);
Index: /issm/trunk-jpl-damage/src/m/model/radarpower.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/radarpower.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/radarpower.m	(revision 11330)
@@ -0,0 +1,116 @@
+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)
+
+%If gdal does not work, uncomment the following line
+setenv('LD_LIBRARY_PATH','/proj/ice/larour/issm/trunk/externalpackages/gdal/install/lib/');
+%Parse inputs
+if nargin==1,
+	options=pairoptions;
+else
+	options=varargin{:};
+	if ~isa(options,'pairoptions'),
+		options=pairoptions(varargin{:});
+	end
+end
+
+highres=getfieldvalue(options,'highres',0);
+xlim=getfieldvalue(options,'xlim',[min(md.mesh.x) max(md.mesh.x)]);
+ylim=getfieldvalue(options,'ylim',[min(md.mesh.y) max(md.mesh.y)]);
+posting=getfieldvalue(options,'posting',0); % 0 -> image posting default
+
+%find gdal coordinates
+x0=min(xlim); x1=max(xlim);
+y0=min(ylim); y1=max(ylim);
+
+%figure out if we should go look for Greenland or Antarctica geotiff, or if user provided one.
+if ~exist(options,'overlay_image'),
+	if strcmpi(md.mesh.hemisphere,'n'),
+		if ~exist([issmdir() '/projects/ModelData/MOG/mog150_greenland_map.jpg']),
+			error(['radarpower error message: file ' issmdir() '/projects/ModelData/MOG/mog150_greenland_map.jpg not found.']);
+		end
+		jpgim=[issmdir() '/projects/ModelData/MOG/mog150_greenland_map.jpg'];
+		geom=load([issmdir() '/projects/ModelData/MOG/mog150_greenland_map.jpgw'],'ascii');
+
+		%geom:   xposting nbcols nbrows yposting xmin ymax
+		xmin=max(geom(5),x0);
+		xmax=min(geom(5)+geom(1)*geom(2),x1);
+		ymin=max(geom(6)-geom(4)*geom(3),y0);
+		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);
+
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		if highres,
+			if ~exist([issmdir() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif']),
+				error(['radarpower error message: file ' issmdir() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif not found.']);
+			end
+			geotiff_name=[issmdir() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif'];
+		else
+			if ~exist([issmdir() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif']),
+				error(['radarpower error message: file ' issmdir() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif not found.']);
+			end
+			geotiff_name=[issmdir() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif'];
+		end
+
+		%Name of image
+		inputname='./temp.tif';
+		eval(['!gdal_translate -quiet -projwin ' num2str(x0) ' ' num2str(y1) ' ' num2str(x1) ' ' num2str(y0) ' ' geotiff_name ' ' inputname ]);
+
+		%Read in temp.tif:
+		im=imread('temp.tif','TIFF');
+		pixelskip=max(1,ceil(posting/((x1-x0)/(size(im,2)))));
+		md.radaroverlay.pwr=double(flipud(im(1:pixelskip:end,1:pixelskip:end)));
+		md.radaroverlay.x=(x0:(x1-x0)/(size(md.radaroverlay.pwr,2)-1):x1);
+		md.radaroverlay.y=(y0:(y1-y0)/(size(md.radaroverlay.pwr,1)-1):y1);
+
+		%Erase image
+		system('rm -rf ./temp.tif');
+
+	else
+		error('field hemisphere should either be ''n'' or ''s''');
+	end
+else
+	%ok, user provided an image. check we also have overlay_xlim and overlay_ylim  options, to know what range of coordinates the image covers.
+	if (~exist(options,'overlay_xlim') | ~exist(options,'overlay_xlim')| ~exist(options,'overlay_xposting')| ~exist(options,'overlay_yposting')),
+		error('radarpower error message: please provide overlay_xlim, overlay_ylim, overlay_xposting and overlay_yposting options together with overlay_image option');
+	end
+	overlay_image=getfieldvalue(options,'overlay_image');
+	overlay_xlim=getfieldvalue(options,'overlay_xlim');
+	overlay_ylim=getfieldvalue(options,'overlay_ylim');
+	overlay_xposting=getfieldvalue(options,'overlay_xposting');
+	overlay_yposting=getfieldvalue(options,'overlay_yposting');
+
+	sizex=floor((x1-x0)/overlay_xposting);
+	sizey=floor((y1-y0)/overlay_yposting);
+	topleftx=floor((x0-overlay_xlim(1))/overlay_xposting); % x min
+	toplefty=floor((overlay_ylim(2)-y1)/overlay_yposting); % y max
+
+
+	%Read and crop file
+	disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	im=imread(overlay_image);
+	im=im(toplefty:toplefty+sizey,topleftx:topleftx+sizex);
+	md.radaroverlay.pwr=double(flipud(im));
+	md.radaroverlay.x=(x0:(x1-x0)/(size(md.radaroverlay.pwr,2)-1):x1);
+	md.radaroverlay.y=(y0:(y1-y0)/(size(md.radaroverlay.pwr,1)-1):y1);
+end
Index: /issm/trunk-jpl-damage/src/m/model/recover_areas.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/recover_areas.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/recover_areas.m	(revision 11330)
@@ -0,0 +1,23 @@
+function [hutterflag macayealflag pattynflag stokesflag filltype]=recover_areas(md,varargin);
+%RECOVER_AREAS - flag the element depending on the physical model that is assigned to them
+%
+%   This routine is called by setelementstype, do not use
+%
+%   Usage:
+%      [hutterflag macayealflag pattynflag stokesflag filltype]=recover_areas(md,varargin);
+
+	%go through varargin, extract options and plug them into subtype options, by order of appearance
+	options=pairoptions(varargin{:});
+	options=deleteduplicates(options,1);
+
+	%recover elements distribution
+	hutterflag  =FlagElements(md,getfieldvalue(options,'hutter',''));
+	macayealflag=FlagElements(md,getfieldvalue(options,'macayeal',''));
+	pattynflag  =FlagElements(md,getfieldvalue(options,'pattyn',''));
+	stokesflag  =FlagElements(md,getfieldvalue(options,'stokes',''));
+	hutterflag  =FlagElements(md,getfieldvalue(options,'hutter',''));
+	filltype    =getfieldvalue(options,'fill','none');
+
+end %end function
+
+
Index: /issm/trunk-jpl-damage/src/m/model/regionaltransient2d.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/regionaltransient2d.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/regionaltransient2d.m	(revision 11330)
@@ -0,0 +1,158 @@
+function md2=regionaltransient2d(md1,area,hmin,hmax,err,stepres)
+%regionaltransient2d - extract a model according to an Argus contour or flag list and remesh
+%               at new resolution res
+%
+%   This routine extracts a submodel from a bigger model with respect to a given contour
+%   md must be followed by the corresponding exp domain file (argus type, .exp extension). 
+%   The model will be remeshed at high rsolution hmin and low resolution hmax.  The ice 
+%   boundary velocities will be spc'd to the transient velocities at saved transient steps
+%   at the resolution optionally provided for stepres.  A stepres of 2 means that you wish
+%   to skip every other saved transient step.  This is useful when extracting a long transient.
+%
+%   Usage:
+%      md2=regionaltransient2d(md1,area,hmin,hmax,err);
+%
+%   Examples:
+%      md2=regionaltransient2d(md,'Domain.exp',500,10000,[15 250]);
+%      md2=regionaltransient2d(md,'Domain.exp',3000,15000,[10 300],2);
+%
+%   See also: MODELEXTRACT, EXTRUDE, COLLAPSE
+
+%some checks
+if ((nargin~=5) & (nargin~=6)),
+	help regionaltransient2d 
+	error('regionaltransient2d error message: bad usage');
+end
+
+%get check option
+if (nargin==5),
+	stepres=1;
+end
+
+%take every fields from model
+mde=modelextract(md1,area);
+mde.private.bamg=[];
+mde.mesh.extractedvertices=nan;
+mde.mesh.extractedelements=nan;
+
+%remesh
+md2=bamg(mde,'hmin',hmin,'hmax',hmax,'field',[mde.inversion.vel_obs mde.geometry.surface],'splitcorner',1,'KeepVertices',0,'err',err);
+md2=setmask(md2,'','');
+
+%automatically modify fields
+
+	%loop over model fields
+	model_fields=fields(md1);
+	for i=1:length(model_fields),
+
+		%get field
+		field=md1.(model_fields{i});
+		fieldsize=size(field);
+
+		%copy field, interpolated to new mesh
+		if isobject(field), %recursive call
+			object_fields=fields(md1.(model_fields{i}));
+			fname=['(model_fields{i}).(object_fields{j})'];
+		else
+			object_fields=field;
+			fname=['(model_fields{i})'];
+		end
+		for j=1:length(object_fields),
+			%get field
+			field=eval(['md2.' fname]);
+			fieldsize=size(field);
+
+			%size = number of nodes * n
+			for n=1:fieldsize(2)
+				if fieldsize(1)==mde.mesh.numberofvertices
+					if(sum(field(:,n) ~= field(1,n)) == 0)
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices,n)=field(1,n)*ones(md2.mesh.numberofvertices,1);']);
+					else
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices,n)=InterpFromMeshToMesh2d(mde.mesh.elements,mde.mesh.x,mde.mesh.y,field(:,n),md2.mesh.x,md2.mesh.y);']);
+					end
+					eval(['md2.' fname '(:,n)=md2.' fname '(1:md2.mesh.numberofvertices,n);']);
+				elseif fieldsize(1)==mde.mesh.numberofvertices+1
+					if(sum(field(1:end-1,n) ~= field(1,n)) == 0)
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices+1,n)=[field(1,n)*ones(md2.mesh.numberofvertices,1); field(end,n)];']);
+					else
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices+1,n)=[InterpFromMeshToMesh2d(mde.mesh.elements,mde.mesh.x,mde.mesh.y,field(1:end-1,n),md2.mesh.x,md2.mesh.y); field(end,n)];']);
+					end
+					eval(['md2.' fname '(:,n)=md2.' fname '(1:md2.mesh.numberofvertices+1,n)']);
+					%size = number of elements * n
+				elseif fieldsize(1)==mde.mesh.numberofelements
+					if(sum(field(1:end-1,n) ~= field(1,n)) == 0)
+						eval(['md2.' fname '(1:md2.mesh.numberofelements,n)=field(1,n)*ones(md2.mesh.numberofelements,1);']);
+					else
+						eval(['md2.' fname '(1:md2.mesh.numberofelements,n)=InterpFromMeshToMesh2d(mde.mesh.elements,mde.mesh.x,mde.mesh.y,field(:,n),md2.mesh.x,md2.mesh.y);']);
+					end
+					eval(['md2.' fname '(:,n)=md2.' fname '(1:md2.mesh.numberofelements,n);']);
+				end
+			end
+		end
+	end
+
+	%Read transient velocities and thickness, looping through only the populated times
+	spcx=[];
+	spcy=[];
+	spct=[];
+	steps=[];
+	nsteps=length(md1.results.TransientSolution);
+	count=0;
+	numElements=arrayfun(@(x) numel(x.step), md1.results.TransientSolution);
+	for t=find(numElements==1)
+		if ~isempty(md1.results.TransientSolution(t).Vel) & mod(count,stepres)==0,
+			vx=PatchToVec(md1.results.TransientSolution(t).Vx);
+			vy=PatchToVec(md1.results.TransientSolution(t).Vy);
+			thickness=PatchToVec(md1.results.TransientSolution(t).Thickness);
+			spcx=[spcx InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,vx,md2.mesh.x,md2.mesh.y)];
+			spcy=[spcy InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,vx,md2.mesh.x,md2.mesh.y)];
+			spct=[spct InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,thickness,md2.mesh.x,md2.mesh.y)];
+			steps=[steps t*md1.timestepping.time_step];
+		end
+		count=count+1;
+	end
+
+	%As long as there are recorded time steps, spc the boundaries with velocities
+	if nsteps > 0
+		md2.diagnostic.spcvx=md2.diagnostic.spcvx*ones(1,size(spcx,2));
+		md2.diagnostic.spcvy=md2.diagnostic.spcvy*ones(1,size(spcy,2));
+		md2.diagnostic.spcvz=md2.diagnostic.spcvz*ones(1,size(spcx,2));
+		md2.prognostic.spcthickness=md2.prognostic.spcthickness*ones(1,size(spct,2));
+		md2.diagnostic.spcvx(find(md2.mesh.vertexonboundary),:)=spcx(find(md2.mesh.vertexonboundary),:);
+		md2.diagnostic.spcvy(find(md2.mesh.vertexonboundary),:)=spcy(find(md2.mesh.vertexonboundary),:);
+		md2.diagnostic.spcvz(find(md2.mesh.vertexonboundary),:)=0;
+		md2.prognostic.spcthickness(find(md2.mesh.vertexonboundary),:)=spct(find(md2.mesh.vertexonboundary),:);
+		md2.diagnostic.spcvx=[md2.diagnostic.spcvx; steps];
+		md2.diagnostic.spcvy=[md2.diagnostic.spcvy; steps];
+		md2.diagnostic.spcvz=[md2.diagnostic.spcvz; steps];
+		md2.prognostic.spcthickness=[md2.prognostic.spcthickness; steps];
+	end
+
+	%Diagnostic.  Don't spc the icefront vertices.
+	if ~isnan(md2.diagnostic.icefront)
+		md1s=modelextract(md1,area);
+		%md2.diagnostic.icefront=[md2.mesh.segments 2];
+		e2=md2.mesh.segments(:,end);
+		e1=md1s.mesh.segments(:,end);
+
+		pload = nan*ones(size(md1s.mesh.elements,1),1);
+		pload(md1s.diagnostic.icefront(:,end-1))=md1s.diagnostic.icefront(:,end);
+
+		x2=mean(md2.mesh.x(md2.mesh.elements(e2,:)),2);
+      y2=mean(md2.mesh.y(md2.mesh.elements(e2,:)),2);
+		x1=mean(md1s.mesh.x(md1s.mesh.elements),2);
+      y1=mean(md1s.mesh.y(md1s.mesh.elements),2);
+
+		pload2=griddata(x1,y1,pload,x2,y2,'nearest');
+		md2.diagnostic.icefront=[md2.mesh.segments(~isnan(pload2),:) pload2(~isnan(pload2))];
+		md2.diagnostic.spcvx(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
+		md2.diagnostic.spcvy(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
+		md2.diagnostic.spcvz(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
+		md2.prognostic.spcthickness(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
+	end
+
+	%Clear results fields
+	if isstruct(md1.results),
+		md2.results=[];
+	end
+
Index: /issm/trunk-jpl-damage/src/m/model/setflowequation.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/setflowequation.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/setflowequation.m	(revision 11330)
@@ -0,0 +1,281 @@
+function md=setflowequation(md,varargin)
+%SETELEMENTSTYPE - associate a solution type to each element
+%
+%   This routine works like plotmodel: it works with an even number of inputs
+%   'hutter','macayeal','pattyn','stokes' and 'fill' are the possible options
+%   that must be followed by the corresponding exp file or flags list
+%   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
+%   If user wants every element outside the domain to be 
+%   setflowequationd, add '~' to the name of the domain file (ex: '~Pattyn.exp');
+%   an empty string '' will be considered as an empty domain
+%   a string 'all' will be considered as the entire domain
+%   You can specify the type of coupling, 'penalties' or 'tiling', to use with the input 'coupling'
+%
+%   Usage:
+%      md=setflowequation(md,varargin)
+%
+%   Example:
+%      md=setflowequation(md,'pattyn','Pattyn.exp','macayeal',md.mask.elementonfloatingice,'fill','hutter');
+%      md=setflowequation(md,'pattyn','Pattyn.exp',fill','hutter','coupling','tiling');
+
+%some checks on list of arguments
+if ((nargin<2) | (nargout~=1)),
+	error('setflowequation error message');
+end
+
+%Find_out what kind of coupling to use
+options=pairoptions(varargin{:});
+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
+
+[hutterflag macayealflag pattynflag stokesflag filltype]=recover_areas(md,varargin{:});
+
+%Flag the elements that has not been flagged as filltype
+if strcmpi(filltype,'hutter'),
+	hutterflag(find(~macayealflag & ~pattynflag))=1;
+elseif strcmpi(filltype,'macayeal'),
+	macayealflag(find(~hutterflag & ~pattynflag & ~stokesflag))=1;
+elseif strcmpi(filltype,'pattyn'),
+	pattynflag(find(~hutterflag & ~macayealflag & ~stokesflag))=1;
+end
+
+%check that each element has at least one flag
+if any(hutterflag+ macayealflag+pattynflag+stokesflag==0),
+	error('setflowequation error message: elements type not assigned, must be specified')
+end
+
+%check that each element has only one flag
+if any(hutterflag+ macayealflag+pattynflag+stokesflag>1),
+	disp('setflowequation warning message: some elements have several types, higher order type is used for them')
+	hutterflag(find(hutterflag & macayealflag))=0;
+	hutterflag(find(hutterflag & pattynflag))=0;
+	macayealflag(find(macayealflag & pattynflag))=0;
+end
+
+%Check that no pattyn or stokes for 2d mesh
+if (md.mesh.dimension==2),
+	if any(stokesflag | pattynflag)
+		error('setflowequation error message: stokes and pattyn elements no allowed in 2d mesh, extrude it first')
+	end
+end
+
+%Stokes can only be used alone for now:
+if any(stokesflag) &any(hutterflag),
+	error('setflowequation error message: stokes cannot be used with any other model for now, put stokes everywhere')
+end
+
+%Initialize node fields
+nodeonhutter=zeros(md.mesh.numberofvertices,1);
+nodeonhutter(md.mesh.elements(find(hutterflag),:))=1;
+nodeonmacayeal=zeros(md.mesh.numberofvertices,1);
+nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+nodeonpattyn=zeros(md.mesh.numberofvertices,1);
+nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
+nodeonstokes=zeros(md.mesh.numberofvertices,1);
+noneflag=zeros(md.mesh.numberofelements,1);
+
+%First modify stokesflag to get rid of elements contrained everywhere (spc + border with pattyn or macayeal)
+if any(stokesflag),
+	fullspcnodes=double((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy)+~isnan(md.diagnostic.spcvz))==3 | (nodeonpattyn & nodeonstokes));         %find all the nodes on the boundary of the domain without icefront
+	fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6);         %find all the nodes on the boundary of the domain without icefront
+	stokesflag(find(fullspcelems))=0;
+	nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+end
+
+%Then complete with NoneApproximation or the other model used if there is no stokes
+if any(stokesflag), 
+	if any(pattynflag), %fill with pattyn
+		pattynflag(~stokesflag)=1;
+		nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
+	elseif any(macayealflag), %fill with macayeal
+		macayealflag(~stokesflag)=1;
+		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+	else %fill with none 
+		noneflag(find(~stokesflag))=1;
+	end
+end
+
+%Now take care of the coupling between MacAyeal and Pattyn
+md.diagnostic.vertex_pairing=[];
+nodeonmacayealpattyn=zeros(md.mesh.numberofvertices,1);
+nodeonpattynstokes=zeros(md.mesh.numberofvertices,1);
+nodeonmacayealstokes=zeros(md.mesh.numberofvertices,1);
+macayealpattynflag=zeros(md.mesh.numberofelements,1);
+macayealstokesflag=zeros(md.mesh.numberofelements,1);
+pattynstokesflag=zeros(md.mesh.numberofelements,1);
+if strcmpi(coupling_method,'penalties'),
+	%Create the border nodes between Pattyn and MacAyeal and extrude them
+	numnodes2d=md.mesh.numberofvertices2d;
+	numlayers=md.mesh.numberoflayers;
+	bordernodes2d=find(nodeonpattyn(1:numnodes2d) & nodeonmacayeal(1:numnodes2d)); %Nodes connected to two different types of elements
+
+	%initialize and fill in penalties structure
+	if ~isnan(bordernodes2d),
+		penalties=[];
+		for	i=1:numlayers-1,
+			penalties=[penalties; [bordernodes2d bordernodes2d+md.mesh.numberofvertices2d*(i)]];
+		end
+		md.diagnostic.vertex_pairing=penalties;
+	end
+elseif strcmpi(coupling_method,'tiling'),
+	if any(macayealflag) & any(pattynflag), %coupling macayeal pattyn
+		%Find node at the border
+		nodeonmacayealpattyn(find(nodeonmacayeal & nodeonpattyn))=1;
+		%Macayeal elements in contact with this layer become MacAyealPattyn elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonmacayealpattyn));
+		commonelements=sum(matrixelements,2)~=0;
+		commonelements(find(pattynflag))=0; %only one layer: the elements previously in macayeal
+		macayealflag(find(commonelements))=0; %these elements are now macayealpattynelements
+		macayealpattynflag(find(commonelements))=1;
+		nodeonmacayeal(:)=0;
+		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+
+		%rule out elements that don't touch the 2 boundaries
+		pos=find(macayealpattynflag);
+		list=zeros(length(pos),1);
+		list = list + any(sum(nodeonmacayeal(md.mesh.elements(pos,:)),2),2);
+		list = list - any(sum(nodeonpattyn(md.mesh.elements(pos,:))  ,2),2);
+		pos1=find(list==1);
+		macayealflag(pos(pos1))=1;
+		macayealpattynflag(pos(pos1))=0;
+		pos2=find(list==-1);
+		pattynflag(pos(pos2))=1;
+		macayealpattynflag(pos(pos2))=0;
+
+		%Recompute nodes associated to these elements
+		nodeonmacayeal(:)=0;
+		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+		nodeonpattyn(:)=0;
+		nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
+		nodeonmacayealpattyn(:)=0;
+		nodeonmacayealpattyn(md.mesh.elements(find(macayealpattynflag),:))=1;
+
+	elseif any(pattynflag) & any(stokesflag), %coupling pattyn stokes
+		%Find node at the border
+		nodeonpattynstokes(find(nodeonpattyn & nodeonstokes))=1;
+		%Stokes elements in contact with this layer become PattynStokes elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonpattynstokes));
+		commonelements=sum(matrixelements,2)~=0;
+		commonelements(find(pattynflag))=0; %only one layer: the elements previously in macayeal
+		stokesflag(find(commonelements))=0; %these elements are now macayealpattynelements
+		pattynstokesflag(find(commonelements))=1;
+		nodeonstokes=zeros(md.mesh.numberofvertices,1);
+		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+
+		%rule out elements that don't touch the 2 boundaries
+		pos=find(pattynstokesflag);
+		list=zeros(length(pos),1);
+		list = list + any(sum(nodeonstokes(md.mesh.elements(pos,:)),2),2);
+		list = list - any(sum(nodeonpattyn(md.mesh.elements(pos,:)),2),2);
+		pos1=find(list==1);
+		stokesflag(pos(pos1))=1;
+		pattynstokesflag(pos(pos1))=0;
+		pos2=find(list==-1);
+		pattynflag(pos(pos2))=1;
+		pattynstokesflag(pos(pos2))=0;
+
+		%Recompute nodes associated to these elements
+		nodeonstokes(:)=0;
+		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+		nodeonpattyn(:)=0;
+		nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
+		nodeonpattynstokes(:)=0;
+		nodeonpattynstokes(md.mesh.elements(find(pattynstokesflag),:))=1;
+
+	elseif any(stokesflag) & any(macayealflag),
+		%Find node at the border
+		nodeonmacayealstokes(find(nodeonmacayeal & nodeonstokes))=1;
+		%Stokes elements in contact with this layer become MacAyealStokes elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonmacayealstokes));
+		commonelements=sum(matrixelements,2)~=0;
+		commonelements(find(macayealflag))=0; %only one layer: the elements previously in macayeal
+		stokesflag(find(commonelements))=0; %these elements are now macayealmacayealelements
+		macayealstokesflag(find(commonelements))=1;
+		nodeonstokes=zeros(md.mesh.numberofvertices,1);
+		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+
+		%rule out elements that don't touch the 2 boundaries
+		pos=find(macayealstokesflag);
+		list=zeros(length(pos),1);
+		list = list + any(sum(nodeonmacayeal(md.mesh.elements(pos,:)),2),2);
+		list = list - any(sum(nodeonstokes(md.mesh.elements(pos,:))  ,2),2);
+		pos1=find(list==1);
+		macayealflag(pos(pos1))=1;
+		macayealstokesflag(pos(pos1))=0;
+		pos2=find(list==-1);
+		stokesflag(pos(pos2))=1;
+		macayealstokesflag(pos(pos2))=0;
+
+		%Recompute nodes associated to these elements
+		nodeonmacayeal(:)=0;
+		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+		nodeonstokes(:)=0;
+		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+		nodeonmacayealstokes(:)=0;
+		nodeonmacayealstokes(md.mesh.elements(find(macayealstokesflag),:))=1;
+
+	elseif any(stokesflag) & any(hutterflag),
+		error('type of coupling not supported yet');
+	end
+end
+
+%Create MacaAyealPattynApproximation where needed
+md.flowequation.element_equation=zeros(md.mesh.numberofelements,1);
+md.flowequation.element_equation(find(noneflag))=0;
+md.flowequation.element_equation(find(hutterflag))=1;
+md.flowequation.element_equation(find(macayealflag))=2;
+md.flowequation.element_equation(find(pattynflag))=3;
+md.flowequation.element_equation(find(stokesflag))=4;
+md.flowequation.element_equation(find(macayealpattynflag))=5;
+md.flowequation.element_equation(find(macayealstokesflag))=6;
+md.flowequation.element_equation(find(pattynstokesflag))=7;
+
+%border
+md.flowequation.borderpattyn=nodeonpattyn;
+md.flowequation.bordermacayeal=nodeonmacayeal;
+md.flowequation.borderstokes=nodeonstokes;
+
+%Create vertices_type
+md.flowequation.vertex_equation=zeros(md.mesh.numberofvertices,1);
+pos=find(nodeonhutter);
+md.flowequation.vertex_equation(pos)=1;
+pos=find(nodeonmacayeal);
+md.flowequation.vertex_equation(pos)=2;
+pos=find(nodeonpattyn);
+md.flowequation.vertex_equation(pos)=3;
+pos=find(nodeonhutter);
+md.flowequation.vertex_equation(pos)=1;
+pos=find(nodeonmacayealpattyn);
+md.flowequation.vertex_equation(pos)=5;
+pos=find(nodeonstokes);
+md.flowequation.vertex_equation(pos)=4;
+if any(stokesflag),
+	pos=find(~nodeonstokes);
+	if(~any(pattynflag) & ~any(macayealflag)),
+		md.flowequation.vertex_equation(pos)=0;
+	end
+end
+pos=find(nodeonpattynstokes);
+md.flowequation.vertex_equation(pos)=7;
+pos=find(nodeonmacayealstokes);
+md.flowequation.vertex_equation(pos)=6;
+
+%figure out solution types
+md.flowequation.ishutter=double(any(md.flowequation.element_equation==1));
+md.flowequation.ismacayealpattyn=double(any(md.flowequation.element_equation==2 | md.flowequation.element_equation==3));
+md.flowequation.isstokes=double(any(md.flowequation.element_equation==4));
+
+return
+
+%Check that tiling can work:
+if any(md.flowequation.bordermacayeal) & any(md.flowequation.borderpattyn) & any(md.flowequation.borderpattyn + md.flowequation.bordermacayeal ~=1),
+	error('error coupling domain too irregular');
+end
+if any(md.flowequation.bordermacayeal) & any(md.flowequation.borderstokes) & any(md.flowequation.borderstokes + md.flowequation.bordermacayeal ~=1),
+	error('error coupling domain too irregular');
+end
+if any(md.flowequation.borderstokes) & any(md.flowequation.borderpattyn) & any(md.flowequation.borderpattyn + md.flowequation.borderstokes~=1),
+	error('error coupling domain too irregular');
+end
Index: /issm/trunk-jpl-damage/src/m/model/setmask.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/setmask.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/setmask.m	(revision 11330)
@@ -0,0 +1,49 @@
+function md=setmask(md,floatingicename,groundedicename)
+%SETMASK - establish boundaries between grounded and floating ice.
+%
+%   By default, ice is considered grounded. The contour floatingicename defines nodes 
+%   for which ice is floating. The contour groundedicename defines nodes inside an floatingice, 
+%   that are grounded (ie: ice rises, islands, etc ...)
+%   All input files are in the Argus format (extension .exp).
+%
+%   Usage:
+%      md=setmask(md,floatingicename,groundedicename)
+%
+%   Examples:
+%      md=setmask(md,'all','');
+%      md=setmask(md,'Iceshelves.exp','Islands.exp');
+
+%some checks on list of arguments
+if ((nargin~=3) | (nargout~=1)),
+	help mask
+	error('mask error message');
+end
+
+%Get assigned fields
+x=md.mesh.x;
+y=md.mesh.y;
+elements=md.mesh.elements;
+
+%Assign elementonfloatingice, elementongroundedice, vertexongroundedice and vertexonfloatingice. Only change at your own peril! This is synchronized heavily with the GroundingLineMigration module. {{{1
+elementonfloatingice=FlagElements(md,floatingicename);
+elementongroundedice=FlagElements(md,groundedicename);
+
+%Because groundedice nodes and elements can be included into an floatingice, we need to update. Remember, all the previous 
+%arrays come from domain outlines that can intersect one another: 
+elementonfloatingice=double((elementonfloatingice & ~elementongroundedice));
+elementongroundedice=double(~elementonfloatingice);
+
+%the order here is important. we choose vertexongroundedice as default on the grounding line.
+vertexonfloatingice=zeros(md.mesh.numberofvertices,1);
+vertexongroundedice=zeros(md.mesh.numberofvertices,1);
+vertexongroundedice(md.mesh.elements(find(elementongroundedice),:))=1;
+vertexonfloatingice(find(~vertexongroundedice))=1;
+%}}}
+
+%Return: 
+md.mask.elementonfloatingice=elementonfloatingice;
+md.mask.vertexonfloatingice=vertexonfloatingice;
+md.mask.elementongroundedice=elementongroundedice;
+md.mask.vertexongroundedice=vertexongroundedice;
+md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+md.mask.elementonwater=zeros(md.mesh.numberofelements,1);
Index: /issm/trunk-jpl-damage/src/m/model/setmask2.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/setmask2.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/setmask2.m	(revision 11330)
@@ -0,0 +1,148 @@
+function md=setmask2(md,landname,floatingicename,groundedicename)
+%GEOGRAPHY2 - establish land, ice sheet and ice shelf areas in a domains.
+%
+%   Usage:
+%      md=setmask2(md,landname,floatingicename,groundedicename)
+%
+%   Examples:
+%      md=setmask2(md,'LandName.exp','Iceshelves.exp','Islands.exp');
+
+%Get assigned fields
+x=md.mesh.x;
+y=md.mesh.y;
+elements=md.mesh.elements;
+
+%recover elements and nodes on land.
+if ischar(landname),
+	[vertexonland,elementonland]=ContourToMesh(elements,x,y,landname,'element and node',2);
+elseif isfloat(landname),
+	if size(landname,1)~=md.mesh.numberofelements,
+		error('Landname for area must be of same size as number of elements in model');
+	end
+	elementonland=landname;
+	vertexonland=zeros(md.mesh.numberofvertices,1);
+	vertexonland(md.mesh.elements(find(elementonland),:))=1;
+else
+	error('Invalid area option option');
+end
+
+%Now, build the connectivity tables for this mesh.
+if size(md.mesh.vertexconnectivity,1)~=md.mesh.numberofvertices,
+	md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+end
+if size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements,
+	md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+end
+
+%any element with 3 nodes on land should be on land:
+elementsonwater=find(~elementonland);
+wrongelements=elementsonwater(find(( vertexonland(md.mesh.elements(elementsonwater,1)) + vertexonland(md.mesh.elements(elementsonwater,2)) + vertexonland(md.mesh.elements(elementsonwater,3)) ...
+                  )==3));
+elementonland(wrongelements)=1;
+
+%any element with its barycentre on land should be on land: (only if landname is an expfile)
+if ischar(landname),
+weights={[1;1;1],[2;1;1],[1;2;1],[1;1;2]};
+	for i=1:length(weights),
+		xelem=x(md.mesh.elements)*weights{i}/sum(weights{i});
+		yelem=y(md.mesh.elements)*weights{i}/sum(weights{i});
+	end
+	baryonland=ContourToNodes(xelem,yelem,landname,1);
+	pos=find(~baryonland); elementonland(pos)=0;
+	pos=find(baryonland); elementonland(pos)=1;
+end
+
+%figure out which elements on land are actually in the middle of the ocean!
+pos1=find(elementonland); 
+connectedtoland=md.mesh.elementconnectivity(pos1,:);
+pos=find(connectedtoland); connectedtoland(pos)=1-elementonland(connectedtoland(pos));
+connectedtolandsum=sum(connectedtoland,2);
+waterelements=pos1(find(connectedtolandsum==3));
+elementonland(waterelements)=0;
+
+%figure out which elements on water  are actually in the middle of the land!
+pos1=find(~elementonland); 
+connectedtowater=md.mesh.elementconnectivity(pos1,:);
+pos=find(connectedtowater); connectedtowater(pos)=elementonland(connectedtowater(pos));
+connectedtowatersum=sum(connectedtowater,2);
+landelements=pos1(find(connectedtowatersum==3));
+elementonland(landelements)=1;
+
+%recover arrays of ice shelf nodes and elements, and ice sheet nodes and elements.
+elementonfloatingice=FlagElements(md,floatingicename);
+elementongroundedice=FlagElements(md,groundedicename);
+
+%Because groundedice nodes and elements can be included into an floatingice, we need to update. Remember, all the previous 
+%arrays come from domain outlines that can intersect one another: 
+vertexonfloatingice=zeros(md.mesh.numberofvertices,1);
+vertexongroundedice=zeros(md.mesh.numberofvertices,1);
+elementonfloatingice=double((elementonfloatingice & ~elementongroundedice));
+elementongroundedice=double(~elementonfloatingice);
+vertexonfloatingice(md.mesh.elements(find(elementonfloatingice),:))=1;
+vertexongroundedice(md.mesh.elements(find(elementongroundedice),:))=1;
+
+%now correct, so that none of the floatingice and groundedice elements and nodes are in the water.
+pos=find(~elementonland);
+elementonfloatingice(pos)=0; 
+elementongroundedice(pos)=0;
+
+pos=find(~vertexonland);
+vertexonfloatingice(pos)=0; 
+vertexongroundedice(pos)=0;
+
+%create vertexonwater and elementonwater: 
+vertexonwater=double(~vertexonland);
+elementonwater=double(~elementonland);
+
+%correct for islands:
+vertexonfloatingice=double(vertexonfloatingice & ~vertexongroundedice);
+elementonfloatingice=double(elementonfloatingice & ~elementongroundedice);
+
+%now, groundedices are everything except iceshelves and water
+vertexongroundedice=double(~vertexonfloatingice & ~vertexonwater);
+elementongroundedice=double(~elementonfloatingice & ~elementonwater);
+
+%Deal with segments on neumann:
+
+%Get current connectivity
+mesh.elementconnectivity=md.mesh.elementconnectivity;
+
+%put 0 for elements on water
+pos=find(mesh.elementconnectivity);
+mesh.elementconnectivity(pos)=mesh.elementconnectivity(pos).*(~elementonwater(mesh.elementconnectivity(pos)));
+
+%put line of ones for elements on water
+pos=find(elementonwater);
+mesh.elementconnectivity(pos,:)=1;% line of ones for elements on water so they won't be considered
+
+%resort lines (zeros must be at the last column for findsegments)
+mesh.elementconnectivity=sort(mesh.elementconnectivity,2,'descend');
+
+%call findsegments to build segment using THIS conectivity
+md.mesh.segments=findsegments(md,'mesh.elementconnectivity',mesh.elementconnectivity);
+
+%some final checks: 
+%check that no node thinks it's on an ice shelf or ice sheet, and lies actually in the middle of the water.
+nodesgrounded=find(~vertexonwater);
+lengthconnectivity=size(md.mesh.vertexconnectivity,2);
+groundedcounters=md.mesh.vertexconnectivity(nodesgrounded,lengthconnectivity);
+groundedconnectivity=md.mesh.vertexconnectivity(nodesgrounded,1:lengthconnectivity-1);
+pos=find(groundedconnectivity);
+groundedconnectivity(pos)=elementonwater(groundedconnectivity(pos));
+groundedsum=sum(groundedconnectivity,2);
+errorflags=find(groundedsum==groundedcounters);
+errornodes=nodesgrounded(errorflags);
+
+vertexonwater(errornodes)=1;
+vertexongroundedice(errornodes)=0;
+vertexonfloatingice(errornodes)=0;
+
+%Return: 
+md.mask.vertexonfloatingice=vertexonfloatingice;
+md.mask.elementonfloatingice=elementonfloatingice;
+md.mask.vertexonwater=vertexonwater;
+md.mask.elementonwater=elementonwater;
+md.mask.vertexongroundedice=vertexongroundedice;
+md.mask.elementongroundedice=elementongroundedice;
+
+md.mesh.segmentmarkers(:)=1;
Index: /issm/trunk-jpl-damage/src/m/model/shear2d.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/shear2d.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/shear2d.m	(revision 11330)
@@ -0,0 +1,23 @@
+function [sx,sy,sxy,s]=shear2d(md)
+%SHEAR2D - computes 2d strain rate
+%
+%   This routine computes the strain rate of 2d models
+%
+%   Usage:
+%      [sx,sy,sxy,s]=shear2d(md);
+%      s=shear2d(md);
+
+[alpha beta]=GetNodalFunctionsCoeff(md.mesh.elements,md.mesh.x,md.mesh.y); 
+
+summation=[1;1;1];
+sx=(md.initialization.vx(md.mesh.elements).*alpha)*summation;
+uy=(md.initialization.vx(md.mesh.elements).*beta)*summation;
+vx=(md.initialization.vy(md.mesh.elements).*alpha)*summation;
+sy=(md.initialization.vy(md.mesh.elements).*beta)*summation;						
+sxy=(uy+vx)/2;
+s=sqrt(sx.^2+sy.^2+sxy.^2+sx.*sy);
+
+%if user requested only one output, it must be the norm
+if nargout==1,
+	sx=s;
+end
Index: /issm/trunk-jpl-damage/src/m/model/sia.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/sia.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/sia.m	(revision 11330)
@@ -0,0 +1,26 @@
+function [velx,vely,vel]=sia(md)
+%BALVEL - computation of Shallow Ice velocities
+%
+%   This routine uses the model of Hutter to compute the velocities
+%   of a 2d model using the surface slope
+%
+%   Usage:
+%      [velx,vely,vel]=sia(md)
+
+if md.mesh.dimension~=2,
+	error('Only 2d meshes are allowed to compute velocity balances');
+end
+
+%Get slope
+[sx,sy,s]=slope(md);
+
+%Average thickness and B over all elements.
+summer=[1;1;1];
+hel=md.geometry.thickness(md.mesh.elements)*summer/3;
+Bel=md.B(md.mesh.elements)*summer/3;
+
+Ael=Bel.^(-3);
+
+velx=-2*(md.materials.rho_ice*md.constants.g)^3*s.^2.*sx.*Ael/4.*hel.^4;
+vely=-2*(md.materials.rho_ice*md.constants.g)^3*s.^2.*sy.*Ael/4.*hel.^4;
+vel=sqrt(velx.^2+vely.^2);
Index: /issm/trunk-jpl-damage/src/m/model/slope.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/slope.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/slope.m	(revision 11330)
@@ -0,0 +1,32 @@
+function [sx,sy,s]=slope(md)
+%SLOPE - compute the surface slope
+%
+%   Usage:
+%      [sx,sy,s]=slope(md)
+
+%load some variables (it is much faster if the variab;es are loaded from md once for all) 
+if (md.mesh.dimension==2),
+	numberofelements=md.mesh.numberofelements;
+	numberofnodes=md.mesh.numberofvertices;
+	index=md.mesh.elements;
+	x=md.mesh.x; y=md.mesh.y;
+else
+	numberofelements=md.mesh.numberofelements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	index=md.mesh.elements2d;
+	x=md.mesh.x2d; y=md.mesh.y2d;
+end
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+
+summation=[1;1;1];
+sx=(md.geometry.surface(index).*alpha)*summation;
+sy=(md.geometry.surface(index).*beta)*summation;
+s=sqrt(sx.^2+sy.^2);
+
+if md.mesh.dimension==3,
+	sx=project3d(md,sx,'element');
+	sy=project3d(md,sy,'element');
+	s=sqrt(sx.^2+sy.^2);
+end
Index: /issm/trunk-jpl-damage/src/m/model/solve.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/solve.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/solve.m	(revision 11330)
@@ -0,0 +1,90 @@
+function md=solve(md,solutionenum,varargin)
+%SOLVE - apply solution sequence for this model
+%
+%   Usage:
+%      md=solve(md,solutionenum,varargin)
+%      where varargin is a lit of paired arguments of string OR enums
+%
+%   solution types available comprise:
+%		 - DiagnosticSolutionEnum
+%		 - PrognosticSolutionEnum
+%		 - ThermalSolutionEnum
+%		 - SteadystateSolutionEnum
+%		 - TransientSolutionEnum...
+%		 - BalancethicknessSolutionEnum
+%		 - BedSlopeSolutionEnum
+%		 - SurfaceSlopeSolutionEnum
+%		 - HydrologySolutionEnum
+%		 - FlaimSolutionEnum
+%
+%  extra options:
+%      - loadonly : does not solve. only load results
+%
+%   Examples:
+%      md=solve(md,DiagnosticSolutionEnum);
+
+%recover options
+options=pairoptions(varargin{:},'solution_type',solutionenum);
+
+%add default options
+options=process_solve_options(options);
+
+%recover some fields
+md.private.solution=options.solution_type;
+
+%check model consistency
+disp('checking model consistency');
+if (solutionenum == FlaimSolutionEnum)
+	modelconsistency(true);
+	md.mesh.checkconsistency(md,solutionenum);
+	md.flaim.checkconsistency(md,solutionenum);
+	if ~modelconsistency()
+		error(' ');
+	end
+else
+	ismodelselfconsistent(md),
+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
+
+%Save model as is (in case of a crash)
+assignin('base',inputname(1),md);
+
+%flaim analysis
+if (md.private.solution == FlaimSolutionEnum)
+	md=flaim_sol(md,options);
+	md.private.solution=EnumToString(options.solution_type);
+	return;
+end
+
+%Marshall model data into a binary file.
+marshall(md);
+
+%write a template file for issm to use, in parallel
+PetscFile(md.solver,[md.miscellaneous.name '.petsc']);
+
+%If running in parallel, we have a different way of launching the solution
+%sequences. 
+if ~strcmpi(md.cluster.name,'none'),
+	md=solveparallel(md,options);
+	return;
+end
+
+%Launch correct solution sequence
+md=issm(md,md.private.solution);
+
+%post processes qmu results if necessary
+if md.qmu.isdakota,
+	md=postqmu(md);
+	cd ..
+	if ~strncmpi(options.keep,'y',1)
+		system(['rm -rf qmu' num2str(feature('GetPid'))]);
+	end
+end
+
+%convert analysis type to string finally
+md.private.solution=EnumToString(options.solution_type);
Index: /issm/trunk-jpl-damage/src/m/model/solveparallel.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/solveparallel.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/solveparallel.m	(revision 11330)
@@ -0,0 +1,52 @@
+function md=solveparallel(md,options)
+%SOLVEPARALLEL - solution sequence using a cluster in parallel mode
+%
+%   Usage:
+%      md=solveparallel(md);
+
+%retrieve cluster: otherwise, we can't call its methods (subsref bug)
+cluster=md.cluster;
+
+if options.loadonly,  
+	md=loadresultsfromcluster(md);
+else
+
+	%First, build a runtime name that is unique, that we will use to create 
+	%directories, name jobs, etc ...
+	c=clock; md.private.runtimename=sprintf('%s-%i-%i-%i-%i-%i-%i-%i',md.miscellaneous.name,c(2),c(3),c(1),c(4),c(5),floor(c(6)),feature('GetPid'));
+
+	if verLessThan('matlab', '7.6')
+		BuildQueueScript(cluster,md);
+		LaunchQueueJob(cluster,md,options);
+	else
+		cluster.BuildQueueScript(md);
+		cluster.LaunchQueueJob(md,options);
+	end
+
+	if ~strcmpi(options.upload,'on'), %did we even try to run? if so, wait on lock
+
+		%Do we return, or just wait for results?
+		if (md.settings.waitonlock>0 &  ~strcmpi(options.batch,'yes')),
+			%we wait for the done file
+			islock=waitonlock(md);
+			if islock==0,
+				%no results to be loaded
+				disp('The results must be loaded manually with md=loadresultsfromcluster(md).');
+			else
+				%load results
+				disp('loading results from cluster');
+				md=loadresultsfromcluster(md);
+			end
+		end
+
+		%post processes qmu results if necessary
+		if md.qmu.isdakota,
+			if ~strncmpi(options.keep,'y',1)
+				system(['rm -rf qmu' num2str(feature('GetPid'))]);
+			end
+		end
+	else
+		error('solveparallel done uploading test decks');
+	end
+
+end
Index: /issm/trunk-jpl-damage/src/m/model/solvers/asmoptions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/solvers/asmoptions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/solvers/asmoptions.m	(revision 11330)
@@ -0,0 +1,31 @@
+function options=asmoptions(varargin)
+%ASMOPTIONS - return Additive Shwartz Method petsc options
+%
+%   Usage:
+%      options=asmoptions;
+			 
+%retrieve options provided in varargin
+arguments=pairoptions(varargin{:});
+
+%default asm options
+options={{'mat_type','aij'},{'ksp_type','gmres'},{'pc_type','asm'},{'sub_pc_type','lu'},{'pc_asm_overlap',3},{'ksp_max_it',100},{'ksp_rtol',1e-30'}};
+
+%now, go through our arguments, and write over default options.
+for i=1:size(arguments.list,1),
+	arg1=arguments.list{i,1};
+	arg2=arguments.list{i,2};
+	found=0;
+	for j=1:size(options,2),
+		joption=options{j};
+		if strcmpi(joption{1},arg1),
+			joption{2}=arg2;
+			options{j}=joption;
+			found=1;
+			break;
+		end
+	end
+	if ~found,
+		%this option did not exist, add it: 
+		options{end+1}={arg1,arg2};
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/solvers/iluasmoptions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/solvers/iluasmoptions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/solvers/iluasmoptions.m	(revision 11330)
@@ -0,0 +1,31 @@
+function options=iluasmoptions(varargin)
+%ASMOPTIONS - return Additive Shwartz Method with ILU preconditioner petsc options
+%
+%   Usage:
+%      options=iluasmoptions;
+			 
+%retrieve options provided in varargin
+arguments=pairoptions(varargin{:});
+
+%default iluasm options
+options={{'mat_type','aij'},{'ksp_type','gmres'},{'pc_type','asm'},{'sub_pc_type','ilu'},{'pc_asm_overlap',5},{'ksp_max_it',100},{'ksp_rtol',1e-15'}};
+
+%now, go through our arguments, and write over default options.
+for i=1:size(arguments.list,1),
+	arg1=arguments.list{i,1};
+	arg2=arguments.list{i,2};
+	found=0;
+	for j=1:size(options,2),
+		joption=options{j};
+		if strcmpi(joption{1},arg1),
+			joption{2}=arg2;
+			options{j}=joption;
+			found=1;
+			break;
+		end
+	end
+	if ~found,
+		%this option did not exist, add it: 
+		options{end+1}={arg1,arg2};
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/solvers/jacobiasmoptions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/solvers/jacobiasmoptions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/solvers/jacobiasmoptions.m	(revision 11330)
@@ -0,0 +1,31 @@
+function options=jacobiasmoptions(varargin)
+%ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+%
+%   Usage:
+%      options=jacobiasmoptions;
+			 
+%retrieve options provided in varargin
+arguments=pairoptions(varargin{:});
+
+%default jacobiasm options
+options={{'mat_type','aij'},{'ksp_type','gmres'},{'pc_type','asm'},{'sub_pc_type','jacobi'},{'pc_asm_overlap',3},{'ksp_max_it',100},{'ksp_rtol',1e-15'}};
+
+%now, go through our arguments, and write over default options.
+for i=1:size(arguments.list,1),
+	arg1=arguments.list{i,1};
+	arg2=arguments.list{i,2};
+	found=0;
+	for j=1:size(options,2),
+		joption=options{j};
+		if strcmpi(joption{1},arg1),
+			joption{2}=arg2;
+			options{j}=joption;
+			found=1;
+			break;
+		end
+	end
+	if ~found,
+		%this option did not exist, add it: 
+		options{end+1}={arg1,arg2};
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/solvers/jacobicgoptions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/solvers/jacobicgoptions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/solvers/jacobicgoptions.m	(revision 11330)
@@ -0,0 +1,31 @@
+function options=jacobiasmoptions(varargin)
+%ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+%
+%   Usage:
+%      options=jacobiasmoptions;
+			 
+%retrieve options provided in varargin
+arguments=pairoptions(varargin{:});
+
+%default jacobiasm options
+options={{'mat_type','aij'},{'ksp_type','cg'},{'ksp_max_it',100},{'ksp_rtol',1e-15'}};
+
+%now, go through our arguments, and write over default options.
+for i=1:size(arguments.list,1),
+	arg1=arguments.list{i,1};
+	arg2=arguments.list{i,2};
+	found=0;
+	for j=1:size(options,2),
+		joption=options{j};
+		if strcmpi(joption{1},arg1),
+			joption{2}=arg2;
+			options{j}=joption;
+			found=1;
+			break;
+		end
+	end
+	if ~found,
+		%this option did not exist, add it: 
+		options{end+1}={arg1,arg2};
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/solvers/matlaboptions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/solvers/matlaboptions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/solvers/matlaboptions.m	(revision 11330)
@@ -0,0 +1,31 @@
+function options=matlaboptions(varargin)
+%MATLABOPTIONS - return Matlab petsc options
+%
+%   Usage:
+%      options=matlaboptions;
+			 
+%retrieve options provided in varargin
+arguments=pairoptions(varargin{:});
+
+%default matlab options
+options={{'ksp_type','matlab'}};
+
+%now, go through our arguments, and write over default options.
+for i=1:size(arguments.list,1),
+	arg1=arguments.list{i,1};
+	arg2=arguments.list{i,2};
+	found=0;
+	for j=1:size(options,2),
+		joption=options{j};
+		if strcmpi(joption{1},arg1),
+			joption{2}=arg2;
+			options{j}=joption;
+			found=1;
+			break;
+		end
+	end
+	if ~found,
+		%this option did not exist, add it: 
+		options{end+1}={arg1,arg2};
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/solvers/mumpsoptions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/solvers/mumpsoptions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/solvers/mumpsoptions.m	(revision 11330)
@@ -0,0 +1,38 @@
+function options=mumpsoptions(varargin)
+%MUMPSOPTIONS - return MUMPS direct solver  petsc options
+%
+%   Usage:
+%      options=mumpsoptions;
+
+%retrieve options provided in varargin
+arguments=pairoptions(varargin{:});
+
+%default mumps options
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==2,
+	options={{'mat_type','aijmumps'},{'ksp_type','preonly'},{'pc_type','lu'},{'mat_mumps_icntl_14',120},{'pc_factor_shift_positive_definite','true'}};
+end
+if PETSC_VERSION==3,
+	options={{'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'}};
+
+end
+
+%now, go through our arguments, and write over default options.
+for i=1:size(arguments.list,1),
+	arg1=arguments.list{i,1};
+	arg2=arguments.list{i,2};
+	found=0;
+	for j=1:size(options,2),
+		joption=options{j};
+		if strcmpi(joption{1},arg1),
+			joption{2}=arg2;
+			options{j}=joption;
+			found=1;
+			break;
+		end
+	end
+	if ~found,
+		%this option did not exist, add it: 
+		options{end+1}={arg1,arg2};
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/solvers/soroptions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/solvers/soroptions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/solvers/soroptions.m	(revision 11330)
@@ -0,0 +1,31 @@
+function options=soroptions(varargin)
+%SOROPTIONS - return Relaxation Solver petsc options
+%
+%   Usage:
+%      options=soroptions;
+			 
+%retrieve options provided in varargin
+arguments=pairoptions(varargin{:});
+
+%default sor options
+options={{'mat_type','aij'},{'ksp_type','cg'},{'pc_type','sor'},{'pc_sor_omega',1.1},{'pc_sor_its',2}};
+
+%now, go through our arguments, and write over default options.
+for i=1:size(arguments.list,1),
+	arg1=arguments.list{i,1};
+	arg2=arguments.list{i,2};
+	found=0;
+	for j=1:size(options,2),
+		joption=options{j};
+		if strcmpi(joption{1},arg1),
+			joption{2}=arg2;
+			options{j}=joption;
+			found=1;
+			break;
+		end
+	end
+	if ~found,
+		%this option did not exist, add it: 
+		options{end+1}={arg1,arg2};
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/solvers/stokesoptions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/solvers/stokesoptions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/solvers/stokesoptions.m	(revision 11330)
@@ -0,0 +1,39 @@
+function options=stokesoptions(varargin)
+%STOKESOPTIONS - return STOKES multi-physics solver petsc options
+%
+%   Usage:
+%      options=stokesoptions;
+
+%retrieve options provided in varargin
+arguments=pairoptions(varargin{:});
+
+%default stokes options
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==2,
+	error('stokesoptions error message: multi-physics options not supported in Petsc 2');
+end
+if PETSC_VERSION==3,
+	options={{'mat_type','mpiaij'},{'ksp_max_it',1000},{'ksp_type','gmres'},{'pc_type','fieldsplit'},{'pc_field_split_type','schur'},...
+	{'fieldsplit_0_pc_type','hypre'},{'fieldsplit_0_ksp_type','gmres'},{'fieldsplit_0_pc_hypre_type','boomerang'},...
+	{'fieldsplit_1_pc_type','jacobi'},{'fieldsplit_1_ksp_type','preonly'},{'issm_option_solver','stokes'}};
+end
+
+%now, go through our arguments, and write over default options.
+for i=1:size(arguments.list,1),
+	arg1=arguments.list{i,1};
+	arg2=arguments.list{i,2};
+	found=0;
+	for j=1:size(options,2),
+		joption=options{j};
+		if strcmpi(joption{1},arg1),
+			joption{2}=arg2;
+			options{j}=joption;
+			found=1;
+			break;
+		end
+	end
+	if ~found,
+		%this option did not exist, add it: 
+		options{end+1}={arg1,arg2};
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/model/thicknessevolution.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/thicknessevolution.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/thicknessevolution.m	(revision 11330)
@@ -0,0 +1,28 @@
+function dhdt=thicknessevolution(md)
+%THICKNESSEVOLUTION - compute the new thickness of a model after ∆t
+%
+%   This routine compute the new thickness of a model after a time step
+%   according to the following formula:
+%   dh/dt=-div(Hu)
+%
+%   Usage:
+%      dhdt=thicknessevolution(md)
+
+if (length(md.initialization.vx)~=md.mesh.numberofvertices)|(length(md.initialization.vy)~=md.mesh.numberofvertices)
+	error(['thicknessevolution error message: vx and vy should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+
+%load some variables 
+H=md.geometry.thickness;
+vx=md.initialization.vx;
+vy=md.initialization.vy;
+index=md.mesh.elements;
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(md.mesh.elements,md.mesh.x,md.mesh.y); 
+
+%compute dhdt=div(Hu)
+summation=1/3*ones(3,1);
+dhdt=(vx(index)*summation).*sum( H(index).*alpha,2) + (vy(index)*summation).*sum(H(index).*beta,2) ...
+	+ ( H(index)*summation).*sum(vx(index).*alpha,2) + ( H(index)*summation).*sum(vy(index).*beta,2);
+dhdt=-dhdt;
Index: /issm/trunk-jpl-damage/src/m/model/tres.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/tres.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/tres.m	(revision 11330)
@@ -0,0 +1,103 @@
+function md=tres(md,string)
+%TRES - transfer results results to corresponding model fields. 
+%
+%    Usage: md=tres(md,string)
+%
+%    Example: md=tres(md,'diagnostic');
+
+%check number of arguments
+
+if strcmpi(string,'diagnostic'),
+	if md.mesh.dimension==2,
+		if isfield(md.results.DiagnosticSolution,'VxAverage'),
+			md.initialization.vx=PatchToVec(md.results.DiagnosticSolution.VxAverage);
+		else
+			md.initialization.vx=PatchToVec(md.results.DiagnosticSolution.Vx);
+		end
+		if isfield(md.results.DiagnosticSolution,'VyAverage'),
+			md.initialization.vy=PatchToVec(md.results.DiagnosticSolution.VyAverage);
+		else
+			md.initialization.vy=PatchToVec(md.results.DiagnosticSolution.Vy);
+		end
+	else 
+		md.initialization.vx=PatchToVec(md.results.DiagnosticSolution.Vx);
+		md.initialization.vy=PatchToVec(md.results.DiagnosticSolution.Vy);
+		if isfield(md.results.DiagnosticSolution,'Vz'),
+			md.initialization.vz=PatchToVec(md.results.DiagnosticSolution.Vz);
+		else
+			md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+		end
+	end
+	md.initialization.vel=PatchToVec(md.results.DiagnosticSolution.Vel);
+
+	if isfield(md.results.DiagnosticSolution,'Pressure'),
+		md.initialization.pressure=PatchToVec(md.results.DiagnosticSolution.Pressure);
+	end
+	if md.rifts.numrifts,
+		if isfield(md.results.DiagnosticSolution,'riftproperties'),
+			md.rifts.riftproperties=md.results.DiagnosticSolution.riftproperties;
+		end
+	end
+	if md.inversion.iscontrol==1,
+		for control_parameters=md.inversion.control_parameters
+			%Will need to be updated... good luck ;)
+			md.(EnumToModelField(control_parameters))=PatchToVec(md.results.DiagnosticSolution.(EnumToString(control_parameters)));
+		end
+	end
+
+elseif strcmpi(string,'dakota'),
+	md.qmu.results=md.results.dakota;
+
+elseif strcmpi(string,'flaim'),
+	md.flaim.solution=md.results.FlaimSolution.solution;
+	md.flaim.quality =md.results.FlaimSolution.quality;
+
+elseif strcmpi(string,'transient'),
+	results=md.results.TransientSolution;
+	results2.Vel=NaN;
+	count=1;
+	for i=1:length(results),
+		if ~isempty(md.results.TransientSolution(i).Vel),
+			results2(count).Vel=PatchToVec(md.results.TransientSolution(i).Vel);
+			results2(count).Surface=PatchToVec(md.results.TransientSolution(i).Surface);
+			results2(count).Thickness=PatchToVec(md.results.TransientSolution(i).Thickness);
+			results2(count).Bed=PatchToVec(md.results.TransientSolution(i).Bed);
+			results2(count).Vx=PatchToVec(md.results.TransientSolution(i).Vx);
+			results2(count).Vy=PatchToVec(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=PatchToVec(md.results.SteadystateSolution.Vx);
+	md.initialization.vy=PatchToVec(md.results.SteadystateSolution.Vy);
+	if isfield(md.results.SteadystateSolution,'Vz'),
+		md.initialization.vz=PatchToVec(md.results.SteadystateSolution.Vz);
+	end
+
+	md.initialization.vel=PatchToVec(md.results.SteadystateSolution.Vel);
+	md.initialization.pressure=PatchToVec(md.results.SteadystateSolution.Pressure);
+	md.initialization.temperature=PatchToVec(md.results.SteadystateSolution.Temperature);
+	md.basalforcings.melting_rate=PatchToVec(md.results.SteadystateSolution.BasalforcingsMeltingRate);
+
+	if md.inversion.iscontrol==1,
+		for control_parameters=md.inversion.control_parameters
+			md.(EnumToModelField(control_parameters))=PatchToVec(md.results.SteadystateSolution.(EnumToString(control_parameters)));
+		end
+	end
+
+elseif strcmpi(string,'thermal'),
+	md.initialization.temperature=PatchToVec(md.results.ThermalSolution.Temperature);
+	md.basalforcings.melting_rate=PatchToVec(md.results.ThermalSolution.BasalMeltingRate);
+elseif strcmpi(string,'hydrology'),
+	md.initialization.watercolumn=PatchToVec(md.results.HydrologySolution.Watercolumn);
+
+else 
+	error(['tres error message: analysis ' string ' not supported yet!']);
+end
Index: /issm/trunk-jpl-damage/src/m/model/waitonlock.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/model/waitonlock.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/model/waitonlock.m	(revision 11330)
@@ -0,0 +1,58 @@
+function flag=waitonlock(md,executionpath,login,port)
+%WAITONLOCK - wait for a file
+%
+%   This routine will return when a file named 'filename' is written to disk.
+%   If the time limit given in input is exceeded, return 0
+%
+%   Usage:
+%      flag=waitonlock(md,executionpath)
+
+%Get filename (lock file) and options
+executionpath=md.cluster.executionpath;
+cluster=md.cluster.name;
+login=md.cluster.login;
+port=md.cluster.port;
+timelimit=md.settings.waitonlock;
+filename=[executionpath '/' md.private.runtimename '/' md.miscellaneous.name '.lock'];
+
+%waitonlock will work if the lock is on the same machine only: 
+if ~strcmpi(oshostname(),cluster),
+
+	disp('solution launched on remote cluster. log in to detect job completion.');
+	choice=input('Is the job successfully completed? (y/n)','s');
+	if ~strcmp(choice,'y'), 
+		disp('Results not loaded... exiting'); 
+		flag=0;
+	else
+		flag=1;
+	end
+
+%job is running on the same machine
+else
+
+	if ismember('interactive',properties(md.cluster)) & md.cluster.interactive
+		%We are in interactive mode, no need to check for job completion
+		flag=1;
+		return;
+	end
+	%initialize time and file presence test flag
+	time=0; ispresent=0;
+	disp(['waiting for ' filename ' hold on... (Ctrl+C to exit)'])
+
+	%loop till file .lock exist or time is up
+	while (ispresent==0 & time<timelimit)
+		ispresent=exist(filename,'file');
+		pause(1);
+		time=time+1/60;
+	end
+
+	%build output
+	if (time>timelimit),
+		disp('Time limit exceeded. Increase md.settings.waitonlock');
+		disp('The results must be loaded manually with md=loadresultsfromcluster(md).');
+		error(['waitonlock error message: time limit exceeded']);
+		flag=0;
+	else
+		flag=1;
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/planet/mesh_refine_tri4.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/planet/mesh_refine_tri4.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/planet/mesh_refine_tri4.m	(revision 11330)
@@ -0,0 +1,146 @@
+function [ FV ] = mesh_refine_tri4(FV)
+
+% mesh_refine_tri4 - creates 4 triangle from each triangle of a mesh
+%
+% [ FV ] = mesh_refine_tri4( FV )
+%
+% FV.vertices   - mesh vertices (Nx3 matrix)
+% FV.faces      - faces with indices into 3 rows
+%                 of FV.vertices (Mx3 matrix)
+% 
+% For each face, 3 new vertices are created at the 
+% triangle edge midpoints.  Each face is divided into 4
+% faces and returned in FV.
+%
+%        B
+%       /\
+%      /  \
+%    a/____\b       Construct new triangles
+%    /\    /\       [A,a,c]
+%   /  \  /  \      [a,B,b]
+%  /____\/____\     [c,b,C]
+% A	     c	   C    [a,b,c]
+% 
+% It is assumed that the vertices are listed in clockwise order in
+% FV.faces (A,B,C above), as viewed from the outside in a RHS coordinate
+% system.
+% 
+% See also: mesh_refine, sphere_tri, sphere_project
+% 
+
+
+% ---this method is not implemented, but the idea here remains...
+% This can be done until some minimal distance (D) of the mean 
+% distance between vertices of all triangles is achieved.  If
+% no D argument is given, the function refines the mesh once.
+% Alternatively, it could be done until some minimum mean 
+% area of faces is achieved.  As is, it just refines once.
+
+
+% $Revision: 1.1 $ $Date: 2004/11/12 01:32:35 $
+
+% Licence:  GNU GPL, no implied or express warranties
+% History:  05/2002, Darren.Weber_at_radiology.ucsf.edu, created
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+tic;
+fprintf('...refining mesh (tri4)...')
+
+% NOTE
+% The centroid is located one third of the way from each vertex to 
+% the midpoint of the opposite side. Each median divides the triangle 
+% into two equal areas; all the medians together divide it into six 
+% equal parts, and the lines from the median point to the vertices 
+% divide the whole into three equivalent triangles.
+
+% Each input triangle with vertices labelled [A,B,C] as shown
+% below will be turned into four new triangles:
+%
+% Make new midpoints
+% a = (A+B)/2
+% b = (B+C)/2
+% c = (C+A)/2
+%
+%        B
+%       /\
+%      /  \
+%    a/____\b       Construct new triangles
+%    /\    /\       [A,a,c]
+%   /  \  /  \      [a,B,b]
+%  /____\/____\     [c,b,C]
+% A	     c	   C    [a,b,c]
+%
+
+% Initialise a new vertices and faces matrix
+Nvert = size(FV.vertices,1);
+Nface = size(FV.faces,1);
+V2 = zeros(Nface*3,3);
+F2 = zeros(Nface*4,3);
+
+for f = 1:Nface,
+    
+    % Get the triangle vertex indices
+    NA = FV.faces(f,1);
+    NB = FV.faces(f,2);
+    NC = FV.faces(f,3);
+    
+    % Get the triangle vertex coordinates
+    A = FV.vertices(NA,:);
+    B = FV.vertices(NB,:);
+    C = FV.vertices(NC,:);
+    
+    % Now find the midpoints between vertices
+    a = (A + B) ./ 2;
+    b = (B + C) ./ 2;
+    c = (C + A) ./ 2;
+    
+    % Find the length of each median
+    %A2blen = sqrt ( sum( (A - b).^2, 2 ) );
+    %B2clen = sqrt ( sum( (B - c).^2, 2 ) );
+    %C2alen = sqrt ( sum( (C - a).^2, 2 ) );
+    
+    % Store the midpoint vertices, while
+    % checking if midpoint vertex already exists
+    [FV, Na] = mesh_find_vertex(FV,a);
+    [FV, Nb] = mesh_find_vertex(FV,b);
+    [FV, Nc] = mesh_find_vertex(FV,c);
+    
+    % Create new faces with orig vertices plus midpoints
+    F2(f*4-3,:) = [ NA, Na, Nc ];
+    F2(f*4-2,:) = [ Na, NB, Nb ];
+    F2(f*4-1,:) = [ Nc, Nb, NC ];
+    F2(f*4-0,:) = [ Na, Nb, Nc ];
+    
+end
+
+% Replace the faces matrix
+FV.faces = F2;
+
+t=toc; fprintf('done (%5.2f sec)\n',t);
+
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [FV, N] = mesh_find_vertex(FV,vertex)
+
+    Vn = size(FV.vertices,1);
+    Va = repmat(vertex,Vn,1);
+    Vexist = find( FV.vertices(:,1) == Va(:,1) & ...
+                   FV.vertices(:,2) == Va(:,2) & ...
+                   FV.vertices(:,3) == Va(:,3) );
+    if Vexist,
+        if size(Vexist) == [1,1],
+            N = Vexist;
+        else,
+            msg = sprintf('replicated vertices');
+            error(msg);
+        end
+    else
+        FV.vertices(end+1,:) = vertex;
+        N = size(FV.vertices,1);
+    end
+
+return
Index: /issm/trunk-jpl-damage/src/m/planet/planetmixedmesh.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/planet/planetmixedmesh.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/planet/planetmixedmesh.m	(revision 11330)
@@ -0,0 +1,99 @@
+function md=planetmixedmesh(md,radius,angleresol)
+%PLANETMIXEDMESH: build 2d shell mesh
+%
+% Usage: md=planetmixedshell(md,radius,angleresol)
+%
+
+conv=pi/180;
+
+r=radius;
+theta=(0:angleresol:360)';
+theta=theta*conv;
+phi=(0:angleresol:180)';
+phi=phi(2:end-1)*conv;
+
+nphi=length(phi);
+nthetha=length(theta);
+
+x=zeros(nphi*nthetha,1);
+y=zeros(nphi*nthetha,1);
+z=zeros(nphi*nthetha,1);
+
+for i=1:nphi,
+	phii=phi(i);
+	x((i-1)*nthetha+1:i*nthetha)=r.*cos(theta).*sin(phii);
+	y((i-1)*nthetha+1:i*nthetha)=r.*sin(theta).*sin(phii);
+	z((i-1)*nthetha+1:i*nthetha)=r.*cos(phii);
+end
+
+quads=zeros((nthetha-1)*(nphi-1),4);
+
+%build elements
+for i=1:nphi-1,
+	for j=1:nthetha-1,
+		count=(i-1)*(nthetha-1)+j;
+	
+		A=(i-1)*nthetha+j;
+		B=(i-1)*nthetha+j+1;
+		C=(i)*nthetha+j+1;
+		D=(i)*nthetha+j;
+		
+		quads(count,:)=[A B C D];
+	end
+end
+
+%now, add polar elements:
+%first north: phi = 0;
+x=[r.*cos(0).*sin(0);x];
+y=[r.*sin(0).*sin(0);y];
+z=[r.*cos(0);z];
+
+%add 1 to quads: 
+quads=quads+1;
+
+%add tria elements:
+trias=zeros(nthetha-1,4);
+
+for i=1:nthetha-1,
+	A=1;
+	B=i+1;
+	C=i+2;
+	trias(i,:)=[A B C NaN];
+end
+
+quads=[trias;quads];
+
+
+% now add south pole: 
+phii=180*conv;
+x=[x;r.*cos(phii).*sin(phii)];
+y=[y;r.*sin(phii).*sin(phii)];
+z=[z;r.*cos(phii)];
+nods=length(x);
+
+%add tria elements:
+trias=zeros(nthetha-1,4);
+
+start=nods-nthetha;
+for i=1:nthetha-1,
+	A=start+i-1;
+	B=start+i;
+	C=nods;
+	trias(i,:)=[A B C NaN];
+end
+
+quads=[quads;trias];
+
+
+md.mesh.elements=quads;
+md.x=x;
+md.y=y;
+md.z=z;
+md.r=sqrt(x.^2+y.^2+z.^2);
+md.theta=acos(z./r);
+md.phi=atan2(y,x);
+
+md.mesh.numberofvertices=length(md.x);
+md.mesh.numberofelements=size(md.mesh.elements,1);
+
+md.mesh.dimension=3;
Index: /issm/trunk-jpl-damage/src/m/planet/planettrimesh.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/planet/planettrimesh.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/planet/planettrimesh.m	(revision 11330)
@@ -0,0 +1,20 @@
+function md=planettrimesh(md,shape,radius,refinement)
+%PLANETTRIMESH: build 2d shell mesh
+%
+% Usage: md=planettrimesh(md,shape,radius,refinement)
+%
+
+results = sphere_tri(shape,refinement,radius);
+md.x=results.vertices(:,1);
+md.y=results.vertices(:,2);
+md.z=results.vertices(:,3);
+md.mesh.elements=results.faces;
+
+md.r=sqrt(md.x.^2+md.y.^2+md.z.^2);
+md.theta=acos(md.z./md.r);
+md.phi=atan2(md.y,md.x);
+
+md.mesh.numberofvertices=length(md.x);
+md.mesh.numberofelements=size(md.mesh.elements,1);
+
+md.mesh.dimension=3;
Index: /issm/trunk-jpl-damage/src/m/planet/runme.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/planet/runme.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/planet/runme.m	(revision 11330)
@@ -0,0 +1,4 @@
+% 5 -> level of refinment
+% 1000 -> radius
+FV = sphere_tri('ico',5,1000); 
+patch('vertices',FV.vertices,'faces',FV.faces,'facecolor',[1 0 0],'edgecolor',[.2 .2 .6]);
Index: /issm/trunk-jpl-damage/src/m/planet/sphere_project.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/planet/sphere_project.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/planet/sphere_project.m	(revision 11330)
@@ -0,0 +1,66 @@
+function V = sphere_project(v,r,c)
+
+% sphere_project - project point X,Y,Z to the surface of sphere radius r
+% 
+% V = sphere_project(v,r,c)
+% 
+% Cartesian inputs:
+% v is the vertex matrix, Nx3 (XYZ)
+% r is the sphere radius, 1x1 (default 1)
+% c is the sphere centroid, 1x3 (default 0,0,0)
+%
+% XYZ are converted to spherical coordinates and their radius is
+% adjusted according to r, from c toward XYZ (defined with theta,phi)
+% 
+% V is returned as Cartesian 3D coordinates
+% 
+
+% $Revision: 1.1 $ $Date: 2004/11/12 01:32:36 $
+
+% Licence:  GNU GPL, no implied or express warranties
+% History:  06/2002, Darren.Weber_at_radiology.ucsf.edu, created
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if ~exist('v','var'),
+    msg = sprintf('SPHERE_PROJECT: No input vertices (X,Y,Z)\n');
+    error(msg);
+end
+
+X = v(:,1);
+Y = v(:,2);
+Z = v(:,3);
+
+if ~exist('c','var'),
+    xo = 0;
+    yo = 0;
+    zo = 0;
+else
+    xo = c(1);
+    yo = c(2);
+    zo = c(3);
+end
+
+if ~exist('r','var'), r = 1; end
+
+% alternate method is to use unit vector of V
+% [ n = 'magnitude(V)'; unitV = V ./ n; ]
+% to change the radius, multiply the unitV
+% by the radius required.  This avoids the
+% use of arctan functions, which have branches.
+
+
+% Convert Cartesian X,Y,Z to spherical (radians)
+theta = atan2( (Y-yo), (X-xo) );
+phi   = atan2( sqrt( (X-xo).^2 + (Y-yo).^2 ), (Z-zo) );
+% do not calc: r = sqrt( (X-xo).^2 + (Y-yo).^2 + (Z-zo).^2);
+
+%   Recalculate X,Y,Z for constant r, given theta & phi.
+R = ones(size(phi)) * r;
+x = R .* sin(phi) .* cos(theta);
+y = R .* sin(phi) .* sin(theta);
+z = R .* cos(phi);
+
+V = [x y z];
+
+return
Index: /issm/trunk-jpl-damage/src/m/planet/sphere_tri.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/planet/sphere_tri.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/planet/sphere_tri.m	(revision 11330)
@@ -0,0 +1,204 @@
+function [FV] = sphere_tri(shape,maxlevel,r,winding)
+
+% sphere_tri - generate a triangle mesh approximating a sphere
+% 
+% Usage: FV = sphere_tri(shape,Nrecurse,r,winding)
+% 
+%   shape is a string, either of the following:
+%   'ico'   starts with icosahedron (most even, default)
+%   'oct'   starts with octahedron
+%   'tetra' starts with tetrahedron (least even)
+%
+%   Nrecurse is int >= 0, setting the recursions (default 0)
+%
+%   r is the radius of the sphere (default 1)
+%
+%   winding is 0 for clockwise, 1 for counterclockwise (default 0).  The
+%   matlab patch command gives outward surface normals for clockwise
+%   order of vertices in the faces (viewed from outside the surface).
+%
+%   FV has fields FV.vertices and FV.faces.  The vertices 
+%   are listed in clockwise order in FV.faces, as viewed 
+%   from the outside in a RHS coordinate system.
+% 
+% The function uses recursive subdivision.  The first
+% approximation is an platonic solid, either an  icosahedron,
+% octahedron or a tetrahedron.  Each level of refinement 
+% subdivides each triangle face by a factor of 4 (see also 
+% mesh_refine).  At each refinement, the vertices are 
+% projected to the sphere surface (see sphere_project).
+% 
+% A recursion level of 3 or 4 is a good sphere surface, if
+% gouraud shading is used for rendering.
+% 
+% The returned struct can be used in the patch command, eg:
+% 
+% % create and plot, vertices: [2562x3] and faces: [5120x3]
+% FV = sphere_tri('ico',4,1);
+% lighting phong; shading interp; figure;
+% patch('vertices',FV.vertices,'faces',FV.faces,...
+%       'facecolor',[1 0 0],'edgecolor',[.2 .2 .6]);
+% axis off; camlight infinite; camproj('perspective');
+% 
+% See also: mesh_refine, sphere_project
+%
+
+
+
+% $Revision: 1.2 $ $Date: 2005/07/20 23:07:03 $
+
+% Licence:  GNU GPL, no implied or express warranties
+% Jon Leech (leech @ cs.unc.edu) 3/24/89
+% icosahedral code added by Jim Buddenhagen (jb1556@daditz.sbc.com) 5/93
+% 06/2002, adapted from c to matlab by Darren.Weber_at_radiology.ucsf.edu
+% 05/2004, reorder of the faces for the 'ico' surface so they are indeed
+% clockwise!  Now the surface normals are directed outward.  Also reset the
+% default recursions to zero, so we can get out just the platonic solids.
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+eegversion = '$Revision: 1.2 $';
+fprintf('SPHERE_TRI [v %s]\n',eegversion(11:15)); tic
+
+if ~exist('shape','var') || isempty(shape),
+    shape = 'ico';
+end
+fprintf('...creating sphere tesselation based on %s\n',shape);
+
+% default maximum subdivision level
+if ~exist('maxlevel','var') || isempty(maxlevel) || maxlevel < 0,
+    maxlevel = 0;
+end
+
+% default radius
+if ~exist('r','var') || isempty(r),
+    r = 1;
+end
+
+if ~exist('winding','var') || isempty(winding),
+    winding = 0;
+end
+
+
+% -----------------
+% define the starting shapes
+
+shape = lower(shape);
+
+switch shape,
+case 'tetra',
+    
+    % Vertices of a tetrahedron
+    sqrt_3 = 0.5773502692;
+    
+    tetra.v = [  sqrt_3,  sqrt_3,  sqrt_3 ;   % +X, +Y, +Z  - PPP
+                -sqrt_3, -sqrt_3,  sqrt_3 ;   % -X, -Y, +Z  - MMP
+                -sqrt_3,  sqrt_3, -sqrt_3 ;   % -X, +Y, -Z  - MPM
+                 sqrt_3, -sqrt_3, -sqrt_3 ];  % +X, -Y, -Z  - PMM
+	
+    % Structure describing a tetrahedron
+    tetra.f = [ 1, 2, 3;
+                1, 4, 2;
+                3, 2, 4;
+                4, 1, 3 ];
+    
+    FV.vertices = tetra.v;
+    FV.faces    = tetra.f;
+    
+case 'oct',
+    
+    % Six equidistant points lying on the unit sphere
+    oct.v = [  1,  0,  0 ;  %  X
+              -1,  0,  0 ; 	% -X
+               0,  1,  0 ;  %  Y
+               0, -1,  0 ; 	% -Y
+               0,  0,  1 ; 	%  Z
+               0,  0, -1 ];	% -Z
+	
+    % Join vertices to create a unit octahedron
+    oct.f = [ 1 5 3 ;    %  X  Z  Y  -  First the top half
+              3 5 2 ;    %  Y  Z -X
+              2 5 4 ;    % -X  Z -Y
+              4 5 1 ;    % -Y  Z  X
+              1 3 6 ;    %  X  Y -Z  -  Now the bottom half
+              3 2 6 ;    %  Y  Z -Z
+              2 4 6 ;    % -X  Z -Z
+              4 1 6 ];   % -Y  Z -Z
+    
+    FV.vertices = oct.v;
+    FV.faces    = oct.f;
+    
+case 'ico',
+    
+    % Twelve vertices of icosahedron on unit sphere
+    tau = 0.8506508084; % t=(1+sqrt(5))/2, tau=t/sqrt(1+t^2)
+    one = 0.5257311121; % one=1/sqrt(1+t^2) , unit sphere
+    
+    ico.v( 1,:) = [  tau,  one,    0 ]; % ZA
+    ico.v( 2,:) = [ -tau,  one,    0 ]; % ZB
+    ico.v( 3,:) = [ -tau, -one,    0 ]; % ZC
+    ico.v( 4,:) = [  tau, -one,    0 ]; % ZD
+    ico.v( 5,:) = [  one,   0 ,  tau ]; % YA
+    ico.v( 6,:) = [  one,   0 , -tau ]; % YB
+    ico.v( 7,:) = [ -one,   0 , -tau ]; % YC
+    ico.v( 8,:) = [ -one,   0 ,  tau ]; % YD
+    ico.v( 9,:) = [   0 ,  tau,  one ]; % XA
+    ico.v(10,:) = [   0 , -tau,  one ]; % XB
+    ico.v(11,:) = [   0 , -tau, -one ]; % XC
+    ico.v(12,:) = [   0 ,  tau, -one ]; % XD
+    
+    % Structure for unit icosahedron
+    ico.f = [  5,  8,  9 ;
+               5, 10,  8 ;
+               6, 12,  7 ;
+               6,  7, 11 ;
+               1,  4,  5 ;
+               1,  6,  4 ;
+               3,  2,  8 ;
+               3,  7,  2 ;
+               9, 12,  1 ;
+               9,  2, 12 ;
+              10,  4, 11 ;
+              10, 11,  3 ;
+               9,  1,  5 ;
+              12,  6,  1 ;
+               5,  4, 10 ;
+               6, 11,  4 ;
+               8,  2,  9 ;
+               7, 12,  2 ;
+               8, 10,  3 ;
+               7,  3, 11 ];
+	
+    FV.vertices = ico.v;
+    FV.faces    = ico.f;
+end
+
+
+% -----------------
+% refine the starting shapes with subdivisions
+if maxlevel,
+    
+    % Subdivide each starting triangle (maxlevel) times
+    for level = 1:maxlevel,
+        
+        % Subdivide each triangle and normalize the new points thus
+        % generated to lie on the surface of a sphere radius r.
+        FV = mesh_refine_tri4(FV);
+        FV.vertices = sphere_project(FV.vertices,r);
+        
+        % An alternative might be to define a min distance
+        % between vertices and recurse or use fminsearch
+        
+    end
+end
+
+if winding,
+    fprintf('...returning counterclockwise vertex order (viewed from outside)\n');
+    FV.faces = FV.faces(:,[1 3 2]);
+else
+    fprintf('...returning clockwise vertex order (viewed from outside)\n');
+end
+
+t=toc; fprintf('...done (%6.2f sec)\n\n',t);
+
+return
Index: /issm/trunk-jpl-damage/src/m/qmu/MassFluxProcessProfile.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/MassFluxProcessProfile.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/MassFluxProcessProfile.m	(revision 11330)
@@ -0,0 +1,14 @@
+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/trunk-jpl-damage/src/m/qmu/dakota_cdfs.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/dakota_cdfs.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/dakota_cdfs.m	(revision 11330)
@@ -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(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(prob(i),mu,sigma);
+        cdf(irow,2)=prob(i);
+        cdf(irow,3)=-norminv(prob(i),0,1);
+        cdf(irow,4)=-norminv(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(-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(-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/trunk-jpl-damage/src/m/qmu/dakota_in_data.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/dakota_in_data.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/dakota_in_data.m	(revision 11330)
@@ -0,0 +1,123 @@
+%
+%  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,versn] = fileparts(filei);
+    params.analysis_components=fullfile(pathstr,[name '.m' versn]);
+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/trunk-jpl-damage/src/m/qmu/dakota_in_params.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/dakota_in_params.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/dakota_in_params.m	(revision 11330)
@@ -0,0 +1,211 @@
+%
+%  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/trunk-jpl-damage/src/m/qmu/dakota_in_parse.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/dakota_in_parse.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/dakota_in_parse.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/dakota_in_write.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/dakota_in_write.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/dakota_in_write.m	(revision 11330)
@@ -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,versn] = 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 versn]);
+
+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,versn] = fileparts(params.analysis_components);
+        if isempty(ext)
+            ext='.m';
+        end
+        params.analysis_components=fullfile(pathstr,[name ext versn]);
+        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/trunk-jpl-damage/src/m/qmu/dakota_m_write.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/dakota_m_write.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/dakota_m_write.m	(revision 11330)
@@ -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,''diagnostic'',''' 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/trunk-jpl-damage/src/m/qmu/dakota_moments.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/dakota_moments.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/dakota_moments.m	(revision 11330)
@@ -0,0 +1,140 @@
+%
+%  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);
+
+    muci(1)   =mu-tinv(prob,nsamp-1)*sigma/sqrt(nsamp);
+    muci(2)   =mu+tinv(prob,nsamp-1)*sigma/sqrt(nsamp);
+    sigmaci(1)=sigma*sqrt((nsamp-1)/chi2inv(prob  ,nsamp-1));
+    sigmaci(2)=sigma*sqrt((nsamp-1)/chi2inv(1-prob,nsamp-1));
+
+end
Index: /issm/trunk-jpl-damage/src/m/qmu/dakota_out_parse.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/dakota_out_parse.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/dakota_out_parse.m	(revision 11330)
@@ -0,0 +1,884 @@
+%
+%  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,'95% confidence intervals for each response function',51)
+        [dresp]=cis_read(fidi,dresp,fline);
+    elseif strncmp(fline,'Probabilities for each response function',40)
+        [dresp]=cdfs_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)]);
+        fline=fgetl(fidi);
+    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(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(data(:,i),0.05);
+    end
+end
+
+dmin   =min    (data,[],1);
+dquart1=prctile(data,25,1);
+dmedian=median (data,1);
+dquart3=prctile(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 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);
+   
+%  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
+
+    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};
+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)
+        return
+    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 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/trunk-jpl-damage/src/m/qmu/dakota_resp_uconv.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/dakota_resp_uconv.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/dakota_resp_uconv.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/examples/README
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/README	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/README	(revision 11330)
@@ -0,0 +1,3 @@
+Example parameter files to setup QMU (quantification of margins and uncertainties) using Dakota.
+
+
Index: /issm/trunk-jpl-damage/src/m/qmu/examples/all_parameters.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/all_parameters.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/all_parameters.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/examples/dakota_rosenbrock_2d.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/dakota_rosenbrock_2d.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/dakota_rosenbrock_2d.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/examples/dakota_rosenbrock_ls.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/dakota_rosenbrock_ls.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/dakota_rosenbrock_ls.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/examples/dakota_rosenbrock_nond.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/dakota_rosenbrock_nond.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/dakota_rosenbrock_nond.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/examples/dakota_rosenbrock_vector.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/dakota_rosenbrock_vector.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/dakota_rosenbrock_vector.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/examples/direct.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/direct.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/direct.m	(revision 11330)
@@ -0,0 +1,11 @@
+%using library mode of Dakota, only for parallel runs.
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+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/trunk-jpl-damage/src/m/qmu/examples/lrel.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/lrel.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/lrel.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/examples/lrel_mmf.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/lrel_mmf.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/lrel_mmf.m	(revision 11330)
@@ -0,0 +1,95 @@
+%  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','diagnostic');
+
+%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/trunk-jpl-damage/src/m/qmu/examples/lsq.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/lsq.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/lsq.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/examples/opt.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/opt.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/opt.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/examples/paramc.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/paramc.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/paramc.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/examples/paramm.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/paramm.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/paramm.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/examples/samp.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/samp.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/samp.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/examples/samp_direct.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/examples/samp_direct.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/examples/samp_direct.m	(revision 11330)
@@ -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='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+
+md.qmu.numberofpartitions=10;
+
+md.qmu
Index: /issm/trunk-jpl-damage/src/m/qmu/expandresponses.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/expandresponses.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/expandresponses.m	(revision 11330)
@@ -0,0 +1,13 @@
+function dresp=expandresponses(md,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/trunk-jpl-damage/src/m/qmu/expandvariables.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/expandvariables.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/expandvariables.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/importancefactors.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/importancefactors.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/importancefactors.m	(revision 11330)
@@ -0,0 +1,64 @@
+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/trunk-jpl-damage/src/m/qmu/plot/plot_boxplot.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_boxplot.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_boxplot.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/plot/plot_cdf.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_cdf.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_cdf.m	(revision 11330)
@@ -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(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(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/trunk-jpl-damage/src/m/qmu/plot/plot_hist_norm.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_hist_norm.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_hist_norm.m	(revision 11330)
@@ -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(edges(  1),mu(i),sigma(i));
+        dhistc(1:size(dhistc,1)-1,end+1)=...
+            normcdf(edges(2:end  ),mu(i),sigma(i))-...
+            normcdf(edges(1:end-1),mu(i),sigma(i));
+        dabove(end+1)=norminv(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/trunk-jpl-damage/src/m/qmu/plot/plot_hist_norm_ci.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_hist_norm_ci.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_hist_norm_ci.m	(revision 11330)
@@ -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(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(edges(  1),mu(i),sigma(i));
+        dhistc(1:size(dhistc,1)-1,end+1)=...
+            normcdf(edges(2:end  ),mu(i),sigma(i))-...
+            normcdf(edges(1:end-1),mu(i),sigma(i));
+        dabove(end+1)=norminv(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(edges(  1),muci(1,i),sigmaci(2,i));
+        dhistc(1:size(dhistc,1)-1,end+1)=...
+            normcdf(edges(2:end  ),muci(1,i),sigmaci(2,i))-...
+            normcdf(edges(1:end-1),muci(1,i),sigmaci(2,i));
+        dabove(end+1)=norminv(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(edges(  1),muci(1,i),sigmaci(1,i));
+        dhistc(1:size(dhistc,1)-1,end+1)=...
+            normcdf(edges(2:end  ),muci(1,i),sigmaci(1,i))-...
+            normcdf(edges(1:end-1),muci(1,i),sigmaci(1,i));
+        dabove(end+1)=norminv(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(edges(  1),muci(2,i),sigmaci(1,i));
+        dhistc(1:size(dhistc,1)-1,end+1)=...
+            normcdf(edges(2:end  ),muci(2,i),sigmaci(1,i))-...
+            normcdf(edges(1:end-1),muci(2,i),sigmaci(1,i));
+        dabove(end+1)=norminv(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(edges(  1),muci(2,i),sigmaci(2,i));
+        dhistc(1:size(dhistc,1)-1,end+1)=...
+            normcdf(edges(2:end  ),muci(2,i),sigmaci(2,i))-...
+            normcdf(edges(1:end-1),muci(2,i),sigmaci(2,i));
+        dabove(end+1)=norminv(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/trunk-jpl-damage/src/m/qmu/plot/plot_if_bars.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_if_bars.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_if_bars.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/plot/plot_if_spec.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_if_spec.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_if_spec.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/plot/plot_normdist_bars.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_normdist_bars.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_normdist_bars.m	(revision 11330)
@@ -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(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(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/trunk-jpl-damage/src/m/qmu/plot/plot_normplot.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_normplot.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_normplot.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/plot/plot_prob_bars.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_prob_bars.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_prob_bars.m	(revision 11330)
@@ -0,0 +1,197 @@
+%
+%  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/trunk-jpl-damage/src/m/qmu/plot/plot_rlev_bars.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_rlev_bars.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_rlev_bars.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/plot/plot_rlev_bars_ci.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_rlev_bars_ci.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_rlev_bars_ci.m	(revision 11330)
@@ -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(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(sdvect,0,1);
+        dresp(i).cdf(:,1)=norminv(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(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(dresp(i).cdf(:,2),dresp(i).meanci(1),dresp(i).stddevci(2));
+            cdfr(end+1,:)=norminv(dresp(i).cdf(:,2),dresp(i).meanci(1),dresp(i).stddevci(1));
+            cdfr(end+1,:)=norminv(dresp(i).cdf(:,2),dresp(i).meanci(2),dresp(i).stddevci(1));
+            cdfr(end+1,:)=norminv(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/trunk-jpl-damage/src/m/qmu/plot/plot_rvsv_line.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_rvsv_line.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_rvsv_line.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/plot/plot_rvsv_scat3.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_rvsv_scat3.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_rvsv_scat3.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/plot/plot_rvsv_surf.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_rvsv_surf.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_rvsv_surf.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/plot/plot_sampdist_bars.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/plot/plot_sampdist_bars.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/plot/plot_sampdist_bars.m	(revision 11330)
@@ -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(dresp(i).sample,25);
+        dresp(i).median=median (dresp(i).sample);
+        dresp(i).quart3=prctile(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/trunk-jpl-damage/src/m/qmu/postqmu.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/postqmu.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/postqmu.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/preqmu.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/preqmu.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/preqmu.m	(revision 11330)
@@ -0,0 +1,107 @@
+function md=preqmu(md,options)
+%QMU - apply Quantification of Margins and Uncertainties techniques 
+%      to a solution sequence (like diagnostic.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
+%       keep: keep qmudir after analysis
+%       outfiles: (John?)
+%       rstfile: backup file name
+%       rundakota: (John?)
+%       runmpi: (John?)
+
+disp('preprocessing dakota inputs');
+
+%first create temporary directory in which we will work
+if strncmpi(options.overwrite,'y',1)
+	system(['rm -rf ' options.qmudir '/*']); 
+else
+	%does the directory exist? if so, then error out
+	if exist(options.qmudir)==7,
+		error('Existing ''%s'' directory, cannot overwrite. Specify ''overwrite'',''y'' option in solve arguments.',options.qmudir);
+	end
+end
+mkdir(options.qmudir)
+cd(options.qmudir)
+
+%when running in library mode, the in file needs to be called md.miscellaneous.name.qmu.in
+options.qmufile=[md.miscellaneous.name ];
+
+%retrieve variables and resposnes for this particular analysis.
+variables=md.qmu.variables(options.ivar);
+responses=md.qmu.responses(options.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{{{1
+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(options.imethod),variables,responses,md.qmu.params(options.iparams),options.qmufile);
+system(['rm -rf ' md.miscellaneous.name '.m']);
+
+%build a list of variables and responses descriptors. the list is not expanded. {{{1
+variabledescriptors={};
+variable_fieldnames=fieldnames(md.qmu.variables(options.ivar));
+for i=1:length(variable_fieldnames),
+	field_name=variable_fieldnames{i};
+	fieldvariables=md.qmu.variables(options.ivar).(field_name);
+	for j=1:numel(fieldvariables)
+		variabledescriptors{end+1}=fieldvariables(j).descriptor;
+	end
+end
+
+responsedescriptors={};
+response_fieldnames=fieldnames(md.qmu.responses(options.iresp));
+for i=1:length(response_fieldnames),
+	field_name=response_fieldnames{i};
+	fieldresponses=md.qmu.responses(options.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/trunk-jpl-damage/src/m/qmu/process_qmu_options.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/process_qmu_options.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/process_qmu_options.m	(revision 11330)
@@ -0,0 +1,101 @@
+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,'diagnostic') |  ...
+		strcmpi(analysis_type,'prognostic') |  ...
+		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/trunk-jpl-damage/src/m/qmu/process_qmu_response_data.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/process_qmu_response_data.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/process_qmu_response_data.m	(revision 11330)
@@ -0,0 +1,52 @@
+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/trunk-jpl-damage/src/m/qmu/qmu_correlation.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/qmu_correlation.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/qmu_correlation.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/qmuisdistributed.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/qmuisdistributed.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/qmuisdistributed.m	(revision 11330)
@@ -0,0 +1,12 @@
+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/trunk-jpl-damage/src/m/qmu/qmumarshall.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/qmumarshall.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/qmumarshall.m	(revision 11330)
@@ -0,0 +1,76 @@
+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/trunk-jpl-damage/src/m/qmu/qmuname.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/qmuname.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/qmuname.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/qmuresponse.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/qmuresponse.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/qmuresponse.m	(revision 11330)
@@ -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;
+	ishutter=m_dhu.parameters.ishutter;
+	ismacayealpattyn=m_dh.parameters.ismacayealpattyn;
+	isstokes=m_ds.parameters.isstokes;
+	if ishutter,
+
+% 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 ismacayealpattyn,
+
+% 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 isstokes,
+
+% 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/trunk-jpl-damage/src/m/qmu/qmuroot.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/qmuroot.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/qmuroot.m	(revision 11330)
@@ -0,0 +1,13 @@
+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/trunk-jpl-damage/src/m/qmu/recover_qmu_options.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/recover_qmu_options.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/recover_qmu_options.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/sensitivities.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/sensitivities.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/sensitivities.m	(revision 11330)
@@ -0,0 +1,66 @@
+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
+	variable=md.(EnumToModelField(StringToEnum(variablename)));
+
+	%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/trunk-jpl-damage/src/m/qmu/setupdesign/IsScaled.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/setupdesign/IsScaled.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/setupdesign/IsScaled.m	(revision 11330)
@@ -0,0 +1,19 @@
+function status=IsScaled(variablename)
+%ISSCALED decide whether a variable should be scaled or not. 
+
+switch variablename,
+case {'MaterialsRhoIce','MaterialsRhoWater','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/trunk-jpl-damage/src/m/qmu/setupdesign/QmuSetupResponses.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/setupdesign/QmuSetupResponses.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/setupdesign/QmuSetupResponses.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/qmu/setupdesign/QmuSetupVariables.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/setupdesign/QmuSetupVariables.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/setupdesign/QmuSetupVariables.m	(revision 11330)
@@ -0,0 +1,46 @@
+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/trunk-jpl-damage/src/m/qmu/setupdesign/setupriftsfriction.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/qmu/setupdesign/setupriftsfriction.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/qmu/setupdesign/setupriftsfriction.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/shared/GetVerbosityLevel.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/shared/GetVerbosityLevel.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/shared/GetVerbosityLevel.m	(revision 11330)
@@ -0,0 +1,17 @@
+function level=GetVerbosityLevel(level_in)
+%GETVERBOSITYLEVEL - get verbosity level
+%
+%   Usage:
+%      level=GetVerbosityLevel();
+
+persistent verbositylevel;
+
+if nargin==1 & nargout==0,
+	verbositylevel=level_in;
+elseif nargin==0 & nargout==1,
+	if isempty(verbositylevel), error('verbositylevel has not been set. Call SetVerbositylevel first!'); end
+	level=verbositylevel;
+else
+	help GetVerbosityLevel
+	error('Bad usage');
+end
Index: /issm/trunk-jpl-damage/src/m/shared/SetVerbosityLevel.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/shared/SetVerbosityLevel.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/shared/SetVerbosityLevel.m	(revision 11330)
@@ -0,0 +1,10 @@
+function SetVerbosityLevel(level)
+%SETVERBOSITYLEVEL - Set verbosity level
+%
+%   Usage:
+%      SetVerbosityLevel(level)
+
+	%Set persistent variable in GetVerbositylevel
+	GetVerbosityLevel(level);
+
+end
Index: /issm/trunk-jpl-damage/src/m/shared/VerboseControl.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/shared/VerboseControl.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/shared/VerboseControl.m	(revision 11330)
@@ -0,0 +1,11 @@
+function bool=VerboseControl()
+%VERBOSECONTROL - Return true if control level is activated
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Numerics/Synchronize.sh
+%            Please read src/c/shared/Numerics/README for more information
+%
+%   Usage:
+%      bool=VerboseControl()
+
+bool=logical(bitand(GetVerbosityLevel(),32));
Index: /issm/trunk-jpl-damage/src/m/shared/VerboseConvergence.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/shared/VerboseConvergence.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/shared/VerboseConvergence.m	(revision 11330)
@@ -0,0 +1,11 @@
+function bool=VerboseConvergence()
+%VERBOSECONVERGENCE - Return true if convergence level is activated
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Numerics/Synchronize.sh
+%            Please read src/c/shared/Numerics/README for more information
+%
+%   Usage:
+%      bool=VerboseConvergence()
+
+bool=logical(bitand(GetVerbosityLevel(),16));
Index: /issm/trunk-jpl-damage/src/m/shared/VerboseMProcessor.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/shared/VerboseMProcessor.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/shared/VerboseMProcessor.m	(revision 11330)
@@ -0,0 +1,11 @@
+function bool=VerboseMProcessor()
+%VERBOSEMPROCESSOR - Return true if mprocessor level is activated
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Numerics/Synchronize.sh
+%            Please read src/c/shared/Numerics/README for more information
+%
+%   Usage:
+%      bool=VerboseMProcessor()
+
+bool=logical(bitand(GetVerbosityLevel(),1));
Index: /issm/trunk-jpl-damage/src/m/shared/VerboseModule.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/shared/VerboseModule.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/shared/VerboseModule.m	(revision 11330)
@@ -0,0 +1,11 @@
+function bool=VerboseModule()
+%VERBOSEMODULE - Return true if module level is activated
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Numerics/Synchronize.sh
+%            Please read src/c/shared/Numerics/README for more information
+%
+%   Usage:
+%      bool=VerboseModule()
+
+bool=logical(bitand(GetVerbosityLevel(),2));
Index: /issm/trunk-jpl-damage/src/m/shared/VerboseQmu.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/shared/VerboseQmu.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/shared/VerboseQmu.m	(revision 11330)
@@ -0,0 +1,11 @@
+function bool=VerboseQmu()
+%VERBOSEQMU - Return true if qmu level is activated
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Numerics/Synchronize.sh
+%            Please read src/c/shared/Numerics/README for more information
+%
+%   Usage:
+%      bool=VerboseQmu()
+
+bool=logical(bitand(GetVerbosityLevel(),64));
Index: /issm/trunk-jpl-damage/src/m/shared/VerboseSolution.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/shared/VerboseSolution.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/shared/VerboseSolution.m	(revision 11330)
@@ -0,0 +1,11 @@
+function bool=VerboseSolution()
+%VERBOSESOLUTION - Return true if solution level is activated
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Numerics/Synchronize.sh
+%            Please read src/c/shared/Numerics/README for more information
+%
+%   Usage:
+%      bool=VerboseSolution()
+
+bool=logical(bitand(GetVerbosityLevel(),4));
Index: /issm/trunk-jpl-damage/src/m/shared/VerboseSolver.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/shared/VerboseSolver.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/shared/VerboseSolver.m	(revision 11330)
@@ -0,0 +1,11 @@
+function bool=VerboseSolver()
+%VERBOSESOLVER - Return true if solver level is activated
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Numerics/Synchronize.sh
+%            Please read src/c/shared/Numerics/README for more information
+%
+%   Usage:
+%      bool=VerboseSolver()
+
+bool=logical(bitand(GetVerbosityLevel(),8));
Index: /issm/trunk-jpl-damage/src/m/solutions/AdjointCorePointerFromSolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/AdjointCorePointerFromSolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/AdjointCorePointerFromSolutionEnum.m	(revision 11330)
@@ -0,0 +1,14 @@
+function [adjointcore]=AdjointCorePointerFromSolutionEnum(solutiontype),
+%COREPOINTERFROMSOLUTIONENUM - returns solution_core function
+%
+%   Usage:
+%      [adjointcore]=AdjointCorePointerFromSolutionEnum(solutiontype);
+
+switch solutiontype,
+
+	case DiagnosticSolutionEnum,         adjointcore='adjointdiagnostic_core';
+	case SteadystateSolutionEnum,        adjointcore='adjointdiagnostic_core';
+	case BalancethicknessSolutionEnum,   adjointcore='adjointbalancethickness_core';
+	otherwise error('%s%s%s',' solution type: ',EnumToString(solutiontype),' not supported yet!');
+
+end
Index: /issm/trunk-jpl-damage/src/m/solutions/AnalysisConfiguration.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/AnalysisConfiguration.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/AnalysisConfiguration.m	(revision 11330)
@@ -0,0 +1,58 @@
+function [analyses,numanalyses]=AnalysisConfiguration(solutiontype),
+%ANALYSISCONFIGURATION - return type of analyses, number of analyses 
+%
+%   Usage:
+%      [analyses, numanalyses]=AnalysisConfiguration(solutiontype);
+
+
+
+switch solutiontype,
+
+	case DiagnosticSolutionEnum,
+		numanalyses=5;
+		analyses=[DiagnosticHorizAnalysisEnum;DiagnosticVertAnalysisEnum;DiagnosticHutterAnalysisEnum;SurfaceSlopeAnalysisEnum;BedSlopeAnalysisEnum];
+
+	case SteadystateSolutionEnum,
+		numanalyses=7; 
+		analyses=[DiagnosticHorizAnalysisEnum;DiagnosticVertAnalysisEnum;DiagnosticHutterAnalysisEnum;SurfaceSlopeAnalysisEnum;BedSlopeAnalysisEnum;ThermalAnalysisEnum;MeltingAnalysisEnum];
+
+	case ThermalSolutionEnum,
+		numanalyses=2; 
+		analyses=[ThermalAnalysisEnum;MeltingAnalysisEnum];
+
+	case EnthalpySolutionEnum,
+		numanalyses=1; 
+		analyses=[EnthalpyAnalysisEnum];
+
+	case PrognosticSolutionEnum,
+		numanalyses=1; 
+		analyses=[PrognosticAnalysisEnum];
+
+	case BalancethicknessSolutionEnum,
+		numanalyses=1; 
+		analyses=[BalancethicknessAnalysisEnum];
+
+	case SurfaceSlopeSolutionEnum,
+		numanalyses=1; 
+		analyses=[SurfaceSlopeAnalysisEnum];
+
+	case BedSlopeSolutionEnum,
+		numanalyses=1; 
+		analyses=[BedSlopeAnalysisEnum];
+
+	case TransientSolutionEnum,
+		numanalyses=8; 
+		analyses=[DiagnosticHorizAnalysisEnum;DiagnosticVertAnalysisEnum;DiagnosticHutterAnalysisEnum;SurfaceSlopeAnalysisEnum;BedSlopeAnalysisEnum;ThermalAnalysisEnum;MeltingAnalysisEnum;PrognosticAnalysisEnum];
+
+	case FlaimSolutionEnum,
+		numanalyses=1; 
+		analyses=[FlaimAnalysisEnum];
+
+	case HydrologySolutionEnum,
+		numanalyses=3; 
+		analyses=[BedSlopeAnalysisEnum;SurfaceSlopeAnalysisEnum;HydrologyAnalysisEnum];
+
+	otherwise
+		error('%s%s%s',' solution type: ',EnumToString(solutiontype),' not supported yet!');
+
+end
Index: /issm/trunk-jpl-damage/src/m/solutions/CorePointerFromSolutionEnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/CorePointerFromSolutionEnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/CorePointerFromSolutionEnum.m	(revision 11330)
@@ -0,0 +1,22 @@
+function [solutioncore]=CorePointerFromSolutionEnum(parameters,solutiontype),
+%COREPOINTERFROMSOLUTIONENUM - returns solution_core function
+%
+%   Usage:
+%      [solutioncore]=CorePointerFromSolutionEnum(parameters,solutiontype);
+
+switch solutiontype,
+
+	case DiagnosticSolutionEnum,               solutioncore='diagnostic_core';
+	case SteadystateSolutionEnum,              solutioncore='steadystate_core';
+	case ThermalSolutionEnum,                  solutioncore='thermal_core';
+	case EnthalpySolutionEnum,                 solutioncore='enthalpy_core';
+	case PrognosticSolutionEnum,               solutioncore='prognostic_core';
+	case BalancethicknessSolutionEnum,         solutioncore='balancethickness_core';
+	case SurfaceSlopeSolutionEnum,             solutioncore='surfaceslope_core';
+	case BedSlopeSolutionEnum,                 solutioncore='bedslope_core';
+	case TransientSolutionEnum,                solutioncore='transient_core';
+	case FlaimSolutionEnum,                    solutioncore='flaim_core';
+	case HydrologySolutionEnum,                solutioncore='DUMMYDUMMY'; %not working in serial mode
+	otherwise error('%s%s%s',' solution type: ',EnumToString(solutiontype),' not supported yet!');
+
+end
Index: /issm/trunk-jpl-damage/src/m/solutions/MatlabProcessPatch.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/MatlabProcessPatch.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/MatlabProcessPatch.m	(revision 11330)
@@ -0,0 +1,65 @@
+function structure=MatlabProcessPatch(structure);
+%PROCESSPATCH - create a structure from a patch
+%
+%   Usage:
+%      Result=ProcessPatch(Result);
+
+%return if there is no fiel Patch
+if (~isfield(structure,'Patch')),
+	return;
+end
+
+%loop over steps
+for i=1:length(structure),
+
+	%Get Patch for current step
+	Patch=structure(i).Patch;
+	numvertices=structure(i).PatchVertices;
+
+	%check that Patch is not empty
+	if length(Patch)==0 continue; end
+
+	%Get number of fields;
+	fields=unique(Patch(:,1));
+	steps=unique(Patch(:,2));
+
+	%parse steps
+	for j=1:length(steps),
+
+		posstep=find(Patch(:,2)==steps(j));
+
+		%Take all the lines of the Patch for this timestep
+		temporarypatch=Patch(posstep,:);
+		time=temporarypatch(1,3);
+		step=temporarypatch(1,2);
+
+		%parse fields
+		for i=1:length(fields),
+
+			%get name
+			fieldname=EnumToString(fields(i));
+
+			%get line positions
+			pos=find(temporarypatch(:,1)==fields(i));
+
+			%Fill Result structure
+			structure(step).steps=step;
+			structure(step).time=time;
+			structure(step).(fieldname).element=temporarypatch(pos,4);
+			structure(step).(fieldname).interpolation=temporarypatch(pos,5);
+			structure(step).(fieldname).index=temporarypatch(pos,6:5+numvertices);
+			if structure(step).(fieldname).interpolation==P1Enum,
+				structure(step).(fieldname).value=temporarypatch(pos,6+numvertices:end);
+			end
+			if structure(step).(fieldname).interpolation==P0Enum,
+				structure(step).(fieldname).value=temporarypatch(pos,6+numvertices);
+			end
+
+		end
+	end
+end
+
+%remove fields
+structure=rmfield(structure,'Patch');
+structure=rmfield(structure,'PatchVertices');
+structure=rmfield(structure,'PatchNodes');
Index: /issm/trunk-jpl-damage/src/m/solutions/ModelUpdateInputsFromVector.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/ModelUpdateInputsFromVector.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/ModelUpdateInputsFromVector.m	(revision 11330)
@@ -0,0 +1,31 @@
+function models=ModelUpdateInputsFromVector(models, vector, enum, typeenum);
+%MODELUPDATEINPUTSFROMVECTOR - Update inputs using a vector
+%
+%   Update inputs using a vector, just calls the FemModelUpdateInputsFromVector 
+%   routine for all models in the 'models' structure
+% 
+%   Usage: 
+%      ModelUpdateInputsFromVector(models, vector, enum, typeenum);
+%
+%   Example:
+%      ModelUpdateInputsFromVector(models, vx, VxEnum, VertexEnum);
+%      ModelUpdateInputsFromVector(models, vxelem, VxEnum, ElementEnum);
+%
+%
+
+%Check that vecor is not null
+if isempty(vector),
+	return; %don't bother
+end
+
+%go through models and call UpdateInputsFromVector
+modelfields=fields(models);
+for i=1:length(modelfields),
+	field=modelfields(i); field=field{1}; model=models.(field);
+
+	if isstruct(model), %there is an analysis_type model
+		[model.elements,model.nodes,model.vertices,model.loads,model.materials,model.parameters] = UpdateInputsFromVector(model.elements,model.nodes,model.vertices,model.loads,model.materials,model.parameters,vector,enum, typeenum);
+		models.(field)=model;
+	end
+
+end
Index: /issm/trunk-jpl-damage/src/m/solutions/NewFemModel.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/NewFemModel.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/NewFemModel.m	(revision 11330)
@@ -0,0 +1,46 @@
+function femmodel=NewFemModel(md,solution_type,analysis_types,nummodels);
+%NEWFEMMODEL - create a finite element model out of the matlab base \@model md. 
+%   For each analysis_type contained in analysis_types, create a set of nodes, constraints 
+%   and loads. All analyses rely on the same elements, vertices and parameters. See 
+%   FemModel.cpp in src/c/objects for more information on the FemModel implementation in c++
+%
+%   Usage:
+%      femmodel=NewFemModel(md,solution_type,analysis_types,nummodels)
+%
+
+	%Set verbosity
+	SetVerbosityLevel(VerboseToBinary(md.verbose));
+
+   %Dynamically allocate whatever is a list of length nummodels: */
+   femmodel.solution_type=solution_type;
+   femmodel.analysis_counter=nummodels; %point to last analysis_type carried out
+   femmodel.analysis_type_list=analysis_types;
+
+	issmprintf(VerboseMProcessor(),'\n   reading data from input file %s.bin...',md.miscellaneous.name);
+   [femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.constraints,femmodel.loads,femmodel.materials,femmodel.parameters]=ModelProcessor([md.miscellaneous.name '.bin'],solution_type,femmodel.analysis_type_list);
+   
+	%Initialize some fiels with empty celils
+	femmodel.results=struct([]);
+
+	%now, go through all analyses types and post-process datasets
+	for i=1:nummodels,
+
+		analysis_type=femmodel.analysis_type_list(i);
+		issmprintf(VerboseMProcessor(),'%s%s','   dealing with analysis type: ',EnumToString(analysis_type));
+
+		femmodel=SetCurrentConfiguration(femmodel,analysis_type);
+
+		if i==1, %only  create vertices dofs once!
+			issmprintf(VerboseMProcessor(),'%s','      generating vertices degrees of freedom');
+			femmodel.vertices=VerticesDof(femmodel.vertices, femmodel.parameters); 
+		end
+
+		issmprintf(VerboseMProcessor(),'%s','      resolving node constraints');
+		[femmodel.nodes]=SpcNodes(femmodel.nodes,femmodel.constraints,femmodel.parameters,analysis_type);
+
+		issmprintf(VerboseMProcessor(),'%s','      creating nodal degrees of freedom');
+		[femmodel.nodes]=NodesDof(femmodel.nodes,femmodel.parameters);
+
+		issmprintf(VerboseMProcessor(),'%s','      configuring elements and loads');
+		[femmodel.elements,femmodel.loads,femmodel.nodes,femmodel.parameters] = ConfigureObjects( femmodel.elements, femmodel.loads, femmodel.nodes, femmodel.vertices,femmodel.materials,femmodel.parameters);
+	end
Index: /issm/trunk-jpl-damage/src/m/solutions/ResetBoundaryConditions.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/ResetBoundaryConditions.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/ResetBoundaryConditions.m	(revision 11330)
@@ -0,0 +1,18 @@
+function femmodel=ResetBoundaryConditions(femmodel,analysis_type);
+%RESETBOUNDARYCONDITIONS - change boundary conditions of a model
+%
+%   Change boundary condition of a model using a vector solution from another model
+%
+%   Usage:
+%      femmodel=ResetBoundaryConditions(femmodel,analysis_type)
+
+	issmprintf(VerboseSolution,'\n%s',['   updating boundary condition ...']);
+
+	%set current analysis: 
+	femmodel=SetCurrentConfiguration(femmodel,analysis_type);
+
+	%recreate constraints vector for the current analysis
+	ug=GetSolutionFromInputs(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters);
+
+	%update values of spcs inside nodes
+	femmodel.constraints=UpdateDynamicConstraints(femmodel.constraints,femmodel.nodes,femmodel.parameters,ug);
Index: /issm/trunk-jpl-damage/src/m/solutions/SetCurrentConfiguration.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/SetCurrentConfiguration.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/SetCurrentConfiguration.m	(revision 11330)
@@ -0,0 +1,43 @@
+function femmodel=SetCurrentConfiguration(femmodel,configuration_enum,varargin)
+%SETCURRENTCONFIGURATION- set current analysis used to configure elements and nodes in our solutions
+%
+%   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
+%
+%   Usage:
+%      femmodel=SetCurrentConfiguration(femmodel,configuration_type)
+%      femmodel=SetCurrentConfiguration(femmodel,configuration_type,analysis_type)
+%
+%   Ex:
+%      femmodel=SetCurrentConfiguration(femmodel,DiagnosticHorizAnalysisEnum)
+%      femmodel=SetCurrentConfiguration(femmodel,SurfaceSlopeAnalysisEnum,SurfaceSlopeXAnalysisEnum)
+%
+
+	if nargin==3,
+		analysis_enum=varargin{1};
+	elseif nargin==2
+		analysis_enum=configuration_enum;
+	else
+		help SetCurrentConfiguration
+		error('bad usage');
+	end
+
+	%first, look for analysis: 
+	found=-1;
+	for i=1:length(femmodel.analysis_type_list),
+		if femmodel.analysis_type_list(i)==configuration_enum,
+			found=i;
+			break;
+		end
+	end
+
+	if found==-1,
+		error(['SetCurrentConfiguration error message: could not find analysis_type ' EnumToString(configuration_enum) ' in list of FemModel analyses']);
+	end
+	
+	%Now, plug analysis_counter and analysis_type inside the parameters: 
+	%set counter and analyse_type
+	femmodel.parameters.AnalysisCounter=found-1; %for c indices
+	femmodel.parameters.AnalysisType=analysis_enum;
+	femmodel.parameters.ConfigurationType=configuration_enum;
Index: /issm/trunk-jpl-damage/src/m/solutions/SpawnCore.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/SpawnCore.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/SpawnCore.m	(revision 11330)
@@ -0,0 +1,24 @@
+function responses=SpawnCore(femmodel,variables,variabledescriptors,counter);
+%SPAWNCORE - for Qmu analysis, using Dakota. Spawn the core solution.
+%
+%   Usage:
+%      responses=SpawnCore(femmodel,variables,variabledescriptors)
+%
+
+%retrieve parameters
+responsedescriptors=femmodel.parameters.QmuResponsedescriptors; 
+solution_type=femmodel.parameters.SolutionType;
+control_analysis=femmodel.parameters.InversionIscontrol;
+
+issmprintf(VerboseQmu(),'%s%i',['   qmu iteration:'],counter);
+
+%first update the inputs to the femmodel using the variables provided to us by dakota.
+[femmodel.elements femmodel.loads femmodel.materials]=InputUpdateFromDakota(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,variables,variabledescriptors);
+
+%now run the core solution
+[solutioncore]=CorePointerFromSolutionEnum(femmodel.parameters,solution_type);
+if(control_analysis)solutioncore='control_core';end;
+eval(['femmodel=' solutioncore '(femmodel);']);
+
+%now process the results to get response function values
+responses=DakotaResponses(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,responsedescriptors);
Index: /issm/trunk-jpl-damage/src/m/solutions/adjointbalancethickness_core.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/adjointbalancethickness_core.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/adjointbalancethickness_core.m	(revision 11330)
@@ -0,0 +1,29 @@
+function femmodel=adjointbalancethickness_core(femmodel),
+%ADJOINT_CORE - compute inverse method adjoint state
+%
+%   Usage:
+%      femmodel=adjointbalancethickness_core(femmodel)
+
+	%recover parameters common to all solutions
+	control_analysis=femmodel.parameters.InversionIscontrol;
+	solution_type=femmodel.parameters.SolutionType;
+
+	%set analysis type to compute velocity:
+	issmprintf(VerboseSolution,'   computing thickness');
+	femmodel=SetCurrentConfiguration(femmodel,BalancethicknessAnalysisEnum);
+	femmodel=solver_linear(femmodel);
+
+	%Call SurfaceAreax, because some it might be needed by PVector
+	femmodel.elements=SurfaceArea(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters);
+
+	%compute adjoint
+	issmprintf(VerboseSolution,'   computing adjoint');
+	femmodel=SetCurrentConfiguration(femmodel,BalancethicknessAnalysisEnum,AdjointBalancethicknessAnalysisEnum);
+	femmodel=solver_adjoint_linear(femmodel);
+
+	%Save results
+	femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,AdjointEnum);
+	if(solution_type==AdjointSolutionEnum & ~control_analysis)
+		issmprintf(VerboseSolution,'   saving results');
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,AdjointEnum);
+	end
Index: /issm/trunk-jpl-damage/src/m/solutions/adjointdiagnostic_core.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/adjointdiagnostic_core.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/adjointdiagnostic_core.m	(revision 11330)
@@ -0,0 +1,36 @@
+function femmodel=adjointdiagnostic_core(femmodel),
+%ADJOINT_CORE - compute inverse method adjoint state
+%
+%   Usage:
+%      femmodel=adjointdiagnostic_core(femmodel)
+
+	%recover parameters common to all solutions
+	isstokes=femmodel.parameters.FlowequationIsstokes;
+	dim=femmodel.parameters.MeshDimension;
+	control_analysis=femmodel.parameters.InversionIscontrol;
+	solution_type=femmodel.parameters.SolutionType;
+	conserve_loads=true;
+
+	%set analysis type to compute velocity:
+	issmprintf(VerboseSolution,'   computing velocities');
+	femmodel=SetCurrentConfiguration(femmodel,DiagnosticHorizAnalysisEnum);
+	femmodel=solver_nonlinear(femmodel,conserve_loads);
+
+	%Call SurfaceAreax, because some it might be needed by PVector
+	femmodel.elements=SurfaceArea(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters);
+
+	%compute adjoint
+	issmprintf(VerboseSolution,'   computing adjoint');
+	femmodel=SetCurrentConfiguration(femmodel,DiagnosticHorizAnalysisEnum,AdjointHorizAnalysisEnum);
+	femmodel=solver_adjoint_linear(femmodel);
+
+	%save results
+	if(solution_type==AdjointSolutionEnum & ~control_analysis)
+		issmprintf(VerboseSolution,'   saving results');
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,AdjointxEnum);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,AdjointyEnum);
+		if(isstokes),
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,AdjointzEnum);
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,AdjointpEnum);
+		end
+	end
Index: /issm/trunk-jpl-damage/src/m/solutions/balancethickness_core.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/balancethickness_core.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/balancethickness_core.m	(revision 11330)
@@ -0,0 +1,23 @@
+function femmodel=balancethickness_core(femmodel)
+%BALANCEDTHICKNESS_CORE - linear solution sequence
+%
+%   Usage:
+%      femmodel=balancethickness_core(femmode)
+
+	%recover parameters common to all solutions
+	dim=femmodel.parameters.MeshDimension;
+	control_analysis=femmodel.parameters.InversionIscontrol;
+	solution_type=femmodel.parameters.SolutionType;
+
+	%Activate formulation
+	femmodel=SetCurrentConfiguration(femmodel,BalancethicknessAnalysisEnum);
+
+	issmprintf(VerboseSolution,'   call computational core');
+	femmodel=solver_linear(femmodel);
+
+	if (solution_type==BalancethicknessSolutionEnum & ~control_analysis),
+		issmprintf(VerboseSolution,'   saving results');
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,ThicknessEnum);
+	end
+	
+end %end function
Index: /issm/trunk-jpl-damage/src/m/solutions/bedslope_core.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/bedslope_core.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/bedslope_core.m	(revision 11330)
@@ -0,0 +1,25 @@
+function femmodel=bedslope_core(femmodel)
+%BEDSLOPE_CORE - core of the bed slope computation solution
+%
+%   Usage:
+%      femmodel=bedslope_core(femmodel)
+%
+
+	%Recover some parameters:
+	dim=femmodel.parameters.MeshDimension;
+	control_analysis=femmodel.parameters.InversionIscontrol;
+	solution_type=femmodel.parameters.SolutionType;
+
+	issmprintf(VerboseSolution,'   computing bed slope');
+
+	%Call on core computations: 
+	femmodel=SetCurrentConfiguration(femmodel,BedSlopeAnalysisEnum,BedSlopeXAnalysisEnum);
+	femmodel=solver_linear(femmodel);
+	femmodel=SetCurrentConfiguration(femmodel,BedSlopeAnalysisEnum,BedSlopeYAnalysisEnum);
+	femmodel=solver_linear(femmodel);
+	
+	if (solution_type==BedSlopeSolutionEnum & ~control_analysis),
+		issmprintf(VerboseSolution,'   saving results');
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,BedSlopeXEnum);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,BedSlopeYEnum);
+	end
Index: /issm/trunk-jpl-damage/src/m/solutions/control_core.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/control_core.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/control_core.m	(revision 11330)
@@ -0,0 +1,86 @@
+function femmodel=control_core(femmodel)
+%CONTROL_CORE - compute the core inversion
+%
+%   Usage:
+%      femmodel=control_core(femmodel);
+%
+
+	%recover parameters common to all solutions
+	num_controls=femmodel.parameters.InversionNumControlParameters;
+	num_responses=femmodel.parameters.InversionNumCostFunctions;
+	responses=femmodel.parameters.InversionCostFunctions;
+	control_type=femmodel.parameters.InversionControlParameters;
+	solution_type=femmodel.parameters.SolutionType;
+	nsteps=femmodel.parameters.InversionNsteps;
+	maxiter=femmodel.parameters.InversionMaxiterPerStep;
+	step_threshold=femmodel.parameters.InversionStepThreshold;
+	tol_cm=femmodel.parameters.InversionCostFunctionThreshold;
+	gradient_only=femmodel.parameters.InversionGradientOnly;
+	dim=femmodel.parameters.MeshDimension;
+	isstokes=femmodel.parameters.FlowequationIsstokes;
+
+	%Initialise options with maxiter
+	options.MaxIter=femmodel.parameters.InversionMaxiterPerStep;
+
+	%Initialize misfits with a vector of zeros
+	J=zeros(nsteps,1);
+	search_scalar=1;
+
+	%Get core from solution type
+	solutioncore=CorePointerFromSolutionEnum(femmodel.parameters,solution_type);
+	adjointcore=AdjointCorePointerFromSolutionEnum(solution_type);
+
+	%Launch once a complete solution to set up all inputs
+	issmprintf(VerboseControl,'   preparing initial solution');
+	if isstokes,
+		eval(['femmodel=' solutioncore '(femmodel);']);
+	end
+
+	for n=1:nsteps,
+
+		issmprintf(VerboseControl(),['control method step ' num2str(n) '/' num2str(femmodel.parameters.InversionNsteps)]);
+		femmodel.parameters.StepResponses=responses(n,:);
+
+		%In steady state inversion, compute new temperature field now
+		if (solution_type==SteadystateSolutionEnum)
+			femmodel=steadystate_core(femmodel);
+		end
+
+		issmprintf(VerboseControl,'   compute adjoint state');
+		eval(['femmodel=' adjointcore '(femmodel);']);
+
+		femmodel=gradient_core(femmodel,n,search_scalar==0);
+
+		%Return gradient if asked
+		if gradient_only,
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,GradientEnum);
+			return;
+		end
+
+		issmprintf(VerboseControl,'   optimizing along gradient direction');
+		[search_scalar J(n)]=ControlOptimization('objectivefunctionC',0,1,options,femmodel,n,femmodel.parameters);
+
+		issmprintf(VerboseControl,'   updating parameter using optimized search scalar');
+		[femmodel.elements,femmodel.nodes,femmmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters]=InputControlUpdate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,search_scalar,1);
+		issmprintf(VerboseControl,['   value of misfit J after optimization #' num2str(n) ':' num2str(J(n))]);
+
+		%Has convergence been reached?
+		converged=controlconvergence(J(n),tol_cm);
+		if converged,
+			break;
+		end
+
+	end
+
+	%generate output
+	issmprintf(VerboseControl,'   preparing final velocity solution');
+	femmodel.parameters.InversionIscontrol=0;
+	eval(['femmodel=' solutioncore '(femmodel);']);
+
+	%Some results not computed by diagnostic or steadystate
+	for i=1:num_controls,
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,control_type(i));
+	end
+	femmodel.results=AddExternalResult(femmodel.results,JEnum,J);
+
+end %end function
Index: /issm/trunk-jpl-damage/src/m/solutions/controlconvergence.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/controlconvergence.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/controlconvergence.m	(revision 11330)
@@ -0,0 +1,11 @@
+function convergence=controlconvergence(J,tol_cm)
+%CONTROLCONVERGENCE - determine the convergence of control_core solution
+%
+%   Usage:
+%       converged=controlconvergence(J,tol_cm)
+
+	convergence=false;
+	if ~isnan(tol_cm) & J<tol_cm,
+		convergence=true;
+		issmprintf(VerboseConvergence(),'\n      Convergence criterion reached: %g < %g\n',J,tol_cm);
+	end
Index: /issm/trunk-jpl-damage/src/m/solutions/convergence.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/convergence.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/convergence.m	(revision 11330)
@@ -0,0 +1,88 @@
+function converged=convergence(K_ff,p_f,u_f,u_f_old,parameters)
+
+%before we start, check that u_f actually holds values, otherwise, we are done converging
+if isempty(u_f), converged=true;  return; end
+
+%Get convergence options
+yts=parameters.ConstantsYts;
+restol=parameters.DiagnosticRestol;
+reltol=parameters.DiagnosticReltol;
+abstol=parameters.DiagnosticAbstol;
+
+%initialization
+converged=false;
+
+%Display solver caracteristics
+if (VerboseConvergence()),
+	solver_res=norm(K_ff*u_f-p_f,2)/norm(p_f,2);
+	issmprintf(VerboseConvergence(),'%s%g','      condition number of stiffness matrix: ',condest(K_ff));
+	issmprintf(VerboseConvergence(),'%s%g','      solver residue: norm(KU-F)/norm(F)=',solver_res);
+end
+
+%Force equilibrium (Mandatory)
+res=norm(K_ff*u_f_old-p_f,2)/norm(p_f,2);
+if isnan(res),
+	error('convergence error message: mechanical equilibrium convergence criterion is NaN!'); 
+end
+if (res<=restol),
+	issmprintf(VerboseConvergence(),'%-60s%g%s%g%s','      mechanical equilibrium convergence criterion',res*100,' < ',restol*100,' %');
+	converged=true;
+else
+	issmprintf(VerboseConvergence(),'%-60s%g%s%g%s','      mechanical equilibrium convergence criterion',res*100,' > ',restol*100,' %');
+	converged=false;
+end
+
+%Relative criterion (optional)
+if ((~isnan(reltol)) | (VerboseConvergence())),
+
+	%compute ndu/nu
+	duf=u_f-u_f_old;
+	ndu=norm(duf,2); 
+	nu=norm(u_f_old,2); 
+	if isnan(ndu),
+		error('convergence error message: relative convergence criterion is NaN!'); 
+	end
+
+	%print criterion
+	if ~isnan(reltol),
+		if nu, %avoid "dividing by zero" warning
+			if (ndu/nu<=reltol),
+				issmprintf(VerboseConvergence(),'%-60s%g%s%g%s','      relative convergence criterion: norm(du)/norm(u)',ndu/nu*100,' < ',reltol*100,' %');
+			else
+				issmprintf(VerboseConvergence(),'%-60s%g%s%g%s','      relative convergence criterion: norm(du)/norm(u)',ndu/nu*100,' > ',reltol*100,' %');
+				converged=false;
+			end
+		else
+			converged=false;
+		end
+	else
+		if nu, %avoid "dividing by zero" warning
+			issmprintf(VerboseConvergence(),'%-60s%g%s','      relative convergence criterion: norm(du)/norm(u)',ndu/nu*100,' %');
+		end
+	end
+
+end
+
+%Absolute criterion (optional)
+if ((~isnan(abstol)) | VerboseConvergence()),
+
+	%compute max(du)
+	duf=u_f-u_f_old;
+	nduinf=norm(duf,inf)*yts; 
+	if isnan(nduinf),
+		error('convergence error message: absolute convergence criterion is NaN!'); 
+	end
+
+	%print criterion
+	if ~isnan(abstol),
+		if (nduinf<=abstol),
+			issmprintf(VerboseConvergence(),'%-60s%g%s%g%s','      absolute convergence criterion: max(du)',nduinf,' < ',abstol,' m/yr');
+		else
+			issmprintf(VerboseConvergence(),'%-60s%g%s%g%s','      absolute convergence criterion: max(du)',nduinf,' > ',abstol,' m/yr');
+			converged=false;
+		end
+	else
+		issmprintf(VerboseConvergence(),'%-60s%g%s','      absolute convergence criterion: max(du)',nduinf,' m/yr');
+	end
+
+end
Index: /issm/trunk-jpl-damage/src/m/solutions/diagnostic_core.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/diagnostic_core.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/diagnostic_core.m	(revision 11330)
@@ -0,0 +1,79 @@
+function femmodel=diagnostic_core(femmodel);
+%DIAGNOSTIC_CORE - compute the core velocity field 
+%
+%   Usage:
+%      results=diagnostic_core(model);
+%
+
+	%some parameters
+	modify_loads=true;
+	conserve_loads=true;
+
+	%recover parameters common to all solutions
+	dim=femmodel.parameters.MeshDimension;
+	ishutter=femmodel.parameters.FlowequationIshutter;
+	ismacayealpattyn=femmodel.parameters.FlowequationIsmacayealpattyn;
+	isstokes=femmodel.parameters.FlowequationIsstokes;
+	dakota_analysis=femmodel.parameters.QmuIsdakota;
+	control_analysis=femmodel.parameters.InversionIscontrol;
+	solution_type=femmodel.parameters.SolutionType;
+
+	%for qmu analysis, be sure the velocity input we are starting from  is the one in the parameters: 
+	if dakota_analysis & solution_type==DiagnosticSolutionEnum,
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,QmuVxEnum,VxEnum);
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,QmuVyEnum,VyEnum);
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,QmuVzEnum,VzEnum);
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,QmuPressureEnum,PressureEnum);
+	end
+
+	%Compute slopes: 
+	if(ishutter), femmodel=surfaceslope_core(femmodel); end
+	if(isstokes),
+		femmodel=bedslope_core(femmodel); 
+		femmodel=SetCurrentConfiguration(femmodel,DiagnosticHorizAnalysisEnum);
+		femmodel.nodes=ResetCoordinateSystem(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters);
+	end
+
+	if ishutter,
+
+		issmprintf(VerboseSolution,'\n%s',['   computing hutter velocities']);
+
+		%Take the last velocity into account so that the velocity on the MacAyeal domain is not zero
+		if(ismacayealpattyn)femmodel=ResetBoundaryConditions(femmodel,DiagnosticHutterAnalysisEnum); end 
+
+		femmodel=SetCurrentConfiguration(femmodel,DiagnosticHutterAnalysisEnum);
+		femmodel=solver_linear(femmodel);
+
+		if(ismacayealpattyn)femmodel=ResetBoundaryConditions(femmodel,DiagnosticHorizAnalysisEnum); end
+
+	end
+			
+	if xor(ismacayealpattyn,isstokes), %if macayealpattyn and stokes, we must use stokescoupling
+
+		issmprintf(VerboseSolution,'\n%s',['   computing horizontal velocities']);
+		femmodel=SetCurrentConfiguration(femmodel,DiagnosticHorizAnalysisEnum);
+		femmodel=solver_nonlinear(femmodel,modify_loads); 
+	end
+	
+	if ismacayealpattyn & isstokes,
+
+		issmprintf(VerboseSolution,'\n%s',['   computing coupling velocities for macayealpattyn and stokes']);
+		femmodel=SetCurrentConfiguration(femmodel,DiagnosticHorizAnalysisEnum);
+		femmodel=solver_stokescoupling_nonlinear(femmodel,conserve_loads); 
+	end
+
+	if dim==3 & (ismacayealpattyn | ishutter) & ~isstokes,
+	
+		issmprintf(VerboseSolution,'\n%s',['   computing vertical velocities']);
+		femmodel=SetCurrentConfiguration(femmodel,DiagnosticVertAnalysisEnum);
+		femmodel=solver_linear(femmodel);
+	end
+
+	if (solution_type==DiagnosticSolutionEnum & ~control_analysis)
+		issmprintf(VerboseSolution,'\n%s',['   saving results']);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VxEnum);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VyEnum);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VelEnum);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,PressureEnum);
+		if(dim==3) femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VzEnum); end
+	end
Index: /issm/trunk-jpl-damage/src/m/solutions/enthalpy_core.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/enthalpy_core.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/enthalpy_core.m	(revision 11330)
@@ -0,0 +1,36 @@
+function femmodel=enthalpy_core(femmodel)
+%ENTHALPY_CORE - core of enthalpy solution
+%
+%   Usage:
+%      femmodel=enthalpy_core(femmodel)
+
+	%recover parameters common to all solutions
+	ndt=femmodel.parameters.TimesteppingFinalTime;
+	dt=femmodel.parameters.TimesteppingTimeStep;
+	control_analysis=femmodel.parameters.InversionIscontrol;
+	solution_type=femmodel.parameters.SolutionType;
+
+	%Compute number of timesteps
+	if (dt==0 | ndt==0),
+		dt=0;
+		nsteps=1;
+	else
+		nsteps=floor(ndt/dt);
+	end
+
+	%Loop through time
+	for i=1:nsteps,
+		issmprintf(VerboseSolution,'\n%s%i/%i\n','time step: ',i,nsteps);
+		time=(i+1)*dt;
+
+		femmodel=enthalpy_core_step(femmodel,i,time); 
+
+		if (solution_type==EnthalpySolutionEnum & ~control_analysis),
+			issmprintf(VerboseSolution,'\n%s',['   saving results']);
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,EnthalpyEnum,i,time);
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,TemperatureEnum,i,time);
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,WaterfractionEnum,i,time);
+		end
+	end
+
+end %end of function
Index: /issm/trunk-jpl-damage/src/m/solutions/enthalpy_core_step.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/enthalpy_core_step.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/enthalpy_core_step.m	(revision 11330)
@@ -0,0 +1,14 @@
+function femmodel=enthalpy_core_step(femmodel,step,time)
+%ENTHALPY_CORE_STEP - core of the enthalpy solution for one step 
+%
+%   Usage:
+%      femmodel=enthalpy_core_step(femmodel,step,time)
+
+	%some parameters
+	modify_loads=true;
+
+	issmprintf(VerboseSolution,'\n%s',['   computing enthalpy']);
+	femmodel=SetCurrentConfiguration(femmodel,EnthalpyAnalysisEnum);
+	femmodel=solver_nonlinear(femmodel,modify_loads);
+
+end %end function
Index: /issm/trunk-jpl-damage/src/m/solutions/flaim_sol.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/flaim_sol.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/flaim_sol.m	(revision 11330)
@@ -0,0 +1,182 @@
+function md=flaim_sol(md,options)
+%
+%   run flaim solution.
+%
+%   options come from the solve.m routine. They can include flaim options:
+%
+%       fmdir:  any directory to run the flaim analysis
+%       fmfile: input file for flaim
+%       overwrite: overwrite qmudir before analysis
+%       keep: keep qmudir after analysis
+%       latsgn: latitude sign (+1, north; -1, south)
+%       cmap: matlab colormap
+%
+
+disp('preprocessing flaim inputs');
+
+%first create temporary directory in which we will work
+if strncmpi(options.overwrite,'y',1)
+	system(['rm -rf ' options.fmdir '/*']); 
+else
+	%does the directory exist? if so, then error out
+	if exist(options.fmdir)==7,
+		error('Existing ''%s'' directory, cannot overwrite. Specify ''overwrite'',''y'' option in solve arguments.',options.fmdir);
+	end
+end
+mkdir(options.fmdir)
+% for testing
+%system(['cp -p issm-split-geikie1-targets.kml ' options.fmdir]);
+%system(['cp -p solution_best.kml ' options.fmdir]);
+%system(['cp -p flaim.targets.log ' options.fmdir]);
+
+%  process file names
+
+[pathstr,name,ext,versn] = fileparts(md.flaim.tracks);
+fm_tracks=fullfile('',[name ext versn]);
+system(['cp -p ' md.flaim.tracks ' ' options.fmdir]);
+
+if ~isempty(md.flaim.targets)
+    [pathstr,name,ext,versn] = fileparts(md.flaim.targets);
+    if isempty(ext)
+        ext='.kml';
+    end
+    fm_targets=fullfile('',[name ext versn]);
+    ext='.log';
+    filelog=fullfile('',[name ext versn]);
+else
+    fm_targets='fm_targets.kml';
+    filelog='fm_targets.log';
+end
+md.flaim.targets=fm_targets;
+
+if ~isempty(md.flaim.solution)
+	[pathstr,name,ext,versn] = fileparts(md.flaim.solution);
+	filesol=fullfile('',[name '' '']);
+else
+	filesol='solution_best';
+end
+
+%  copy target file if it exists
+
+if any(isnan(md.flaim.criterion)) || isempty(md.flaim.criterion)
+	display('Copying existing target file.');
+	system(['cp -p ' md.flaim.targets ' ' options.fmdir]);
+	cd(options.fmdir)
+
+%  calculate latitude and longitude, if necessary 
+
+else
+	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     ~isfield(options,'latsgn')
+			error(['Missing ''latsgn'' parameter to calculate missing lat/long values.']);
+		elseif (abs(options.latsgn) ~= 1)
+			error(['Incorrect latsgn=' num2str(options.latsgn) ' parameter to calculate missing lat/long values.']);
+		else
+			display('Converting x/y values to lat/long values.');
+			[md.mesh.lat,md.mesh.long]=xy2ll(md.mesh.x,md.mesh.y,options.latsgn);
+		end
+	end
+
+%  colormap command operates on a figure, so create an invisible one
+%  (could also directly call colormaps, e.g. jet(64), but risky)
+
+	if ~isempty(md.flaim.criterion)
+		hfig=figure('Visible','off');
+		if isfield(options,'cmap') && ~isempty(options.cmap)
+			colormap(options.cmap)
+		end
+		options.cmap=colormap;
+		close(hfig)
+	end
+	if ~isfield(options,'cmap')
+		options.cmap=[];
+	end
+
+%  write the target kml file
+
+	cd(options.fmdir)
+	display('Calling KMLMeshWrite.');
+	KMLMeshWrite(md.miscellaneous.name,md.miscellaneous.notes,md.mesh.elements,md.mesh.vertexconnectivity,md.mesh.lat,md.mesh.long,md.qmu.partition,md.flaim.criterion,options.cmap,fm_targets);
+%  for testing
+%	fm_targets='issm-split-geikie1-targets.kml';
+end
+
+%  call flaim
+
+display('Calling flaim.');
+FLAIM_DIR=flaimdir();
+%system([FLAIM_DIR '/clasp/swathModule/models/issm/issm.exe -kml ' fm_tracks ' -kml ' fm_targets ' -gridsatequator 200000 -opt 1 -hst 2017-276T02:57:00 -hdur 4d -sparsepoints -usevalueordering -split-antimeridian >& ' filelog]);
+%$(MODELDIR)$(PATHSEP)$(MODELEXEC) -kml kml_inputs$(PATHSEP)$(KMLNAME) -gridsatequator 200000 \
+%		-opt 1 -hst 2017-276T02:57:00 -hdur 4d -sparsepoints -usevalueordering \
+%		-split-antimeridian -pathoptimize 1 25km 30000
+flaim_cmd=[FLAIM_DIR '/clasp/swathModule/models/issm/issm.exe -kml ' fm_tracks ' -kml ' fm_targets ' -gridsatequator ' int2str(md.flaim.gridsatequator) ' -opt 1 -hst 2017-276T02:57:00 -hdur 4d -sparsepoints'];
+
+if (md.flaim.usevalueordering)
+	flaim_cmd=[flaim_cmd ' -usevalueordering'];
+end
+if (md.flaim.split_antimeridian)
+	flaim_cmd=[flaim_cmd ' -split-antimeridian'];
+end
+if (md.flaim.path_optimize)
+	flaim_cmd=[flaim_cmd ' -pathoptimize ' num2str(md.flaim.opt_ndir) ' ' num2str(md.flaim.opt_dist) 'km ' num2str(md.flaim.opt_niter)];
+end
+
+flaim_cmd=[flaim_cmd ' >& ' filelog];
+system(flaim_cmd);
+
+%  post-process the flaim output
+
+display(['Post-processing the flaim output in the ''' options.fmdir ''' sub-directory.']);
+
+if exist('solution_best.kml','file')
+	if ~strcmp(filesol,'solution_best')
+		system(['mv solution_best.kml ' filesol '.kml']);
+	end
+	if ~strncmpi(options.keep,'y',1)
+		md.results.FlaimSolution.solution=[filesol];
+	else
+		md.results.FlaimSolution.solution=[options.fmdir filesep filesol];
+	end
+else
+	md.results.FlaimSolution.solution='';
+end
+
+if exist(filelog,'file')
+	[status,fline]=system(['grep -i quality ' filelog]);
+
+	if ~isempty(fline)
+		strings=textscan(fline,'%s','delimiter',' =,','MultipleDelimsAsOne',1);
+		md.results.FlaimSolution.quality =sscanf(strings{1}{end},'%f');
+	else
+		warning('Could not find ''quality'' in the ''%s/%s'' flaim log file.',options.fmdir,filelog);
+		md.results.FlaimSolution.quality =NaN;
+	end
+	fidi=fopen(filelog,'r');
+	while true
+		fline=fgetl(fidi);
+		if ~ischar(fline) || strncmp(fline,'........',8)
+			break
+		end
+	end
+	fido=fopen([filesol '.log'],'w');
+	while true
+		fline=fgetl(fidi);
+		if ~ischar(fline)
+			break
+		end
+		fprintf(fido,'%s\n',fline);
+	end
+	fclose(fidi);
+	fclose(fido);
+end
+display(md.results.FlaimSolution);
+
+cd ..
+if ~strncmpi(options.keep,'y',1)
+	system(['mv ' options.fmdir filesep fm_targets ' .']);
+	system(['mv ' options.fmdir filesep filesol '.kml .']);
+	system(['mv ' options.fmdir filesep filesol '.log .']);
+	system(['rm -rf ' options.fmdir]);
+end
+
Index: /issm/trunk-jpl-damage/src/m/solutions/gradient_core.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/gradient_core.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/gradient_core.m	(revision 11330)
@@ -0,0 +1,54 @@
+function femmodel=gradient_core(femmodel,varargin),
+%GRADIENT_CORE - Brief compute inverse method gradient direction
+% 
+%   Usage:
+%       femmodel=gradient_core(femmodel,varargin);
+% 
+%   Examples:
+%      femmodel=gradient_core(femmodel);
+%      femmodel=gradient_core(femmodel,step,search_scalar);
+
+if nargin==3,
+	step=varargin{1};
+	orthogonalize=varargin{2};
+elseif nargin==1
+	step=0;
+	orthogonalize=false;
+else
+	help gradient_core
+	error('bad usage');
+end
+
+	%recover parameters common to all solutions
+	num_controls=femmodel.parameters.InversionNumControlParameters;
+	control_type=femmodel.parameters.InversionControlParameters;
+	control_steady=femmodel.parameters.ControlSteady;
+	gradient_scaling_list=femmodel.parameters.InversionGradientScaling;
+
+	for i=1:num_controls,
+
+		issmprintf(VerboseControl,['   compute gradient of J with respect to %s'],EnumToString(control_type(i)));
+		grad=Gradj(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,control_type(i));
+
+		if orthogonalize,
+			issmprintf(VerboseControl,'%s',['   orthogonalization']);
+			old_gradient=ControlInputGetGradient(femmodel.elements,femmodel.nodes, femmodel.vertices,femmodel.loads, femmodel.materials,femmodel.parameters,control_type(i));
+			new_gradient=Orth(grad,old_gradient);
+		else
+			new_gradient=grad;
+		end
+
+		 %Get scaling factor of current control:
+		 norm_grad=norm(new_gradient,inf);
+		 if(norm_grad<=0),     error(['||∂J/∂α||∞ = 0   gradient norm of J with respect to ' EnumToString(control_type(i))  ' is zero']); end
+		 if(isnan(norm_grad)), error(['||∂J/∂α||∞ = NaN gradient norm of J with respect to ' EnumToString(control_type(i))  ' is NaN' ]); end
+		 gradient_scaling=gradient_scaling_list(step,i)/norm_grad;
+
+		%plug back into inputs:
+		[femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters]=ControlInputSetGradient(femmodel.elements,femmodel.nodes, femmodel.vertices,femmodel.loads, femmodel.materials,  femmodel.parameters,control_type(i),new_gradient);
+	end
+
+	%Scale all gradients
+	for i=1:num_controls,
+		[femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters]=ControlInputScaleGradient(femmodel.elements,femmodel.nodes, femmodel.vertices,femmodel.loads, femmodel.materials,  femmodel.parameters,control_type(i),gradient_scaling);
+	end
Index: /issm/trunk-jpl-damage/src/m/solutions/issm.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/issm.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/issm.m	(revision 11330)
@@ -0,0 +1,42 @@
+function md=issm(md,solution_type);
+%ISSM - ISSM main parallel program
+%
+%   Usage:
+%      md=issm(md)
+%
+	%timing
+	t1=clock;
+	disp('launching solution sequence');
+
+	%out of solution_type, figure types of analyses needed:
+	[analyses,numanalyses]=AnalysisConfiguration(solution_type);
+
+	%create finite element model
+	femmodel=NewFemModel(md,solution_type,analyses,numanalyses);
+
+	%out of solution_type, figure out solution core function pointer
+	[solutioncore]=CorePointerFromSolutionEnum(femmodel.parameters,solution_type);
+	
+	%process petsc options: 
+	femmodel.parameters=ParsePetscOptions(femmodel.parameters,[md.miscellaneous.name '.petsc']);
+
+	%retrieve parameters
+	dakota_analysis=femmodel.parameters.QmuIsdakota;
+	control_analysis=femmodel.parameters.InversionIscontrol;
+
+	%compute solution
+	issmprintf(VerboseSolution,'%s',['call computational core']);
+	if dakota_analysis,
+		Dakota(femmodel);
+	elseif control_analysis
+		femmodel=control_core(femmodel);
+	else
+		eval(['femmodel=' solutioncore '(femmodel);']);
+	end
+
+	issmprintf(VerboseSolution,'%s',['write results'])
+	md.results.(EnumToString(solution_type))=OutputResults(femmodel.elements, femmodel.nodes , femmodel.vertices , femmodel.loads , femmodel.materials, femmodel.parameters, femmodel.results);
+
+	%stop timing
+	t2=clock;
+	disp(['solution converged in ' num2str(etime(t2,t1)) ' seconds']);
Index: /issm/trunk-jpl-damage/src/m/solutions/modelsize.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/modelsize.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/modelsize.m	(revision 11330)
@@ -0,0 +1,20 @@
+function dof=modelsize(models)
+%DOF - return the maximum number of degrees of freedom of the model
+%
+%   Usage:
+%      dof=modelsize(models)
+
+%initialize dof
+dof=0;
+
+%get all models
+modelsname=fieldnames(models);
+
+%get max dof
+for i=1:length(modelsname);
+	if ~strcmpi(modelsname,'analysis_type'),
+		if ~isempty(models.(modelsname{i}).nodesets),
+			dof=max(dof,models.(modelsname{i}).nodesets.fsize);
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/solutions/objectivefunctionC.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/objectivefunctionC.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/objectivefunctionC.m	(revision 11330)
@@ -0,0 +1,36 @@
+function J =objectivefunctionC(search_scalar,femmodel);
+%OBJECTIVEFUNCTIONC - objective function that return a parameter for a certain function
+
+conserve_loads=true;
+J=0;
+
+%recover some parameters
+analysis_type = femmodel.parameters.AnalysisType;
+solution_type = femmodel.parameters.SolutionType;
+isstokes      = femmodel.parameters.FlowequationIsstokes;
+
+%set current configuration
+if (solution_type==DiagnosticSolutionEnum | solution_type==SteadystateSolutionEnum)
+	femmodel=SetCurrentConfiguration(femmodel,DiagnosticHorizAnalysisEnum);
+elseif (solution_type==BalancethicknessSolutionEnum)
+	femmodel=SetCurrentConfiguration(femmodel,BalancethicknessAnalysisEnum);
+else
+	error('solution not implemented yet');
+end
+
+%Use search scalar to shoot parameter in the gradient direction:
+[femmodel.elements,femmodel.nodes,femmmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters]=InputControlUpdate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,search_scalar,0);
+
+%Run diagnostic with updated inputs:
+if (solution_type==DiagnosticSolutionEnum)
+	femmodel=solver_nonlinear(femmodel,conserve_loads);  %true means we conserve loads at each diagnostic run
+elseif (solution_type==SteadystateSolutionEnum)
+	femmodel=diagnostic_core(femmodel);  %We need a 3D velocity!! (vz is required for the next thermal run)
+elseif (solution_type==BalancethicknessSolutionEnum)
+	femmodel=solver_linear(femmodel);
+else
+	error('solution not implemented yet');
+end
+
+%Compute misfit for this velocity field
+J=CostFunction(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials, femmodel.parameters);
Index: /issm/trunk-jpl-damage/src/m/solutions/prognostic_core.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/prognostic_core.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/prognostic_core.m	(revision 11330)
@@ -0,0 +1,22 @@
+function femmodel=prognostic_core(femmodel)
+%PROGNOSTIC_CORE - linear solution sequence
+%
+%   Usage:
+%      femmodel=prognostic_core(femmodel)
+
+	%recover parameters common to all solutions
+	control_analysis=femmodel.parameters.InversionIscontrol;
+	solution_type=femmodel.parameters.SolutionType;
+
+	%Activate formulation
+	femmodel=SetCurrentConfiguration(femmodel,PrognosticAnalysisEnum);
+
+	issmprintf(VerboseSolution,'\n%s',['   call computational core']);
+	femmodel=solver_linear(femmodel);
+	
+	if (solution_type==PrognosticSolutionEnum & ~control_analysis)
+		issmprintf(VerboseSolution,'\n%s',['   saving results']);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,ThicknessEnum);
+	end
+
+end %end function
Index: /issm/trunk-jpl-damage/src/m/solutions/steadystate_core.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/steadystate_core.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/steadystate_core.m	(revision 11330)
@@ -0,0 +1,51 @@
+function femmodel=steadystate_core(femmodel);
+%STEADYSTATE_CORE - compute the core temperature and velocity field  at thermal steady state.
+%
+%   Usage:
+%      femmodel=steadystate_core(femmodel);
+%
+
+	%recover parameters common to all solutions
+	dim=femmodel.parameters.MeshDimension;
+	control_analysis=femmodel.parameters.InversionIscontrol;
+	solution_type=femmodel.parameters.SolutionType;
+
+	%Initialize counter
+	step=1;
+
+	while true,
+
+		issmprintf(VerboseSolution,'\n%s%i\n','   computing velocities and temperatures for step: ',step);
+		femmodel=thermal_core(femmodel); 
+
+		issmprintf(VerboseSolution,'\n%s',['   computing new velocity']);
+		femmodel=diagnostic_core(femmodel); 
+
+		if step>1,
+			issmprintf(VerboseSolution,'\n%s',['   checking temperature, velocity and pressure convergence']);
+			if steadystateconvergence(femmodel), break; end
+		end 
+
+		issmprintf(VerboseSolution,'\n%s',['   saving velocities, temperature and pressure for convergence']);
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VxEnum,VxPicardEnum);
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VyEnum,VyPicardEnum);
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VzEnum,VzPicardEnum);
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,PressureEnum,PressurePicardEnum);
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,TemperatureEnum,TemperatureOldEnum);
+
+		%Increase counter
+		step=step+1;
+	end
+
+	if (solution_type==SteadystateSolutionEnum & ~control_analysis),
+		issmprintf(VerboseSolution,'\n%s',['   saving results']);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VxEnum);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VyEnum);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VzEnum);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VelEnum);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,PressureEnum);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,TemperatureEnum);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,BasalforcingsMeltingRateEnum);
+	end
+
+end %end of function
Index: /issm/trunk-jpl-damage/src/m/solutions/steadystateconvergence.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/steadystateconvergence.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/steadystateconvergence.m	(revision 11330)
@@ -0,0 +1,23 @@
+function converged=steadystateconvergence(femmodel),
+%STEADYSTATECONVERGENCE - determine convergence of steady state solution
+% 
+%   Usage:
+%      steadystateconvergence(femmodel)
+	
+	converged=false;
+	velocity_convergence=false;
+	temperature_convergence=false;
+
+	%Retrieve parameters
+	convergencecriterionvalue=femmodel.parameters.SteadystateReltol;
+	velocityenums=[VxEnum;VxPicardEnum;VyEnum;VyPicardEnum;VzEnum;VzPicardEnum;PressureEnum;PressurePicardEnum]; %pairs of enums (new and old) on which to carry out the converence tests
+	temperatureenums=[TemperatureEnum;TemperatureOldEnum];
+	convergencecriterion=[RelativeEnum]; %criterions for convergence, RelativeEnum or AbsoluteEnum 
+
+	%Figure out convergence at the input level, because we don't have the solution vectors
+	velocity_convergence=InputConvergence(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,velocityenums,convergencecriterion,convergencecriterionvalue);
+	temperature_convergence=InputConvergence(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,temperatureenums,convergencecriterion,convergencecriterionvalue);
+
+	if (velocity_convergence & temperature_convergence),
+		converged=true;
+	end
Index: /issm/trunk-jpl-damage/src/m/solutions/surfaceslope_core.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/surfaceslope_core.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/surfaceslope_core.m	(revision 11330)
@@ -0,0 +1,26 @@
+function femmodel=surfaceslope_core(femmodel)
+%SURFACESLOPE_CORE - core of the surface slope computation solution
+%
+%   Usage:
+%      femmodel=surfaceslope_core(femmodel)
+%
+
+	%Recover some parameters:
+	dim=femmodel.parameters.MeshDimension;
+	control_analysis=femmodel.parameters.InversionIscontrol;
+	solution_type=femmodel.parameters.SolutionType;
+
+	%Call on core computations: 
+	issmprintf(VerboseSolution,'\n%s',['   computing surface slope']);
+	femmodel=SetCurrentConfiguration(femmodel,SurfaceSlopeAnalysisEnum,SurfaceSlopeXAnalysisEnum);
+	femmodel=solver_linear(femmodel);
+	femmodel=SetCurrentConfiguration(femmodel,SurfaceSlopeAnalysisEnum,SurfaceSlopeYAnalysisEnum);
+	femmodel=solver_linear(femmodel);
+	
+	if (solution_type==SurfaceSlopeSolutionEnum),
+		issmprintf(VerboseSolution,'\n%s',['   saving results']);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,SurfaceSlopeXEnum);
+		femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,SurfaceSlopeYEnum);
+	end
+
+end %end function
Index: /issm/trunk-jpl-damage/src/m/solutions/thermal_core.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/thermal_core.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/thermal_core.m	(revision 11330)
@@ -0,0 +1,37 @@
+function femmodel=thermal_core(femmodel)
+%THERMAL_CORE - core of thermal solution
+%
+%   Usage:
+%      femmodel=thermal_core(femmodel)
+
+
+	%recover parameters common to all solutions
+	ndt=femmodel.parameters.TimesteppingFinalTime;
+	dt=femmodel.parameters.TimesteppingTimeStep;
+	control_analysis=femmodel.parameters.InversionIscontrol;
+	solution_type=femmodel.parameters.SolutionType;
+
+	%Compute number of timesteps
+	if (dt==0 | ndt==0),
+		dt=0;
+		nsteps=1;
+	else
+		nsteps=floor(ndt/dt);
+	end
+
+	%Loop through time
+	for i=1:nsteps,
+		issmprintf(VerboseSolution,'\n%s%i/%i\n','time step: ',i,nsteps);
+		time=(i+1)*dt;
+
+		issmprintf(VerboseSolution,'\n%s',['   computing temperature']);
+		femmodel=thermal_core_step(femmodel,i,time); 
+
+		if (solution_type==ThermalSolutionEnum & ~control_analysis),
+			issmprintf(VerboseSolution,'\n%s',['   saving results']);
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,TemperatureEnum,i,time);
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,BasalforcingsMeltingRateEnum,i,time);
+		end
+	end
+
+end %end of function
Index: /issm/trunk-jpl-damage/src/m/solutions/thermal_core_step.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/thermal_core_step.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/thermal_core_step.m	(revision 11330)
@@ -0,0 +1,15 @@
+function femmodel=thermal_core_step(femmodel,step,time)
+%THERMAL_CORE_STEP - core of the thermal solution for one step 
+%
+%   Usage:
+%      femmodel=thermal_core_step(femmodel,step,time)
+
+	issmprintf(VerboseSolution,'\n%s',['   computing temperature']);
+	femmodel=SetCurrentConfiguration(femmodel,ThermalAnalysisEnum);
+	femmodel=solver_thermal_nonlinear(femmodel);
+
+	issmprintf(VerboseSolution,'\n%s',['   computing melting']);
+	femmodel=SetCurrentConfiguration(femmodel,MeltingAnalysisEnum);
+	femmodel=solver_linear(femmodel);
+	
+end %end function
Index: /issm/trunk-jpl-damage/src/m/solutions/transient_core.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solutions/transient_core.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solutions/transient_core.m	(revision 11330)
@@ -0,0 +1,97 @@
+function femmodel=transient3d_core(femmodel)
+%TRANSIENT3D_CORE - core of transient 2d solution
+%
+%   Usage:
+%      femmodel=transient3d_core(femmodel)
+
+	%recover parameters common to all solutions
+	dim=femmodel.parameters.MeshDimension;
+	ndt=femmodel.parameters.TimesteppingFinalTime;
+	dt=femmodel.parameters.TimesteppingTimeStep;
+	yts=femmodel.parameters.ConstantsYts;
+	control_analysis=femmodel.parameters.InversionIscontrol;
+	solution_type=femmodel.parameters.SolutionType;
+	output_frequency=femmodel.parameters.SettingsOutputFrequency;
+	time_adapt=femmodel.parameters.TimesteppingTimeAdapt;
+	dakota_analysis=femmodel.parameters.QmuIsdakota;
+	isdiagnostic=femmodel.parameters.TransientIsdiagnostic;
+	isprognostic=femmodel.parameters.TransientIsprognostic;
+	isthermal=femmodel.parameters.TransientIsthermal;
+	isgroundingline=femmodel.parameters.TransientIsgroundingline;
+	groundinglinemigration=femmodel.parameters.GroundinglineMigration;
+
+	%Initialize
+	time=0;
+	step=0;
+
+	%for qmu analysis, be sure the velocity input we are starting from  is the one in the parameters: 
+	if dakota_analysis,
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,QmuVxEnum,VxEnum);
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,QmuVyEnum,VyEnum);
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,QmuVzEnum,VzEnum);
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,QmuPressureEnum,PressureEnum);
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,QmuBedEnum,BedEnum);
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,QmuThicknessEnum,ThicknessEnum);      
+		femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,QmuSurfaceEnum,SurfaceEnum);
+		if (isthermal & dim==3)
+			femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,QmuTemperatureEnum,TemperatureEnum);
+			femmodel.elements=InputDuplicate(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,QmuMeltingEnum,BasalforcingsMeltingRateEnum);
+		end
+	end
+
+	%Loop through time
+	while (time < ndt - (yts*eps)),
+
+		%Increment
+		if(time_adapt),
+			dt=TimeAdapt(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters);
+			if(time+dt>ndt), dt=ndt-time; end
+			femmodel.parameters.TimesteppingTimeStep=dt;
+		end
+		step=step+1;
+		time=time+dt;
+		femmodel.parameters.Time=time;
+
+		issmprintf(VerboseSolution,'\n%s%g%s%i%s%g\n','time [yr] ',time/yts,' iteration number: ',step,'/',floor(ndt/dt));
+
+		if (isthermal & dim==3)
+			issmprintf(VerboseSolution,'\n%s',['   computing temperature']);
+			femmodel=thermal_core_step(femmodel); 
+		end
+
+		if (isdiagnostic)
+			issmprintf(VerboseSolution,'\n%s',['   computing new velocities']);
+			femmodel=diagnostic_core(femmodel); 
+		end
+
+		if (isprognostic)
+			issmprintf(VerboseSolution,'\n%s',['   computing new thickness']);
+			femmodel=prognostic_core(femmodel); 
+			issmprintf(VerboseSolution,'\n%s',['   updating vertices position']);
+			[femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters]=...
+				UpdateVertexPositions(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters);
+		end
+
+		if (isgroundingline)
+			issmprintf(VerboseSolution,'\n%s',['   computing new grounding line']);
+			[femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters]=...
+				GroundinglineMigration(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters);
+		end
+
+		if (solution_type==TransientSolutionEnum & ~control_analysis & (mod(step,output_frequency)==0 | time==ndt)),
+			issmprintf(VerboseSolution,'\n%s',['   saving results']);
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VxEnum,step,time);
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VyEnum,step,time);
+			if (dim==3), femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VzEnum,step,time); end
+			if (isdiagnostic), femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,VelEnum,step,time); end
+			if (isdiagnostic), femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,PressureEnum,step,time); end
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,ThicknessEnum,step,time);
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,SurfaceEnum,step,time);
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,BedEnum,step,time);
+			if (dim==3 & isthermal), femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,TemperatureEnum,step,time);end
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,BasalforcingsMeltingRateEnum,step,time);
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,SurfaceforcingsMassBalanceEnum,step,time);
+			femmodel.elements=InputToResult(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,MaskElementonfloatingiceEnum,step,time);
+		end
+	end
+end %end of function
Index: /issm/trunk-jpl-damage/src/m/solvers/solver_adjoint_linear.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solvers/solver_adjoint_linear.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solvers/solver_adjoint_linear.m	(revision 11330)
@@ -0,0 +1,19 @@
+function femmodel=solver_adjoint_linear(femmodel)
+%SOLVER_LINEAR - core solver of any linear solution sequence
+%
+%   Usage:
+%      femmodel =solver_adjoint_linear(femmodel)
+
+	%Get parameters
+	configuration_type=femmodel.parameters.ConfigurationType;
+	[femmodel.nodes]=UpdateConstraints(femmodel.nodes,femmodel.constraints,femmodel.parameters);
+
+	[K_ff,K_fs,p_f,df,kmax]=SystemMatrices(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters);
+	ys =CreateNodalConstraints(femmodel.nodes,configuration_type);
+	p_f=Reduceload( p_f, K_fs, ys,true);
+
+	issmprintf(VerboseSolver(),'%s%g','      condition number of stiffness matrix: ',condest(K_ff));
+	u_f=Solver(K_ff,p_f,[],df,femmodel.parameters);
+	u_g=Mergesolutionfromftog( u_f, ys, femmodel.nodes,femmodel.parameters,true); 
+
+	[femmodel.elements,femmodel.materials]=InputUpdateFromSolution(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,u_g);
Index: /issm/trunk-jpl-damage/src/m/solvers/solver_linear.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solvers/solver_linear.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solvers/solver_linear.m	(revision 11330)
@@ -0,0 +1,18 @@
+function femmodel=solver_linear(femmodel)
+%SOLVER_LINEAR - core solver of any linear solution sequence
+%
+%   Usage:
+%      femmodel =solver_linear(femmodel)
+
+	%Get parameters
+	configuration_type=femmodel.parameters.ConfigurationType;
+	[femmodel.nodes]=UpdateConstraints(femmodel.nodes,femmodel.constraints,femmodel.parameters);
+
+	[K_ff,K_fs,p_f,df,kmax]=SystemMatrices(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters);
+	ys  =CreateNodalConstraints(femmodel.nodes,configuration_type);
+	p_f =Reduceload( p_f, K_fs, ys);
+
+	issmprintf(VerboseSolver(),'%s%g','      condition number of stiffness matrix: ',condest(K_ff));
+	u_f=Solver(K_ff,p_f,[],df,femmodel.parameters);
+	u_g= Mergesolutionfromftog( u_f, ys, femmodel.nodes,femmodel.parameters); 
+	[femmodel.elements,femmodel.materials]=InputUpdateFromSolution(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,u_g);
Index: /issm/trunk-jpl-damage/src/m/solvers/solver_nonlinear.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solvers/solver_nonlinear.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solvers/solver_nonlinear.m	(revision 11330)
@@ -0,0 +1,77 @@
+function femmodel=solver_nonlinear(femmodel,conserve_loads)
+%SOLVER_NONLINEAR - core solver of diagnostic run
+%
+%   Usage:
+%      [femmodel]=solver_nonlinear(femmodel,conserve_loads)
+
+	%Branch on partitioning schema requested
+	rift_penalty_threshold=femmodel.parameters.DiagnosticRiftPenaltyThreshold;
+	maxiter=femmodel.parameters.DiagnosticMaxiter;
+	configuration_type=femmodel.parameters.ConfigurationType;
+	[femmodel.nodes]=UpdateConstraints(femmodel.nodes,femmodel.constraints,femmodel.parameters);
+
+	%keep a copy of loads for now
+	loads=femmodel.loads;
+
+	%initialize solution vector
+	converged=0; count=1;
+
+	%Start non-linear iteration using input velocity: 
+	ug=GetSolutionFromInputs(femmodel.elements, femmodel.nodes, femmodel.vertices, loads, femmodel.materials, femmodel.parameters);
+	uf=Reducevectorgtof( ug, femmodel.nodes,femmodel.parameters);
+
+	%Update the solution to make sure that vx and vxold are similar
+	[femmodel.elements loads]=InputUpdateFromConstant(femmodel.elements,femmodel.nodes,femmodel.vertices,loads,femmodel.materials,femmodel.parameters,double(converged),ConvergedEnum);
+	[femmodel.elements,femmodel.materials]=InputUpdateFromSolution(femmodel.elements,femmodel.nodes,femmodel.vertices,loads,femmodel.materials,femmodel.parameters,ug);
+
+	while(~converged),
+
+		%save pointer to old velocity
+		old_ug=ug;
+		old_uf=uf;
+
+		[K_ff,K_fs,p_f,df,kmax]=SystemMatrices(femmodel.elements,femmodel.nodes,femmodel.vertices,loads,femmodel.materials,femmodel.parameters);
+		ys=CreateNodalConstraints(femmodel.nodes,configuration_type);
+		p_f = Reduceload( p_f, K_fs, ys);
+
+		issmprintf(VerboseSolver(),'%s%g','      condition number of stiffness matrix: ',condest(K_ff));
+		uf=Solver(K_ff,p_f,old_uf,df,femmodel.parameters);
+		ug= Mergesolutionfromftog( uf, ys, femmodel.nodes,femmodel.parameters); 
+
+		%Figure out if convergence have been reached
+		converged=convergence(K_ff,p_f,uf,old_uf,femmodel.parameters);
+
+		%add convergence status into  status
+		[femmodel.elements loads]=InputUpdateFromConstant(femmodel.elements,femmodel.nodes,femmodel.vertices,loads,femmodel.materials,femmodel.parameters,double(converged),ConvergedEnum);
+
+		[femmodel.elements,femmodel.materials]=InputUpdateFromSolution(femmodel.elements,femmodel.nodes,femmodel.vertices,loads,femmodel.materials,femmodel.parameters,ug);
+		[loads,constraints_converged,num_unstable_constraints] =ConstraintsState( femmodel.elements,femmodel.nodes,femmodel.vertices,loads, femmodel.materials,femmodel.parameters);
+
+		issmprintf(VerboseConvergence(),'%s%i','      number of unstable constraints: ',num_unstable_constraints);
+
+		%rift convergence
+		if ~constraints_converged,
+			if converged,
+				if num_unstable_constraints <= rift_penalty_threshold,
+					converged=1;
+				else 
+					converged=0;
+				end
+			end
+		end
+
+		%increase count
+		count=count+1;
+		if(converged==1) break; end
+		if(count>maxiter),
+			issmprintf(true,'%s%i%s','      maximum number of iterations ',maxiter,' exceeded');
+			break;
+		end
+
+	end
+
+	%deal with loads:
+	if conserve_loads==false,
+		femmodel.loads=loads;
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/solvers/solver_stokescoupling_nonlinear.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solvers/solver_stokescoupling_nonlinear.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solvers/solver_stokescoupling_nonlinear.m	(revision 11330)
@@ -0,0 +1,54 @@
+function femmodel=solver_couplingstokes_nonlinear(femmodel,conserve_loads)
+%SOLVER_COUPLINGSTOKES_NONLINEAR - core solver of coupling run
+%
+%   Usage:
+%      [femmodel]=solver_couplingstokes_nonlinear(femmodel,conserve_loads)
+
+	%initialize solution vector
+	converged=0; count=1;
+
+	%First get ug=ug_horiz+ug_vert
+	femmodel=SetCurrentConfiguration(femmodel,DiagnosticHorizAnalysisEnum);
+	ug_horiz=GetSolutionFromInputs(femmodel.elements, femmodel.nodes, femmodel.vertices, femmodel.loads, femmodel.materials, femmodel.parameters);
+	uf_horiz=Reducevectorgtof( ug_horiz, femmodel.nodes,femmodel.parameters);
+
+	while(~converged),
+
+		%First compute the horizontal velocity
+		femmodel=SetCurrentConfiguration(femmodel,DiagnosticHorizAnalysisEnum);
+		configuration_type=femmodel.parameters.ConfigurationType;
+
+		%Update the solution to make sure that vx and vxold are similar
+		[femmodel.elements,femmodel.materials]=InputUpdateFromSolution(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,ug_horiz);
+
+		%save pointer to old velocity
+		old_ug_horiz=ug_horiz;
+		old_uf_horiz=uf_horiz;
+
+		[K_ff_horiz,K_fs_horiz,p_f_horiz,d_f_horiz,kmax_horiz]=SystemMatrices(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters);
+		ys=CreateNodalConstraints(femmodel.nodes,configuration_type);
+		p_f_horiz = Reduceload( p_f_horiz, K_fs_horiz, ys);
+
+		uf_horiz=Solver(K_ff_horiz,p_f_horiz,old_uf_horiz,d_f_horiz,femmodel.parameters);
+		ug_horiz= Mergesolutionfromftog( uf_horiz, ys, femmodel.nodes,femmodel.parameters); 
+
+		[femmodel.elements,femmodel.materials]=InputUpdateFromSolution(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,ug_horiz);
+
+		%Figure out if convergence have been reached
+		converged=convergence(K_ff_horiz,p_f_horiz,uf_horiz,old_uf_horiz,femmodel.parameters);
+
+		%Then compute vertical velocity
+		femmodel=SetCurrentConfiguration(femmodel,DiagnosticVertAnalysisEnum);
+		configuration_type=femmodel.parameters.ConfigurationType;
+
+		[K_ff_vert,K_fs_vert,p_f_vert,d_f_vert,kmax_vert]=SystemMatrices(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters);
+		ys=CreateNodalConstraints(femmodel.nodes,configuration_type);
+		p_f_vert = Reduceload( p_f_vert, K_fs_vert, ys);
+
+		uf_vert=Solver(K_ff_vert,p_f_vert,[],d_f_vert,femmodel.parameters);
+		ug_vert= Mergesolutionfromftog( uf_vert, ys, femmodel.nodes,femmodel.parameters); 
+
+		[femmodel.elements,femmodel.materials]=InputUpdateFromSolution(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,ug_vert);
+
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/solvers/solver_thermal_nonlinear.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/solvers/solver_thermal_nonlinear.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/solvers/solver_thermal_nonlinear.m	(revision 11330)
@@ -0,0 +1,53 @@
+function femmodel=solver_thermal_nonlinear(femmodel)
+%SOLVER_THERMAL_NONLINEAR - core of thermal solution sequence.
+%   femmodel is returned together with temperature and melting_offset, in case loads have been modified
+%
+%   Usage:
+%      [femmodel]=solver_thermal_nonlinear(femmodel)
+
+	count=1;
+	converged=0;
+
+	%Get parameters
+	configuration_type=femmodel.parameters.ConfigurationType;
+	thermal_maxiter=femmodel.parameters.ThermalMaxiter;
+
+	issmprintf(VerboseConvergence(),'\n%s',['   starting direct shooting method']);
+
+	%Reset penalties and initialize convergence as false
+	[femmodel.elements loads]=InputUpdateFromConstant(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,0,ConvergedEnum);
+	[femmodel.elements femmodel.loads]=InputUpdateFromConstant(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,1,ResetPenaltiesEnum);
+
+	%update constraints
+	[femmodel.nodes]=UpdateConstraints(femmodel.nodes,femmodel.constraints,femmodel.parameters);
+
+	while(~converged),
+
+		[K_ff,K_fs,p_f,d_f,melting_offset]=SystemMatrices(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters);
+		ys=CreateNodalConstraints(femmodel.nodes,configuration_type);
+		p_f = Reduceload( p_f, K_fs, ys);
+
+		issmprintf(VerboseSolver(),'%s%g','   condition number of stiffness matrix: ',condest(K_ff));
+		t_f=Solver(K_ff,p_f,[],d_f,femmodel.parameters);
+		t_g= Mergesolutionfromftog( t_f, ys, femmodel.nodes,femmodel.parameters); 
+
+		[femmodel.elements,femmodel.materials]=InputUpdateFromSolution(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,t_g);
+		[femmodel.loads,constraints_converged,num_unstable_constraints] =ConstraintsState(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads, femmodel.materials,femmodel.parameters);
+	
+		if ~converged,
+			issmprintf(VerboseConvergence(),'%s%i','   #unstable constraints ',num_unstable_constraints);
+			if num_unstable_constraints<=femmodel.parameters.ThermalPenaltyThreshold,
+				converged=1;
+			end
+		end
+		if(count>thermal_maxiter),
+			issmprintf(true,'%s%i%s','      maximum number of iterations ',thermal_maxiter,' exceeded');
+			break;
+		end
+		[femmodel.elements loads]=InputUpdateFromConstant(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,double(converged),ConvergedEnum);
+		count=count+1;
+	end
+
+	[femmodel.elements,femmodel.materials]=InputUpdateFromSolution(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,t_g);
+	[femmodel.elements femmodel.loads]=InputUpdateFromConstant(femmodel.elements,femmodel.nodes,femmodel.vertices,femmodel.loads,femmodel.materials,femmodel.parameters,melting_offset,MeltingOffsetEnum);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Analysis/plot_basins.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Analysis/plot_basins.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Analysis/plot_basins.m	(revision 11330)
@@ -0,0 +1,14 @@
+%run in top level Agu09.
+
+figure(1),clf,hold on;
+
+%domain=expread('Exp/DomainOutline50km.exp',1);
+%plot(domain.x,domain.y,'k-');
+
+list=listfiles;
+for i=1:length(list),
+	name=list{i};
+	contour=expread(name,1);
+	plot(contour.x,contour.y,'r-');
+	text(mean(contour.x),mean(contour.y),num2str(name(1:end-4)),'FontSize',18);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Analysis/setcluster.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Analysis/setcluster.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Analysis/setcluster.m	(revision 11330)
@@ -0,0 +1,7 @@
+function md=setcluster(md,cluster);
+%SETCLUSTER - set cluster parameters from structure
+%
+%   Usage:
+%      md=setcluster(md,cluster);
+
+md.cluster=cluster;
Index: /issm/trunk-jpl-damage/src/m/utils/Array/allempty.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/allempty.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/allempty.m	(revision 11330)
@@ -0,0 +1,22 @@
+%
+%  function to return an empty cell array if all array elements are empty
+%
+%  function [cout]=allempty(cin)
+%
+function [cout]=allempty(cin)
+
+if ~nargin
+    help allempty
+    return
+end
+
+for j=1:numel(cin)
+    if ~isempty(cin{j})
+        cout=cin;
+        return
+    end
+end
+cout={};
+
+end
+
Index: /issm/trunk-jpl-damage/src/m/utils/Array/allequal.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/allequal.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/allequal.m	(revision 11330)
@@ -0,0 +1,70 @@
+%
+%  function to return an empty array if all array elements are
+%  equal to the given value, which may also be empty but not nan.
+%
+%  (note that by definition, nan is not equal to nan.  this could
+%  be changed by using isequalwithequalnans.)
+%
+%  function [aout]=allequal(ain,aval)
+%
+function [aout]=allequal(ain,aval)
+
+if ~nargin
+    help allequal
+    return
+end
+
+aout=ain;
+
+if     islogical(ain) && islogical(aval)
+    for i=1:numel(ain)
+        if ~isequal(ain(i),aval)
+            return
+        end
+    end
+    aout=logical([]);
+
+elseif isnumeric(ain) && isnumeric(aval)
+    for i=1:numel(ain)
+        if ~isequal(ain(i),aval)
+            return
+        end
+    end
+    aout=[];
+
+elseif ischar(ain) && ischar(aval)
+    for i=1:size(ain,1)
+        if ~strcmp(ain(i,:),aval)
+            return
+        end
+    end
+    aout='';
+
+elseif iscell(ain)
+    if     islogical(aval)
+        for i=1:numel(ain)
+            if ~islogical(ain{i}) || ~isequal(ain{i},aval)
+                return
+            end
+        end
+        aout={};
+
+    elseif isnumeric(aval)
+        for i=1:numel(ain)
+            if ~isnumeric(ain{i}) || ~isequal(ain{i},aval)
+                return
+            end
+        end
+        aout={};
+
+    elseif ischar(aval)
+        for i=1:size(ain,1)
+            if ~ischar(ain{i}) || ~strcmp(ain{i},aval)
+                return
+            end
+        end
+        aout={};
+    end
+end
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Array/allnan.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/allnan.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/allnan.m	(revision 11330)
@@ -0,0 +1,22 @@
+%
+%  function to return an empty double array if all array elements are NaN
+%
+%  function [dout]=allnan(din)
+%
+function [dout]=allnan(din)
+
+if ~nargin
+    help allnan
+    return
+end
+
+for i=1:numel(din)
+    if ~isnan(din(i))
+        dout=din;
+        return
+    end
+end
+dout=[];
+
+end
+
Index: /issm/trunk-jpl-damage/src/m/utils/Array/any2str.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/any2str.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/any2str.m	(revision 11330)
@@ -0,0 +1,22 @@
+%
+%  function to convert anything to a string
+%
+%  function [svec]=any2str(a,alim)
+%
+function [svec]=any2str(a,alim)
+
+if ~exist('alim','var') || (numel(a) <= alim)
+    if iscell(a)
+        svec=string_cell(a);
+    else
+        if (numel(a) > 1) && ~ischar(a)
+            svec=string_vec(a);
+        else
+            svec=item2str(a);
+        end
+    end
+else
+	svec=[string_size(a) ' ''' class(a) ''''];
+end
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Array/array_numel.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/array_numel.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/array_numel.m	(revision 11330)
@@ -0,0 +1,35 @@
+%
+%  function to find a number of elements from a list of arrays.
+%  
+%  [asize]=array_numel(varargin)
+%
+%  see array_size to check the number and shape of elements, if
+%  multiple indices will be used.
+%
+function [anum]=array_numel(varargin)
+
+anum=1;
+
+for iarg=1:nargin
+    if ischar(varargin{iarg})
+        inum=numel(cellstr(varargin{iarg}));
+    else
+        inum=numel(varargin{iarg});
+    end
+    
+    if ~isequal(inum,1)
+        if isequal(anum,1)
+            anum=inum;
+        else
+            if ~isequal(inum,anum)
+                if ~isempty(inputname(iarg))
+                    error('Array ''%s'' has inconsistent number of elements.',inputname(iarg));
+                else
+                    error('Array %d has inconsistent number of elements.',iarg);
+                end
+            end
+        end
+    end
+end
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Array/array_size.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/array_size.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/array_size.m	(revision 11330)
@@ -0,0 +1,35 @@
+%
+%  function to find an array size from a list of arrays.
+%  
+%  [asize]=array_size(varargin)
+%
+%  see array_numel to check only the number of elements, if
+%  single indices will be used.
+%
+function [asize]=array_size(varargin)
+
+asize=[1 1];
+
+for iarg=1:nargin
+    if ischar(varargin{iarg})
+        isize=size(cellstr(varargin{iarg}));
+    else
+        isize=size(varargin{iarg});
+    end
+    
+    if ~isequal(isize,[1 1])
+        if isequal(asize,[1 1])
+            asize=isize;
+        else
+            if ~isequal(isize,asize)
+                if ~isempty(inputname(iarg))
+                    error('Array ''%s'' has inconsistent size.',inputname(iarg));
+                else
+                    error('Array %d has inconsistent size.',iarg);
+                end
+            end
+        end
+    end
+end
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Array/find_string.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/find_string.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/find_string.m	(revision 11330)
@@ -0,0 +1,18 @@
+%
+%  function to find a string in a cell array
+%  (could probably be replaced by matlab strmatch)
+%  
+%  [ifound]=find_string(cells,str)
+%
+function [ifound]=find_string(cells,str)
+
+ifound=false;
+
+for i=1:numel(cells)
+    if ischar(cells{i}) && strcmp(cells{i},str)
+        ifound=i;
+        return
+    end
+end
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Array/item2str.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/item2str.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/item2str.m	(revision 11330)
@@ -0,0 +1,31 @@
+%
+%  function to convert an item to a string
+%
+%  function [svec]=item2str(a)
+%
+function [svec]=item2str(a)
+
+if     islogical(a)
+    if a
+        svec='true';
+    else
+        svec='false';
+    end
+elseif ischar(a)
+    svec=['''' a ''''];
+elseif isnumeric(a)
+    svec=num2str(a);
+else
+    if ~isempty(inputname(1))
+        warning('item2str:item_unrecog',...
+            'Item ''%s'' is of unrecognized type ''%s''.',...
+            inputname(1),class(a));
+    else
+        warning('item2str:item_unrecog',...
+            'Item %d is of unrecognized type ''%s''.',...
+            1,class(a));
+    end
+    return
+end
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Array/rotateticklabel.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/rotateticklabel.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/rotateticklabel.m	(revision 11330)
@@ -0,0 +1,69 @@
+function th=rotateticklabel(h,rot,demo)
+%ROTATETICKLABEL rotates tick labels
+%   TH=ROTATETICKLABEL(H,ROT) is the calling form where H is a handle to
+%   the axis that contains the XTickLabels that are to be rotated. ROT is
+%   an optional parameter that specifies the angle of rotation. The default
+%   angle is 90. TH is a handle to the text objects created. For long
+%   strings such as those produced by datetick, you may have to adjust the
+%   position of the axes so the labels don't get cut off.
+%
+%   Of course, GCA can be substituted for H if desired.
+%
+%   TH=ROTATETICKLABEL([],[],'demo') shows a demo figure.
+%
+%   Known deficiencies: if tick labels are raised to a power, the power
+%   will be lost after rotation.
+%
+%   See also datetick.
+
+%   Written Oct 14, 2005 by Andy Bliss
+%   Copyright 2005 by Andy Bliss
+
+%DEMO:
+if nargin==3
+    x=[now-.7 now-.3 now];
+    y=[20 35 15];
+    figure
+    plot(x,y,'.-')
+    datetick('x',0,'keepticks')
+    h=gca;
+    set(h,'position',[0.13 0.35 0.775 0.55])
+    rot=90;
+end
+
+%set the default rotation if user doesn't specify
+if nargin==1
+    rot=90;
+end
+%make sure the rotation is in the range 0:360 (brute force method)
+while rot>360
+    rot=rot-360;
+end
+while rot<0
+    rot=rot+360;
+end
+%get current tick labels
+a=get(h,'XTickLabel');
+%erase current tick labels from figure
+set(h,'XTickLabel',[]);
+%get tick label positions
+b=get(h,'XTick');
+c=get(h,'YTick');
+%make new tick labels
+%  must consider yscale (jes, 9/14/10)
+switch lower(get(h,'YScale'))
+    case 'linear'
+        if rot<180
+            th=text(b,repmat(c(1)-.1*(c(2)-c(1)),length(b),1),a,'HorizontalAlignment','right','rotation',rot,'Interpreter','none');
+        else
+            th=text(b,repmat(c(1)-.1*(c(2)-c(1)),length(b),1),a,'HorizontalAlignment','left','rotation',rot,'Interpreter','none');
+        end
+    case 'log'
+        if rot<180
+            th=text(b,repmat(10^(log10(c(1))-.1*(log10(c(2))-log10(c(1)))),length(b),1),a,'HorizontalAlignment','right','rotation',rot,'Interpreter','none');
+        else
+            th=text(b,repmat(10^(log10(c(1))-.1*(log10(c(2))-log10(c(1)))),length(b),1),a,'HorizontalAlignment','left','rotation',rot,'Interpreter','none');
+        end
+    otherwise
+        set(h,'XTickLabel',a);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Array/str2int.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/str2int.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/str2int.m	(revision 11330)
@@ -0,0 +1,46 @@
+%
+%  function to find and read the first or last positive integer
+%  in a character string.
+%
+%  function [aint]=str2int(astr,cfl)
+%
+function [aint]=str2int(astr,cfl);
+
+aint=[];
+
+if     ~exist('cfl','var') || strncmpi(cfl,'f',1)
+    i=1;
+
+    while (i <= length(astr))
+        if (astr(i) >= '0' && astr(i) <= '9')
+            aint=sscanf(astr(i:length(astr)),'%d',[1,1]);
+            return
+        else
+            i=i+1;
+        end
+	end
+
+elseif strncmpi(cfl,'l',1)
+    i=length(astr);
+    ifound=false;
+
+    while (i >= 1)
+        if     (astr(i) >= '0' && astr(i) <= '9')
+            ifound=true;
+            i=i-1;
+        elseif ~ifound
+            i=i-1;
+        else
+            aint=sscanf(astr(i+1:length(astr)),'%d',[1,1]);
+            return
+        end
+	end
+
+    if ifound
+        aint=sscanf(astr,'%d',[1,1]);
+        return
+    end
+end
+
+end
+
Index: /issm/trunk-jpl-damage/src/m/utils/Array/string_cell.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/string_cell.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/string_cell.m	(revision 11330)
@@ -0,0 +1,26 @@
+%
+%  function to return the string of a cell array
+%
+%  function [svec]=string_cell(a)
+%
+function [svec]=string_cell(a)
+
+if ~nargin
+    help string_cell
+    return
+end
+
+if (numel(a) == 0)
+    svec='{}';
+    return
+end
+
+%  assemble string for output
+
+svec ='{';
+for i=1:numel(a)-1;
+    svec=[svec item2str(a{i}) ' '];
+end
+svec=[svec item2str(a{end}) '}'];
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Array/string_dim.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/string_dim.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/string_dim.m	(revision 11330)
@@ -0,0 +1,72 @@
+%
+%  function to return the string dimension of an array element
+%
+%  function [sdim]=string_dim(a,idim,varargin)
+%
+function [sdim]=string_dim(a,idim,varargin)
+
+if ~nargin
+    help string_dim
+    return
+end
+
+%  check for scalar
+
+if (numel(a) == 1) && (idim == 1)
+    sdim='';
+    return
+end
+
+%  check for overflow
+
+if (idim > numel(a))
+    if ~isempty(inputname(1))
+        error('Index %d exceeds number of elements in array ''%s''.',...
+            idim,inputname(1));
+    else
+        error('Index %d exceeds number of elements in array %d.',...
+            idim,1);
+    end
+end
+
+%  check for column or row vector (Matlab uses a minimum of two
+%  dimensions, so this won't match Matlab standard output)
+
+for iarg=1:nargin-2
+    if strcmpi(varargin{iarg},'vector')
+        if (ndims(a) == 2) && ((size(a,1) == 1) || (size(a,2) == 1))
+            sdim =['(' num2str(idim) ')'];
+            return
+        end
+    end
+end
+
+%  do the general case
+
+asize=size(a);
+index=zeros(size(asize));
+aprod=prod(asize);
+idim =idim-1;
+
+%  calculate indices base 0 and convert to base 1
+
+%  note that ind2sub might be useful, except that it requires a list
+%  of scalars rather than a vector for output.
+
+for i=length(asize):-1:1
+    aprod=aprod/asize(i);
+    index(i)=floor(idim/aprod);
+    idim=idim-index(i)*aprod;
+end
+index=index+1;
+
+%  assemble string for output
+
+sdim ='(';
+for i=1:length(asize)-1;
+    sdim =[sdim num2str(index(i)) ','];
+end
+sdim =[sdim num2str(index(end)) ')'];
+
+end
+
Index: /issm/trunk-jpl-damage/src/m/utils/Array/string_size.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/string_size.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/string_size.m	(revision 11330)
@@ -0,0 +1,38 @@
+%
+%  function to return the string size of an array
+%
+%  function [ssize]=string_size(a,varargin)
+%
+function [ssize]=string_size(a,varargin)
+
+if ~nargin
+    help string_size
+    return
+end
+
+%  check for column or row vector (Matlab uses a minimum of two
+%  dimensions, so this won't match Matlab standard output)
+
+for iarg=1:nargin-1
+    if strcmpi(varargin{iarg},'vector')
+        if (ndims(a) == 2) && ((size(a,1) == 1) || (size(a,2) == 1))
+            ssize =['(' num2str(numel(a)) ')'];
+            return
+        end
+    end
+end
+
+%  do the general case
+
+asize=size(a);
+
+%  assemble string for output
+
+ssize ='(';
+for i=1:length(asize)-1;
+    ssize =[ssize num2str(asize(i)) 'x'];
+end
+ssize =[ssize num2str(asize(end)) ')'];
+
+end
+
Index: /issm/trunk-jpl-damage/src/m/utils/Array/string_vec.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/string_vec.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/string_vec.m	(revision 11330)
@@ -0,0 +1,26 @@
+%
+%  function to return the string of an vector
+%
+%  function [svec]=string_vec(a)
+%
+function [svec]=string_vec(a)
+
+if ~nargin
+    help string_vec
+    return
+end
+
+if (numel(a) == 0)
+    svec='[]';
+    return
+end
+
+%  assemble string for output
+
+svec ='[';
+for i=1:numel(a)-1;
+    svec=[svec item2str(a(i)) ' '];
+end
+svec=[svec item2str(a(end)) ']'];
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Array/struc_class.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/struc_class.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/struc_class.m	(revision 11330)
@@ -0,0 +1,30 @@
+%
+%  function to find the structural fields of a specified class
+%  
+%  [sclasso]=struc_class(sclass,cstr)
+%
+function [sclasso]=struc_class(sclass,cstr)
+
+%  collect only the objects of the appropriate class
+
+if     isa(sclass,cstr)
+    if ~isempty(inputname(1))
+        sclasso.(inputname(1))=sclass;
+    else
+        sclasso.(cstr)        =sclass;
+    end
+
+elseif isstruct(sclass)
+    fnames=fieldnames(sclass);
+    for i=1:numel(fnames)
+        if isa(sclass.(fnames{i}),cstr)
+            sclasso.(fnames{i})=sclass.(fnames{i});
+        end
+    end
+end
+
+if ~exist('sclasso','var')
+    sclasso=struct([]);
+end
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Array/struc_desc.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Array/struc_desc.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Array/struc_desc.m	(revision 11330)
@@ -0,0 +1,61 @@
+%
+%  function to find the structures with the specified descriptors
+%  
+%  [sarrayo]=struc_desc(sarray,varargin)
+%
+function [sarrayo]=struc_desc(sarray,varargin)
+
+if ~isfield(sarray,'descriptor')
+    if ~isempty(inputname(1))
+        error('Field ''descriptor'' not found in array ''%s''.',inputname(1));
+    else
+        error('Field ''descriptor'' not found in array %d.',1);
+    end
+end
+
+sarrayo=struct([]);
+
+for iarg=1:nargin-1
+    if     iscell(varargin{iarg})
+        desc=        varargin{iarg};
+    elseif ischar(varargin{iarg})
+        desc=cellstr(varargin{iarg});
+    end
+    
+    for i=1:length(desc)
+        sarrayoi=struc_desci(sarray,desc{i});
+        if ~isempty(sarrayoi)
+            if isempty(sarrayo)
+                sarrayo       =sarrayoi;
+            else
+                sarrayo(end+1)=sarrayoi;
+            end
+        end
+    end
+end
+
+%  if nothing found, return whole array
+
+if isempty(sarrayo)
+    sarrayo=sarray;
+end
+
+end
+
+%
+%  function to find the structure with the specified descriptor
+%  
+function [sarrayo]=struc_desci(sarray,str)
+
+sarrayo=struct([]);
+
+for i=1:numel(sarray)
+    if strcmp(sarray(i).descriptor,str)
+        sarrayo=sarray(i);
+        return
+    end
+end
+
+warning(['String ''' str ''' not found in array ''' inputname(1) '''.']);
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/BC/SetIceSheetBC.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/BC/SetIceSheetBC.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/BC/SetIceSheetBC.m	(revision 11330)
@@ -0,0 +1,68 @@
+function md=SetIceSheetBC(md)
+%SETICESHEETBC - Create the boundary conditions for diagnostic and thermal models for an IceSheet with no Ice Front
+%
+%   Usage:
+%      md=SetIceSheetBC(md)
+%
+%   See also: SETICESHELFBC, SETMARINEICESHEETBC
+
+%node on Dirichlet
+pos=find(md.mesh.vertexonboundary);
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.spcvz(pos)=0;
+md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+
+%Dirichlet Values
+if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
+	disp('      boundary conditions for diagnostic model: spc set as observed velocities');
+	md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos);
+else
+	disp('      boundary conditions for diagnostic model: spc set as zero');
+end
+
+%segment on neumann (Ice Front) -> none
+if (md.mesh.dimension==2)
+	md.diagnostic.icefront=zeros(0,4);
+else
+	md.diagnostic.icefront=zeros(0,6);
+end
+
+%Create zeros basal melting rate and surface mass balance if not specified
+if isnan(md.surfaceforcings.accumulation_rate),
+	md.surfaceforcings.accumulation_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.accumulation_rate specified: values set as zero');
+end
+if isnan(md.surfaceforcings.ablation_rate),
+	md.surfaceforcings.ablation_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.ablation_rate specified: values set as zero');
+end
+if isnan(md.surfaceforcings.mass_balance),
+	md.surfaceforcings.mass_balance=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.mass_balance specified: values set as zero');
+end
+if isnan(md.basalforcings.melting_rate),
+	md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no basalforcings.melting_rate specified: values set as zero');
+end
+if isnan(md.balancethickness.thickening_rate),
+	md.balancethickness.thickening_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no balancethickness.thickening_rate specified: values set as zero');
+end
+
+md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+
+if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
+		md.basalforcings.geothermalflux=50*10^-3*ones(md.mesh.numberofvertices,1); %50 mW/m^2
+	end
+else
+	disp('      no thermal boundary conditions created: no observed temperature found');
+end
Index: /issm/trunk-jpl-damage/src/m/utils/BC/SetIceShelfBC.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/BC/SetIceShelfBC.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/BC/SetIceShelfBC.m	(revision 11330)
@@ -0,0 +1,100 @@
+function md=SetIceShelfBC(md,varargin)
+%SETICESHELFBC - Create the boundary conditions for diagnostic and thermal models for a  Ice Shelf with Ice Front
+%
+%   Neumann BC are used on the ice front (an ANRGUS contour around the ice front
+%   must be given in input)
+%   Dirichlet BC are used elsewhere for diagnostic
+%
+%   Usage:
+%      md=SetIceShelfBC(md,varargin)
+%
+%   Example:
+%      md=SetIceShelfBC(md);
+%      md=SetIceShelfBC(md,'Front.exp');
+%
+%   See also: SETICESHEETBC, SETMARINEICESHEETBC
+
+%node on Dirichlet (boundary and ~icefront)
+if nargin==2,
+	icefrontfile=varargin{1};
+	if ~exist(icefrontfile), error(['SetIceShelfBC error message: ice front file ' icefrontfile ' not found']); end
+	nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2);
+	nodeonicefront=double(md.mesh.vertexonboundary & nodeinsideicefront);
+elseif nargin==1,
+	nodeonicefront=zeros(md.mesh.numberofvertices,1);
+else
+	help SetIceShelfBC
+	error('bad usage');
+end
+pos=find(md.mesh.vertexonboundary & ~nodeonicefront);
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.spcvz(pos)=0;
+md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+
+%Dirichlet Values
+if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
+	disp('      boundary conditions for diagnostic model: spc set as observed velocities');
+	md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos);
+else
+	disp('      boundary conditions for diagnostic model: spc set as zero');
+end
+
+%segment on Ice Front
+%segment on Neumann (Ice Front)
+pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2)));
+if (md.mesh.dimension==2)
+	pressureload=md.mesh.segments(pos,:);
+elseif md.mesh.dimension==3
+	pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
+	pressureload=[];
+	for i=1:md.mesh.numberoflayers-1,
+		pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
+	end
+end
+
+%Add water or air enum depending on the element
+pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))];
+
+%plug onto model
+md.diagnostic.icefront=pressureload;
+
+%Create zeros basalforcings.melting_rate, surfaceforcings.ablation_rate, surfaceforcings.accumulation_rate
+% and surfaceforcings.mass_balance if not specified
+if isnan(md.surfaceforcings.accumulation_rate),
+	md.surfaceforcings.accumulation_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.accumulation_rate specified: values set as zero');
+end
+if isnan(md.surfaceforcings.ablation_rate),
+	md.surfaceforcings.ablation_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.ablation_rate specified: values set as zero');
+end
+if isnan(md.surfaceforcings.mass_balance),
+	md.surfaceforcings.mass_balance=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.mass_balance specified: values set as zero');
+end
+if isnan(md.basalforcings.melting_rate),
+	md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no basalforcings.melting_rate specified: values set as zero');
+end
+if isnan(md.balancethickness.thickening_rate),
+	md.balancethickness.thickening_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no balancethickness.thickening_rate specified: values set as zero');
+end
+
+md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+
+if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
+		md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
+	end
+else
+	disp('      no thermal boundary conditions created: no observed temperature found');
+end
Index: /issm/trunk-jpl-damage/src/m/utils/BC/SetMarineIceSheetBC.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/BC/SetMarineIceSheetBC.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/BC/SetMarineIceSheetBC.m	(revision 11330)
@@ -0,0 +1,112 @@
+function md=SetMarineIceSheetBC(md,varargin)
+%SETICEMARINESHEETBC - Create the boundary conditions for diagnostic and thermal models for a  Marine Ice Sheet with Ice Front
+%
+%   Neumann BC are used on the ice front (an ARGUS contour around the ice front
+%   can be given in input, or it will be deduced as onfloatingice & onboundary)
+%   Dirichlet BC are used elsewhere for diagnostic
+%
+%   Usage:
+%      md=SetMarineIceSheetBC(md,icefrontfile)
+%      md=SetMarineIceSheetBC(md)
+%
+%   Example:
+%      md=SetMarineIceSheetBC(md,'Front.exp')
+%      md=SetMarineIceSheetBC(md)
+%
+%   See also: SETICESHELFBC, SETMARINEICESHEETBC
+
+%node on Dirichlet (boundary and ~icefront)
+if nargin==2,
+	%User provided Front.exp, use it
+	icefrontfile=varargin{1};
+	if ~exist(icefrontfile)
+		error(['SetMarineIceSheetBC error message: ice front file ' icefrontfile ' not found']);
+	end
+	nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2);
+	vertexonicefront=double(md.mesh.vertexonboundary & nodeinsideicefront);
+else
+	%Guess where the ice front is
+	vertexonfloatingice=zeros(md.mesh.numberofvertices,1);
+	vertexonfloatingice(md.mesh.elements(find(md.mask.elementonfloatingice),:))=1;
+	vertexonicefront=double(md.mesh.vertexonboundary & vertexonfloatingice);
+end
+pos=find(md.mesh.vertexonboundary & ~vertexonicefront);
+if isempty(pos),
+	warning('SetMarineIceSheetBC warning: ice front all around the glacier, no dirichlet found. Dirichlet must be added manually')
+end
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.spcvz(pos)=0;
+md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+
+%Dirichlet Values
+if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
+	disp('      boundary conditions for diagnostic model: spc set as observed velocities');
+	md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos);
+else
+	disp('      boundary conditions for diagnostic model: spc set as zero');
+end
+
+md.hydrology.spcwatercolumn=zeros(md.mesh.numberofvertices,2);
+pos=find(md.mesh.vertexonboundary); 
+md.hydrology.spcwatercolumn(pos,1)=1;
+
+%segment on Neumann (Ice Front)
+pos=find(vertexonicefront(md.mesh.segments(:,1)) | vertexonicefront(md.mesh.segments(:,2)));
+if (md.mesh.dimension==2)
+	pressureload=md.mesh.segments(pos,:);
+elseif md.mesh.dimension==3
+	pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
+	pressureload=[];
+	for i=1:md.mesh.numberoflayers-1,
+		pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
+	end
+end
+
+%Add water or air enum depending on the element
+pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))+ 0*md.mask.elementongroundedice(pressureload(:,end))];
+
+%plug onto model
+md.diagnostic.icefront=pressureload;
+
+
+%Create zeros basalforcings.melting_rate, surfaceforcings.ablation_rate, surfaceforcings.accumulation_rate
+% and surfaceforcings.mass_balance if not specified
+if isnan(md.surfaceforcings.accumulation_rate),
+	md.surfaceforcings.accumulation_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.accumulation_rate specified: values set as zero');
+end
+if isnan(md.surfaceforcings.ablation_rate),
+	md.surfaceforcings.ablation_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.ablation_rate specified: values set as zero');
+end
+if isnan(md.surfaceforcings.mass_balance),
+	md.surfaceforcings.mass_balance=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.mass_balance specified: values set as zero');
+end
+if isnan(md.basalforcings.melting_rate),
+	md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no basalforcings.melting_rate specified: values set as zero');
+end
+if isnan(md.balancethickness.thickening_rate),
+	md.balancethickness.thickening_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no balancethickness.thickening_rate specified: values set as zero');
+end
+
+md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+
+if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
+		md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
+		md.basalforcings.geothermalflux(find(md.mask.vertexongroundedice))=50*10^-3; %50mW/m2
+	end
+else
+	disp('      no thermal boundary conditions created: no observed temperature found');
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Basins/basinzoom.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Basins/basinzoom.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Basins/basinzoom.m	(revision 11330)
@@ -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([issmdir '/projects/ModelData/Names/Names.mat']);
+		
+%Go through names: 
+found=0;
+for i=1:size(names,1),
+	if strcmpi(names{i,1},basin),
+		%ok, we've got the region. Get lat and long: 
+		long=names{i,2};
+		lat=names{i,3};
+		hemisphere=names{i,4};
+		found=1;
+		break;
+	end
+end
+
+if ~found,
+	error(['basinzoom error message: cannot find basin ' basin '. Use isbasin to determine a basin name.']);
+end
+
+if hemisphere==+1,
+	central_meridian=getfieldvalue(options,'central_meridian',45);
+	standard_parallel=getfieldvalue(options,'standard_parallel',70);
+else
+	central_meridian=getfieldvalue(options,'central_meridian',0);
+	standard_parallel=getfieldvalue(options,'standard_parallel',71);
+end
+
+%Transform lat long into x,y: 
+[xc,yc]=ll2xy(lat,long,hemisphere,central_meridian,standard_parallel);
+
+%compute x0,x1 and y0,y1 using basindeltax and basindeltay
+x0=xc-basindeltax/2;
+x1=xc+basindeltax/2;
+y0=yc-basindeltay/2;
+y1=yc+basindeltay/2;
+
+if ~isnan(unitmultiplier)
+	x0=x0*unitmultiplier;
+	x1=x1*unitmultiplier;
+	y0=y0*unitmultiplier;
+	y1=y1*unitmultiplier;
+end
+
+%if output arguments are present, return the limits, 
+%otherwise, set them on the current graphic. 
+if nargout==2,
+	found=1;
+	varargout{1}=[x0 x1];
+	varargout{2}=[y0 y1];
+else
+	xlim([x0 x1]);
+	ylim([y0 y1]);
+	found=1;
+	daspect([1;1;1]);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Basins/isbasin.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Basins/isbasin.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Basins/isbasin.m	(revision 11330)
@@ -0,0 +1,19 @@
+function isbasin(name)
+%ISBASIN: figure out if a basin name exists.
+%
+%
+%        Usage:  index=isbasin('jks');
+%
+%
+
+
+%First, load basin names:
+load([issmdir '/projects/ModelData/Names/Names.mat']);
+
+
+%go through names: 
+for i=1:length(names),
+	if ~isempty(strfind(names{i,1},name)),
+		disp(['''' names{i,1} ''' Long:' num2str(names{i,2}) ' Lat:' num2str(names{i,3}) ]);
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Basins/plotbasins.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Basins/plotbasins.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Basins/plotbasins.m	(revision 11330)
@@ -0,0 +1,18 @@
+%display all the domain outlines in a directory
+
+basins=listfiles;
+
+hold on
+for i=1:length(basins), 
+	%check whether this is a .exp file
+	basin=basins{i};
+	if strcmpi(basin(end-3:end),'.exp'),
+
+		contour=expread(basin,0);
+		x=contour(1).x;
+		y=contour(1).y;
+		x0=mean(x); y0=mean(y);
+		text(x0,y0,basin(1:end-4),'Fontsize',14);
+		expdisp(basin);
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Basins/showbasins.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Basins/showbasins.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Basins/showbasins.m	(revision 11330)
@@ -0,0 +1,69 @@
+function showbasins(varargin)
+%SHOWBASINS - return basins that are within the xlim and ylim
+%
+%   Usage:
+%      names=showbasins(options);
+%   Options: 
+%      'unit' default 1
+%      'hemisphere': default +1;
+%      'central_meridian: 45 for Greenland and 0 for Antarctica
+%      'standard_parallel: 70 for Greenland and 71 for Antarctica
+%
+
+%is varargin an options database already?
+if nargin==0,
+	options=pairoptions(varargin{:});
+elseif (isa(varargin{1},'plotoptions') | isa(varargin{1},'pairoptions')),
+	%do nothing to the varargin: 
+	options=varargin{1};
+else
+	%process varargin for options: 
+	options=pairoptions(varargin{:});
+end
+
+
+%recover some options, and set defaults
+unitmultiplier=getfieldvalue(options,'unit',1);
+fontsize=getfieldvalue(options,'fontsize',12);
+hemisphere=getfieldvalue(options,'hemisphere');
+
+if strcmpi(hemisphere,'s'),
+	hemisphere=-1;
+elseif strcmpi(hemisphere,'n'),
+	hemisphere=+1;
+else
+	error('showbasins error message: hemispehre should be either ''n'' or ''s''');
+	end
+
+if hemisphere==+1,
+	central_meridian=getfieldvalue(options,'central_meridian',45);
+	standard_parallel=getfieldvalue(options,'standard_parallel',70);
+else
+	central_meridian=getfieldvalue(options,'central_meridian',0);
+	standard_parallel=getfieldvalue(options,'standard_parallel',71);
+end
+
+%Ok, find basin we are talking about: 
+load([issmdir '/projects/ModelData/Names/Names.mat']);
+
+%Get xlim and ylim, and convert into lat,long: 
+xlimits=xlim; x0=xlimits(1); x1=xlimits(2);
+ylimits=ylim; y0=ylimits(1); y1=ylimits(2);
+
+%Convert names lat and long into x,y:
+lat=cell2mat(names(:,3));
+long=cell2mat(names(:,2));
+
+%Now, convert lat,long into x,y:
+[x,y]=ll2xy(lat,long,hemisphere,central_meridian,standard_parallel);
+
+%Find  x,y within xlimits and ylimits: 
+locations=find(x>x0 & x<x1 & y>y0 & y<y1);
+
+%Go through locations, and display the names: 
+for i=1:size(locations,1),
+	hold on,
+	plot(x(locations(i)),y(locations(i)),'r.');
+	t=text(x(locations(i)),y(locations(i)),names{locations(i),1}); 
+	set(t,'FontSize',fontsize);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Cluster/QueueRequirements.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Cluster/QueueRequirements.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Cluster/QueueRequirements.m	(revision 11330)
@@ -0,0 +1,35 @@
+function QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,queue,np,time)
+%QUEUEREQUIREMENTS - queue requirements in time, number of cpus, by name of queue.
+%
+%   Usage: 
+%      QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,np,time)
+
+%Ok, go through requirements for current queue:
+index=ismemberi(queue,available_queues);
+if  ~index,
+	%ok, either we a generic cluster, with 'none' queue, or we could not find the queue reqruirements
+	if strcmpi(available_queues{1},'none'),
+		%reset index to 1, so we can fish the requirements
+		index=1;
+	else
+		string=available_queues{1};
+		for i=2:length(available_queues),
+			string=[string ' ' available_queues{i}];
+		end
+		error(['QueueRequirements error message: availables queues are ' string]);
+	end
+end
+
+%check on time requirements
+rtime=queue_requirements_time(index);
+if time<=0,
+	error('QueueRequirements: time should be a positive number');
+end
+if time>rtime,
+	error(['QueueRequirements: time should be < ' num2str(rtime) ' for queue: ' queue]);
+end
+
+%check on np requirements
+if np<=0,
+	error('QueueRequirements: np should be a positive number');
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Cluster/parallelrange.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Cluster/parallelrange.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Cluster/parallelrange.m	(revision 11330)
@@ -0,0 +1,23 @@
+function [i1,i2]=parallelrange(rank,numprocs,globalsize)
+%PARALLELRANGE - from a rank, and a number of processors, figure out a range, for parallel tasks.
+%
+%   Usage: 
+%      [i1,i1]=parallelrange(rank,numprocs,globalsize)
+
+num_local_rows=zeros(numprocs,1);
+
+for i=1:numprocs,
+	%we use floor. we under distribute rows. The rows left  are then redistributed, therefore resulting in a more even distribution.
+	num_local_rows(i)=floor(globalsize/numprocs);
+end
+
+
+%There may be some rows left. Distribute evenly.
+row_rest=globalsize - numprocs*floor(globalsize/numprocs);
+
+for i=1:row_rest,
+	num_local_rows(i)=num_local_rows(i)+1;
+end
+
+i1=sum(num_local_rows(1:rank-1))+1;
+i2=i1+num_local_rows(rank)-1;
Index: /issm/trunk-jpl-damage/src/m/utils/DataProcessing/CreateDataBoundaries.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/DataProcessing/CreateDataBoundaries.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/DataProcessing/CreateDataBoundaries.m	(revision 11330)
@@ -0,0 +1,43 @@
+function	[Xedge,Yedge,EdgeValues]=CreateDataBoundaries(x_m,y_m,x_matrix,y_matrix,datamatrix);
+%CREATEDATABOUNDARIES - Create values on the edge of the matrix
+%
+%   This function create vectors with coordinates and values to constrain a matrix 
+%   on its edge from a given matrix tiwh data everywhere.
+%   x_m and y_m belongs to the matrix to be constrained
+%   x_matrix, y_matrix belongs to the matrix to be constrained with
+%   datamatrix is the matrix with values for the constraint
+%
+%   Usage:
+%      [Xedge,Yedge,EdgeValues]=CreateDataBoundaries(x_m,y_m,x_matrix,y_matrix,datamatrix);
+% 
+%   See also: TRACKSTOMATRIX, CREATEDATAMATRIX
+
+%Check the consistency of the data matrix
+if(length(x_matrix)~=(size(datamatrix,2)+1) | length(y_matrix)~=(size(datamatrix,1)+1)),
+	error('CreateDataBoundaries error message: size of matrix and vectors to constrained not consistent')
+end
+
+nxglobal=length(x_m);
+nyglobal=length(y_m);
+
+%Create the edgevalues and coordinates
+xedge1=x_m(1)*ones(nyglobal,1);
+xedge2=x_m(2:end-1);
+xedge3=x_m(end)*ones(nyglobal,1);
+xedge4=x_m(2:end-1);
+xedge5=x_m(2)*ones(nyglobal-2,1);
+xedge6=x_m(3:end-2);
+xedge7=x_m(end-1)*ones(nyglobal-2,1);
+xedge8=x_m(3:end-2);
+yedge1=y_m;
+yedge2=y_m(1)*ones(nxglobal-2,1);
+yedge3=y_m;
+yedge4=y_m(end)*ones(nxglobal-2,1);
+yedge5=y_m(2:end-1);
+yedge6=y_m(2)*ones(nxglobal-4,1);
+yedge7=y_m(2:end-1);
+yedge8=y_m(end-1)*ones(nxglobal-4,1);
+
+Xedge=[xedge1;xedge2;xedge3;xedge4;xedge5;xedge6;xedge7;xedge8];
+Yedge=[yedge1;yedge2;yedge3;yedge4;yedge5;yedge6;yedge7;yedge8];
+EdgeValues=DataInterp(x_matrix,y_matrix,datamatrix,Xedge,Yedge);
Index: /issm/trunk-jpl-damage/src/m/utils/DataProcessing/CreateDataMatrix.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/DataProcessing/CreateDataMatrix.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/DataProcessing/CreateDataMatrix.m	(revision 11330)
@@ -0,0 +1,94 @@
+function [Mvalue Mx My]=CreateDataMatrix(x_m,y_m,track_coord,track_values),
+%CREATEDATAMATRIX - Create a map with average values of map 
+%
+%   This routine creates a map with average values of tracks.
+%   x_m1 and y_m1 are two vectors containing the coordinates of the matrix
+%   trac_coord is an exp file containing the coordinates of the tracks (x and y)
+%   trav_values is a vector with the values along the track coordinates
+%
+%   Usage:
+%      [Mvalue Mx My]=CreateDataMatrix(x_m,y_m,track_coord,track_values),
+%
+%   Example:
+%      [Mvalue Mx My]=CreateDataMatrix(x_m,y_m,'trackcoord.exp',thickness_track)
+%
+%   See also: CREATEDATABOUNDARIES, TRACKSTOMATRIX
+
+%Read the points of the tracks
+stru=expread(track_coord,1);
+nods=stru.nods;
+xtracks=stru.x';
+ytracks=stru.y';
+
+%First check that the parameters are ok:
+if (size(track_values,1)~=nods)  || (size(xtracks,2)~=nods) || (size(ytracks,2)~=nods),
+	error('CreateDataMatrix error message : track coordinates and track values must have the same size');
+end
+
+%Compute number of rows and columns
+numrow=size(y_m,1)-1;
+numcol=size(x_m,1)-1;
+
+%Remove useless points of the track
+points=find(track_values==0);
+track_values(points)=[];
+xtracks(points)=[];
+ytracks(points)=[];
+points=find(isnan(track_values));
+track_values(points)=[];
+xtracks(points)=[];
+ytracks(points)=[];
+points=find(track_values<0);
+track_values(points)=[];
+xtracks(points)=[];
+ytracks(points)=[];
+
+points=find(xtracks<x_m(1) | xtracks>x_m(end) | ytracks<y_m(1) | ytracks>y_m(end));
+track_values(points)=[];
+xtracks(points)=[];
+ytracks(points)=[];
+
+%initialize some matrices
+numpoints=zeros(numrow,numcol);
+value=zeros(numrow,numcol);
+coordx=zeros(numrow,numcol);
+coordy=zeros(numrow,numcol);
+
+%Loop over the points of the track
+nel=size(track_values,1);
+fprintf('%s','      track processing progress:   0.00 %');
+for i=1:nel;
+	if mod(i,1000)==0,
+		fprintf('\b\b\b\b\b\b\b')
+		fprintf('%5.2f%s',i/nel*100,' %');
+	end
+
+	x=xtracks(i);
+	y=ytracks(i);
+
+	%get indices for the matrix
+	indexx=max(find(x_m<x));
+	indexy=max(find(y_m<y));
+
+	%get weighing coefficient
+	val=track_values(i);
+
+	%update numoverlap and weights
+	numpoints(indexy,indexx)=numpoints(indexy,indexx)+1;
+	value(indexy,indexx)=value(indexy,indexx)+val;
+	coordx(indexy,indexx)=coordx(indexy,indexx)+x;
+	coordy(indexy,indexx)=coordy(indexy,indexx)+y;
+
+end
+if nel>1000,
+	fprintf('\b\b\b\b\b\b\b\b')
+	fprintf('%4.2f%s\n',100,' %');
+end
+
+%Change the values of numoverlap to 1 if 0 since we are going to devide by this matrix
+numpoints(find(~numpoints))=1;
+
+%Create the center of mass for coordiantes and values.
+Mvalue=value./numpoints;
+Mx=coordx./numpoints;
+My=coordy./numpoints;
Index: /issm/trunk-jpl-damage/src/m/utils/DataProcessing/MisfitDeinterlace.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/DataProcessing/MisfitDeinterlace.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/DataProcessing/MisfitDeinterlace.m	(revision 11330)
@@ -0,0 +1,21 @@
+function Jstruct=MisfitDeinterlace(misfit,type)
+%MISFITDEINTERLACE - deinterlace misfits that are mixed together, using type.
+%
+%   Usage:
+%      Jstruct=MisfitDeinterlace(misfit,type)
+%
+%   Example:
+%      Jstruct=MisfitDeinterlace(md.results.diagnostic.J,md.fit)
+%
+%
+Jstruct=struct();
+
+count=1;
+for i=0:max(type),
+	pos=find(type==i);
+	if length(pos),
+		Jstruct(count).type=i;
+		Jstruct(count).J=misfit(pos);
+		count=count+1;
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/DataProcessing/TracksToMatrix.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/DataProcessing/TracksToMatrix.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/DataProcessing/TracksToMatrix.m	(revision 11330)
@@ -0,0 +1,84 @@
+function [x_f y_f MatData]=TracksToMatrix(xmin,ymin,nx,ny,posting,track_coord,track_values,theta,varargin),
+%TRACKSTOMATRIX - Create a map from tracks
+%
+%   This routine creates a map from tracks using a Kriging algorithm given by the package DACE.
+%   - xmin and ymin are two scalars that are the extreme values of the data matrix one wants to create
+%   - posting is a scalar giving the posting of the matrix to be created in meters
+%   - trac_coord is an Argus file containing the coordinates of the tracks (x and y)
+%   - trav_values is a vector with the values along the track coordinates
+%   - theta is a parameter of the correlation function stricly positive
+%   varagin can contain a matrix of data to constrain the matrix to be created
+%   it shoud contain indices x and y and the matrix
+%
+%   Usage:
+%      [x_ y_f MatData]=TracksToMatrix(xmin,ymin,nx,ny,posting,track_coord,track_values,theta),
+%
+%   Example:
+%      [x_f y_f Thickness]=TracksToMatrix(-10^6,10^6,200,180,1000,'trackcoord.exp',thickness_values,theta),
+%      [x_f y_f Thickness]=TracksToMatrix(-10^6,10^6,200,180,1000,'trackcoord.exp',thickness_values,theta,x_m,y_m,globalthickness),
+%
+%   See also: CREATEDATABOUNDARIES, CREATEDATAMATRIX
+
+%some checks
+if nargin~=8 & nargin~=11,
+	error(' TracksToMatrix error message: wrong number of arguments')
+end
+
+%Add path to dace
+addpath([issmtier() '/externalpackages/dace/install'])
+
+%First create the x_m and y_m fot the matrix
+x_f=[xmin:posting:xmin+posting*nx]';
+y_f=[ymin:posting:ymin+posting*ny]';
+
+%Now create a bigger map we will then truncate
+x_m=[xmin-posting*nx/2:posting:xmin+posting*nx*3/2]';
+y_m=[ymin-posting*ny/2:posting:ymin+posting*ny*3/2]';
+
+%Create DataMatrix with local averaging of tracks
+[Mvalue Mx My]=CreateDataMatrix(x_m,y_m,track_coord,track_values);
+
+%Create vector for these coordinates and values
+Svalue=sparse(Mvalue);
+Sx=sparse(Mx);
+Sy=sparse(My);
+[i,j,Values]=find(Svalue);
+[i,j,X]=find(Sx);
+[i,j,Y]=find(Sy);
+Coord=[X,Y];
+
+%Create boundaries for the track if specified
+if nargin==11,
+	disp('      constain the border of matrix with global matrix');
+	%Find out the elements to counstrain the border
+	x_matrix=varargin{1};
+	y_matrix=varargin{2};
+	datamatrix=varargin{3};
+
+	%Create values on the border of the smaller map
+	[Xedge,Yedge,EdgeValues]=CreateDataBoundaries(x_m,y_m,x_matrix,y_matrix,datamatrix);
+
+	%Create values on the border of the larger map
+	[Xedge2,Yedge2,EdgeValues2]=CreateDataBoundaries(x_f,y_f,x_matrix,y_matrix,datamatrix);
+
+	%Add these values to the track values
+	Values=[Values;EdgeValues;EdgeValues2];
+	Coord=[X,Y;Xedge,Yedge;Xedge2,Yedge2];
+end
+
+%Create model for data
+disp('      create the statiscal model of the data');
+[dmodel,perf]=dacefit(Coord,Values,@regpoly1,@corrgauss,theta);
+
+%Create design site(points where we are looking for the data)
+Points=nodesamp([x_f(1)+posting/2,y_f(1)+posting/2;x_f(end)-posting/2,y_f(end)-posting/2],[length(x_f)-1;length(y_f)-1]);
+
+%Compute data on these points
+disp('      predict the values');
+VecData=predictor(Points,dmodel);
+
+%Reshape to get a matrix
+MatData=reshape(VecData,ny,nx);
+
+%remove DACE path
+rmpath([issmtier() '/externalpackages/dace/install']);
Index: /issm/trunk-jpl-damage/src/m/utils/DataProcessing/addtrack.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/DataProcessing/addtrack.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/DataProcessing/addtrack.m	(revision 11330)
@@ -0,0 +1,156 @@
+function [x_m2 y_m2 values2]=addtrack(x_m1,y_m1,values1,track_coord,track_values,distance,exponent,varargin),
+%ADDTRACK - modify a map to take values of a track
+%
+%   This routine modifies a map to improve it with values of tracks.
+%   This output map has more values than the input one so that the values
+%   of the tracks are relevant.
+%   x_m1 and y_m1 are two vectors containing the coordinates of the matrix
+%   the distance between two points must be the same everywhere
+%   values1 is a matrix of size (y_m1-1)*(x_m1-1)
+%   trac_coord is an exp file containing the coordinates of the tracks (x and y)
+%   trav_values is a vector with the values along the track coordinates
+%   distance indicates the distance from the tracks where points have to be modified
+%   exposant allows to chance the influence of the track and the map
+%   it must be positive and usually is superior to 1.
+%
+%   Usage:
+%      [x_m2 y_m2 values1 values2]=addtrack(x_m1,y_m1,values1,track_coord,track_values,distance,exposant[,subdivision])
+%
+%   Example:
+%      [xnew ynew valuesnew]=addtrack(x_m,y_m,thickness,'trackcoord.exp',thickness_track,1000,2)
+%      [xnew ynew valuesnew]=addtrack(x_m,y_m,thickness,'trackcoord.exp',thickness_track,1000,2,3)
+
+%Create a new picture precise enough to be modified by the tracks
+%Read the points of the tracks
+stru=expread(track_coord,1);
+nods=stru.nods;
+xtracks=stru.x';
+ytracks=stru.y';
+
+%First check that the parameters are ok:
+if (size(track_values,1)~=nods)  || (size(xtracks,2)~=nods) || (size(ytracks,2)~=nods),
+	error('addtrack error message : track coordinates and track values must have the same size');
+elseif distance<0,
+	error('addtrack error message : the distance must be a positive value');
+elseif exponent<0,
+	error('addtrack error message : the exponent must be a positive value');
+elseif (size(x_m1,1)~=(size(values1,2)+1)) || (size(y_m1,1)~=(size(values1,1)+1)),
+	error('addtrack error message : problem in the map, check the size of x_m1, y_m1 and values1');
+end
+
+%stru.nods=4;
+%xtracks=[50 50 55 62]; % 2 3 4 5 6 7 8 9 1 ]';
+%ytracks=[40 40.5 41 41]; % 5 5 5 5 5 5 5 5 8 ]';
+%x_m1=[1:10:101]';
+%y_m1=[1:10:101]';
+%track_values=2*ones(4,1);
+%values1=ones(10,10);
+
+%Find the average distance between two points of the tracks
+av_x=sum(abs(diff(xtracks)))/(stru.nods-1);
+av_y=sum(abs(diff(ytracks)))/(stru.nods-1);
+dist_av=sqrt(av_x^2+av_y^2);
+
+%Calculate the multiplicate factor for the new values:
+if nargin==7,
+	mult=round((x_m1(2)-x_m1(1))/(1*dist_av));
+else
+	mult=varargin{1};
+end
+
+%Plug the values in the new multiplied matrix
+values=zeros(mult*size(values1,1),mult*size(values1,2));
+
+for i=1:mult,
+	for j=1:mult,
+		values(i:mult:end,j:mult:end)=values1;
+	end
+end
+
+%Create the new x and y addapted to the matrix
+x_m2=linspace(x_m1(1),x_m1(end),mult*(size(x_m1,1)-1)+1)';
+y_m2=linspace(y_m1(1),y_m1(end),mult*(size(y_m1,1)-1)+1)';
+
+%Create a new set of x and y correponding to the medium value on the matrix
+x_med=(x_m2(1:end-1)+x_m2(2:end))/2;
+y_med=(y_m2(1:end-1)+y_m2(2:end))/2;
+
+numrow=size(y_med,1);
+numcol=size(x_med,1);
+
+%Create new x and y to have the hole matrix
+x_mat=repmat(x_med',numrow,1);
+y_mat=repmat(y_med,1,numcol);
+
+%Remove useless points of the track
+points=find(track_values==0);
+track_values(points)=[];
+xtracks(points)=[];
+ytracks(points)=[];
+points=find(isnan(track_values));
+track_values(points)=[];
+xtracks(points)=[];
+ytracks(points)=[];
+
+%Remove points outside of the map
+points=find(xtracks<x_med(1) | xtracks>x_med(end) | ytracks<y_med(1) | ytracks>y_med(end));
+track_values(points)=[];
+xtracks(points)=[];
+ytracks(points)=[];
+
+%initialize some matrices
+numoverlap=zeros(numrow,numcol);
+weights=zeros(numrow,numcol);
+weightsvalues=zeros(numrow,numcol);
+
+%Loop over the points of the track
+nel=size(track_values,1);
+fprintf('%s','      track processing progress:   0.00 %');
+for i=1:nel;
+	if mod(i,1000)==0,
+		fprintf('\b\b\b\b\b\b\b')
+		fprintf('%5.2f%s',i/nel*100,' %');
+	end
+
+	x=xtracks(i);
+	y=ytracks(i);
+
+	%get indices that are modified
+	indexx1=max(find(x_med<x-distance));
+	if isempty( indexx1), indexx1=1; end
+	indexx2=min(find(x_med>x+distance));
+	if isempty( indexx2), indexx2=numrow; end
+	indexy1=max(find(y_med<y-distance));
+	if isempty( indexy1), indexy1=1; end
+	indexy2=min(find(y_med>y+distance));
+	if isempty( indexy2), indexy2=numcol; end
+
+
+	%get weighing coefficient
+	val=track_values(i);
+	distances=sqrt((x-x_mat(indexy1:indexy2,indexx1:indexx2)).^2+(y-y_mat(indexy1:indexy2,indexx1:indexx2)).^2);
+	coeff=min(1,(distances/distance)).^(1/exponent);
+
+	%update numoverlap and weights
+	numoverlap(indexy1:indexy2,indexx1:indexx2)=numoverlap(indexy1:indexy2,indexx1:indexx2)+1;
+	weights(indexy1:indexy2,indexx1:indexx2)=weights(indexy1:indexy2,indexx1:indexx2)+coeff;
+	weightsvalues(indexy1:indexy2,indexx1:indexx2)=weightsvalues(indexy1:indexy2,indexx1:indexx2)+(1-coeff)*val;
+
+end
+if nel>1000,
+	fprintf('\b\b\b\b\b\b\b\b')
+	fprintf('%4.2f%s\n',100,' %');
+end
+
+
+%Change the values of numoverlap to 1 if 0 since we are going to devide by this matrix
+numoverlap(find(~numoverlap))=1;
+
+%Same thing for weights since values far from the tracks don't change
+weights(find(~weights))=1;
+
+%Create the final matrix depending on the previous matrix
+values=(values.*weights+weightsvalues)./numoverlap;
+
+%Plug the values of the track in the new matrix
+values2=values;
Index: /issm/trunk-jpl-damage/src/m/utils/DataProcessing/data_processing_tool.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/DataProcessing/data_processing_tool.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/DataProcessing/data_processing_tool.m	(revision 11330)
@@ -0,0 +1,467 @@
+function varargout = data_processing_tool(varargin)
+%DATA_PROCESSING_TOOL - GUI to process binary data
+%
+%   this routine is a GUI that helps the user to open
+%   a binary file (Little Endian, Big Endian, Float 32,
+%   double,...) and save a Matlab file (.mat) with the
+%   processed data and the coordinates
+%
+%   Usage:
+%      data_processing_tool
+
+	gui_Singleton = 1;
+	gui_State = struct('gui_Name',       mfilename, ...
+		'gui_Singleton',  gui_Singleton, ...
+		'gui_OpeningFcn', @data_processing_tool_OpeningFcn, ...
+		'gui_OutputFcn',  @data_processing_tool_OutputFcn, ...
+		'gui_LayoutFcn',  [] , ...
+		'gui_Callback',   []);
+	if nargin && ischar(varargin{1})
+		gui_State.gui_Callback = str2func(varargin{1});
+	end
+
+	if nargout
+		[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
+	else
+		gui_mainfcn(gui_State, varargin{:});
+	end
+end
+
+function data_processing_tool_OpeningFcn(hObject, eventdata, handles, varargin)
+	handles.output = hObject;
+
+	%enable toolbar (useful for caxis...)
+	set(hObject,'toolbar','figure');
+
+	% Update handles structure
+	guidata(hObject, handles);
+
+	%this variable used to prevent users from breaking the GUI
+	%the variable is set to 1 once the data has been processed
+	handles.processDataCompleted=0;
+
+	%initialize other variables
+	handles.Msize=NaN;
+	handles.Nsize=NaN;
+	handles.numvectors=NaN;
+	handles.endian=NaN;
+	handles.datatype=NaN;
+	handles.dx=NaN;
+	handles.dy=NaN;
+	handles.xEast=NaN;
+	handles.yNorth=NaN;
+
+	%two files permitted
+	set(handles.inputFile,'Max',1);
+	set(handles.inputFile,'Min',0);
+
+	% Update handles structure
+	guidata(hObject, handles);
+end
+
+% --- Outputs from this function are returned to the command line.
+function varargout = data_processing_tool_OutputFcn(hObject, eventdata, handles) 
+
+	% Get default command line output from handles structure
+	varargout{1} = handles.output;
+end
+
+
+function inputFile_Callback(hObject, eventdata, handles)
+%no code needed for this callback, the listbox is only used as a visual
+end
+
+function addFiles_pushbutton_Callback(hObject, eventdata, handles)
+	%gets input file(s) from user. the sample data files have extension .s2p
+	[input_file,pathname] = uigetfile( ...
+		{'*.*', 'All Files (*.*)'}, ...
+		'Select files', ... 
+		'MultiSelect', 'on');
+
+	%if file selection is cancelled, pathname should be zero
+	%and nothing should happen
+	if pathname==0
+		return
+	end
+
+	handles.processDataCompleted=1;
+
+	%gets the current data file names inside the listbox
+	inputFileName=get(handles.inputFile,'String');
+
+	%if they only select one file, then the data will not be a cell
+	inputFileName= fullfile(pathname,input_file);
+
+	%updates the gui to display all filenames in the listbox
+	set(handles.inputFile,'String',inputFileName);
+
+	%make sure first file is always selected so it doesn't go out of range
+	%the GUI will break if this value is out of range
+	set(handles.inputFile,'Value',1);
+
+	% Update handles structure
+	guidata(hObject, handles);
+end
+
+function reset_pushbutton_Callback(hObject, eventdata, handles)
+	%resets the GUI by clearing all relevant fields
+
+	handles.processDataCompleted = 0;
+
+	%clears the axes
+	cla(handles.axes1,'reset');
+
+	%set the popupmenu to default value
+%	set(handles.plot_popupmenu,'Value',1);
+
+	%clears the contents of the listbox
+	set(handles.inputFile,'String','');
+	set(handles.inputFile,'Value',0);
+
+	%updates the handles structure
+	guidata(hObject, handles);
+end
+
+function plotdata_pushbutton_Callback(hObject, eventdata, handles)
+
+	%get the list of input file names from the listbox
+	inputFileName=get(handles.inputFile,'String');
+
+	%checks to see if the user selected any input files
+	%if not, nothing happens
+	if isempty(inputFileName)
+		errordlg('Select a file first!')
+		return
+	end
+
+	%disables the button while data is processing
+	disableButtons(handles);
+	refresh(data_processing_tool); 
+
+	%parse options
+	if ~isnan(handles.Msize)
+		M=handles.Msize;
+	else
+		errordlg('Number of lines (M) not valid')
+		return
+	end
+	if ~isnan(handles.Nsize)
+		N=handles.Nsize;
+	else
+		errordlg('Number of rows (N) not valid')
+		return
+	end
+	if ~isnan(handles.numvectors)
+		numvectors=handles.numvectors;
+		%change M
+		M=numvectors*M;
+	else
+		numvectors=1;
+	end
+	if ~isnan(handles.endian)
+		endian=handles.endian;
+	else
+		endian=1;
+	end
+	if ~isnan(handles.datatype)
+		datatype=handles.datatype;
+	else
+		datatype='float32';
+	end
+
+	%open file
+	if endian==1
+		fid=fopen(inputFileName,'r','ieee-be');
+	else
+		fid=fopen(inputFileName,'r','ieee-le');
+	end
+
+	%read file
+	[u, numpoints]=fread(fid, [M,N],datatype);
+
+	%close file
+	fclose(fid);
+
+	%Pair of vectors?
+	if numvectors==2,
+	   vx=u(1:2:M,:);vx=flipud(vx');
+	   vy=u(2:2:M,:);vx=flipud(vx');
+
+		%keep track
+		handles.vx=vx;
+		handles.vy=vy;
+
+		u=sqrt(vx.^2+vy.^2);
+	end
+
+	cla(handles.axes1); %clear the axes
+	axes(handles.axes1); %set the axes to plot
+	grid on
+	imagesc(u)
+	colorbar
+
+	%keep track
+	handles.u=u;
+
+	%to see whether the data has been processed or not
+	handles.processDataCompleted=2;
+
+	%data is done processing, so re-enable the buttons
+	enableButtons(handles);
+	guidata(hObject, handles);
+end
+
+function plotcoord_Callback(hObject, eventdata, handles)
+
+	%check
+	if handles.processDataCompleted<2
+		errordlg('Process data first !')
+		return
+	end
+
+	%parse options
+	if ~isnan(handles.dx)
+		dx=handles.dx;
+	else
+		errordlg('value of x-spacing not supported')
+		return
+	end
+	if ~isnan(handles.dy)
+		dy=handles.dy;
+	else
+		errordlg('value of y-spacing not supported')
+		return
+	end
+	if ~isnan(handles.xEast)
+		xEast=handles.xEast;
+	else
+		errordlg('value of xEast not supported')
+		return
+	end
+	if ~isnan(handles.yNorth)
+		yNorth=handles.yNorth;
+	else
+		errordlg('value of yNorth not supported')
+		return
+	end
+
+	disableButtons(handles);
+
+	%process coordinates
+	u=handles.u;
+	s=size(u);
+	M=s(1)+1;
+	N=s(2)+1;
+
+	%correction North and East -> real
+	yNorth=yNorth-M*dy; % corner north
+	x_m=xEast+dx*(0:N-1)';
+	y_m=yNorth+dy*(0:M-1)';
+
+	%plot new axes
+	cla(handles.axes1); %clear the axes
+	axes(handles.axes1); %set the axes to plot
+	grid on
+	imagesc(x_m,y_m,handles.u)
+	set(handles.axes1,'Ydir','Normal');
+	colorbar
+
+	%Keep track of x_m and y_m
+	handles.x_m=x_m;
+	handles.y_m=y_m;
+
+	%to see whether the data has been processed or not
+	handles.processDataCompleted=3;
+
+	%data is done processing, so re-enable the buttons
+	enableButtons(handles);
+	guidata(hObject, handles);
+
+end
+
+
+function save_pushbutton_Callback(hObject, eventdata, handles)
+	%if the data hasn't been processed yet, 
+	%nothing happens when this button is pressed
+	if (handles.processDataCompleted ~= 3)
+		return
+	end
+
+	disableButtons(handles);
+
+	if handles.numvectors==2,
+
+		prompt={'Enter the name of the variable 1:','Enter the name of the variable 2:','Enter the name of the file:'};
+		name='Save Matlab File';
+		numlines=1;
+		defaultanswer={'vx','vy','ProcessedFile'};
+		answer=inputdlg(prompt,name,numlines,defaultanswer);
+		variablename1=answer{1};
+		variablename2=answer{2};
+		filename=answer{3};
+
+		if ~isempty(variablename1) & ~isempty(variablename2) & ~isempty(filename)
+			%get the variables
+			x_m=handles.x_m;
+			y_m=handles.y_m;
+			eval([variablename1 ' = handles.vx;']);
+			eval([variablename2 ' = handles.vy;']);
+			x_m=handles.x_m;
+			eval(['save ' filename ' x_m y_m ' variablename1 ' ' variablename2 ]);
+			disp(['in the file ' filename ' have been saved the following variables: x_m, y_m, ' variablename1 ' and ' variablename2])
+		end
+	else
+		prompt={'Enter the name of the variable:','Enter the name of the file:'};
+		name='Save Matlab File';
+		numlines=1;
+		defaultanswer={'thickness','ProcessedFile'};
+		answer=inputdlg(prompt,name,numlines,defaultanswer);
+		variablename=answer{1};
+		filename=answer{2};
+
+		if ~isempty(variablename) & ~isempty(filename)
+			%get the variables
+			x_m=handles.x_m;
+			y_m=handles.y_m;
+			eval([variablename ' = handles.u;']);
+			eval(['save ' filename ' x_m y_m ' variablename]);
+			disp(['in the file ' filename ' have been saved the following variables: x_m, y_m, and ' variablename])
+		end
+	end
+	enableButtons(handles);
+	guidata(hObject, handles);
+end
+
+function inputFile_CreateFcn(hObject, eventdata, handles)
+	if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+		set(hObject,'BackgroundColor','white');
+	end
+end
+
+function disableButtons(handles)
+	set(handles.figure1,'Pointer','watch');
+	set(handles.plotdata_pushbutton,'Enable','off');
+	set(handles.plotcoord,'Enable','off');
+	set(handles.save_pushbutton,'Enable','off');
+	set(handles.addFiles_pushbutton,'Enable','off');
+	set(handles.reset_pushbutton,'Enable','off');
+end
+
+function enableButtons(handles)
+	set(handles.figure1,'Pointer','arrow');
+	set(handles.plotdata_pushbutton,'Enable','on');
+	set(handles.plotcoord,'Enable','on');
+	set(handles.save_pushbutton,'Enable','on');
+	set(handles.addFiles_pushbutton,'Enable','on');
+	set(handles.reset_pushbutton,'Enable','on');
+end
+
+function EndianType_Callback(hObject, eventdata, handles)
+	handles.endian=get(handles.EndianType,'Value');
+	guidata(hObject, handles);
+end
+
+function EndianType_CreateFcn(hObject, eventdata, handles)
+	if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+		set(hObject,'BackgroundColor','white');
+	end
+end
+
+function DataType_Callback(hObject, eventdata, handles)
+
+	datatype= get(handles.DataType,'Value');
+	switch datatype
+		case 1
+			string='float32';
+
+		case 2
+			string='single';
+
+		case 3
+			string='float64';
+
+		case 4
+			string='double';
+		end
+	handles.datatype=string;
+	guidata(hObject, handles);
+end
+
+function DataType_CreateFcn(hObject, eventdata, handles)
+	if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+		set(hObject,'BackgroundColor','white');
+	end
+end
+
+function PairOfVectors_Callback(hObject, eventdata, handles)
+	handles.numvectors = get(handles.PairOfVectors,'Value');
+	guidata(hObject, handles);
+end
+
+function PairOfVectors_CreateFcn(hObject, eventdata, handles)
+	if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+		set(hObject,'BackgroundColor','white');
+	end
+end
+
+function Msize_Callback(hObject, eventdata, handles)
+	handles.Msize=eval(get(hObject,'String'));
+	guidata(hObject, handles);
+end
+
+function Msize_CreateFcn(hObject, eventdata, handles)
+	if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+		set(hObject,'BackgroundColor','white');
+	end
+end
+
+function Nsize_Callback(hObject, eventdata, handles)
+	handles.Nsize=eval(get(hObject,'String'));
+	guidata(hObject, handles);
+end
+
+function Nsize_CreateFcn(hObject, eventdata, handles)
+	if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+		set(hObject,'BackgroundColor','white');
+	end
+end
+
+function dx_Callback(hObject, eventdata, handles)
+	handles.dx=eval(get(hObject,'String'));
+	guidata(hObject, handles);
+end
+function dx_CreateFcn(hObject, eventdata, handles)
+	if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+		set(hObject,'BackgroundColor','white');
+	end
+end
+
+function dy_Callback(hObject, eventdata, handles)
+	handles.dy=eval(get(hObject,'String'));
+	guidata(hObject, handles);
+end
+function dy_CreateFcn(hObject, eventdata, handles)
+	if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+		set(hObject,'BackgroundColor','white');
+	end
+end
+
+function xEast_Callback(hObject, eventdata, handles)
+	handles.xEast=eval(get(hObject,'String'));
+	guidata(hObject, handles);
+end
+function xEast_CreateFcn(hObject, eventdata, handles)
+	if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+		set(hObject,'BackgroundColor','white');
+	end
+end
+
+function yNorth_Callback(hObject, eventdata, handles)
+	handles.yNorth=eval(get(hObject,'String'));
+	guidata(hObject, handles);
+end
+function yNorth_CreateFcn(hObject, eventdata, handles)
+	if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
+		set(hObject,'BackgroundColor','white');
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Ecco3/ecco32issm.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Ecco3/ecco32issm.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Ecco3/ecco32issm.m	(revision 11330)
@@ -0,0 +1,8 @@
+function nodefield=ecco32issm(field,transition,xecco3,yecco3)
+
+	xecco3linear=xecco3(:); yecco3linear=yecco3(:); %linearize
+	nodefieldlinear=zeros(length(xecco3linear),1);
+	nodefieldlinear(transition(:,1))=field(transition(:,2));
+	nodefield=xecco3;
+	nodefield(:)=nodefieldlinear;
+	%nodefield=nodefield'; %not sure we need that
Index: /issm/trunk-jpl-damage/src/m/utils/Ecco3/issm2ecco3.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Ecco3/issm2ecco3.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Ecco3/issm2ecco3.m	(revision 11330)
@@ -0,0 +1,8 @@
+function nodefield=issm2ecco3(field,transition,xecco3,yecco3)
+
+	xecco3linear=xecco3(:); yecco3linear=yecco3(:); %linearize
+	nodefieldlinear=zeros(length(xecco3linear),1);
+	nodefieldlinear(transition(:,1))=field(transition(:,2));
+	nodefield=xecco3;
+	nodefield(:)=nodefieldlinear;
+	%nodefield=nodefield'; %not sure we need that
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/clicktoflowline.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/clicktoflowline.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/clicktoflowline.m	(revision 11330)
@@ -0,0 +1,16 @@
+function clicktoflowline(index,x,y,u,v,filename)
+%CLICKTOFLOWLINE create a flowline contour file (named 'filename') by clicking on a velocity field once.
+%
+% Usage: clicktoflowline(index,x,y,u,v,x0,y0,filename)
+%
+% Ex: clicktoflowline(md.mesh.elements,md.mesh.x,md.mesh.y,md.inversion.vx_obs,md.inversion.vy_obs,'flowline1.exp')
+
+
+[x0,y0]=ginput(1);
+
+line=flowlines(index,x,y,u,v,x0,y0,200);
+
+hold on
+plot(line.x,line.y,'r-');
+
+expwrite(line,filename);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/downstreamflowlines.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/downstreamflowlines.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/downstreamflowlines.m	(revision 11330)
@@ -0,0 +1,110 @@
+function flowpath=downstreamflowlines(index,x,y,u,v,x0,y0,varargin)
+%DOWNSTREAMFLOWLINES - compute flowlines from a given set of seed points
+%
+%   Usage:
+%      flowpath=downstreamflowlines(index,x,y,u,v,x0,y0)
+%
+%   the velocity field is given by the couple (u,v) and the coordinates
+%   of the seed points are (x0,y0). One can use one or several seed 
+%   points
+%
+%   Example:
+%      flowpath=downstreamflowlines(md.mesh.elements,md.mesh.x,md.mesh.y,md.vx,md.initialization.vy,x0,y0)
+
+%check input size
+if nargin>9 | nargin<7,
+	help flowlines
+	error('flowlines error message: bad usage');
+end
+
+%check input
+if (length(x)~=length(y) | length(x)~=length(u) | length(x)~=length(v)),
+	error('flowlines error message: x,y,u and v must have the same length');
+end
+if length(x)<3,
+	error('flowlines error message: at least one element is required');
+end
+if length(x0)~=length(y0),
+	error('flowlines error message: x0 and y0 do not have the same length');
+end
+
+%get maxiter and precision
+if nargin==9
+	maxiter=varargin{1};%maximum number of iterations
+	precision=varargin{2}; %division of each segment (higer precision increases number of segments)
+else
+	maxiter=200; %maximum number of iterations
+	precision=1; %division of each segment (higer precision increases number of segments)
+end
+
+%check seed points
+tria=TriaSearch(index,x,y,x0,y0);
+pos=find(isnan(tria));
+x0(pos)=[];
+y0(pos)=[];
+
+%initialize other variables
+N=length(x0);
+X=x0; Y=y0;
+flowpath=struct('x',cell(N,1),'y',cell(N,1),'name','','density',1);
+for i=1:N,
+	flowpath(i).x=x0(i);
+	flowpath(i).y=y0(i);
+end
+done=zeros(N,1);
+
+%get avegared length of each element
+length_tria=1/3*(sqrt( (x(index(:,1))-x(index(:,2))).^2+(y(index(:,1))-y(index(:,2))).^2 )+...
+	sqrt((x(index(:,1))-x(index(:,3))).^2+(y(index(:,1))-y(index(:,3))).^2 )+...
+	sqrt((x(index(:,2))-x(index(:,3))).^2+(y(index(:,2))-y(index(:,3))).^2 ));
+
+%take velocity for each element
+u=u(index)*[1;1;1]/3;
+v=v(index)*[1;1;1]/3;
+
+%initialization:
+counter=1;
+
+while any(~done) 
+
+	%find current triangle
+	queue=find(~done);
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+
+	%check that the point is actually inside a triangle of the mesh
+	listnan=find(isnan(tria));
+	for i=1:length(listnan)
+		%remove the last point
+		flowpath(queue(listnan(i))).x(end)=[];
+		flowpath(queue(listnan(i))).y(end)=[];
+		done(queue(listnan(i)))=1;
+	end
+	tria(listnan)=[]; 
+	queue(listnan)=[];
+
+	if isempty(tria),
+		break;
+	end
+
+	%velocity of the current triangle and norm it
+	ut=u(tria); vt=v(tria); normv=sqrt(ut.^2+vt.^2);
+	ut=ut./normv;vt=vt./normv;
+
+	%check counter
+	if counter>maxiter
+		disp(['Maximum number of iterations (' num2str(maxiter) ') reached while going forward'])
+		break
+	end
+	counter=counter+1;
+
+	%remove stagnant point
+	done(queue(find(ut==0 & vt==0)))=1;
+
+	%build next point
+	for i=1:length(queue)
+		X(queue(i))=flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision;
+		Y(queue(i))=flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision;
+		flowpath(queue(i)).x=[flowpath(queue(i)).x;flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision];
+		flowpath(queue(i)).y=[flowpath(queue(i)).y;flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision];
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expbox.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expbox.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expbox.m	(revision 11330)
@@ -0,0 +1,41 @@
+function expbox(filename)
+%EXPBOX - Create a ARGUS file using to clicks
+%
+%   Two clicks on a plot are used to generate a rectangular box
+%   This box is written in EXP format on filename
+%
+%   Usage:
+%      expbox(filename)
+
+%check
+if exist(filename,'file'),
+	choice=input(['A file ' filename ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return
+	end
+end
+
+%Get points
+disp('Click twice to define a rectangular domain. First click for upper left corner, second for lower right corner');
+[x,y]=ginput(2);
+
+x1=x(1);
+x2=x(2);
+x3=x2;
+x4=x1;
+
+y1=y(1);
+y2=y1;
+y3=y(2);
+y4=y3;
+
+%Build Exp structure
+A=struct();
+A.nods=5;
+A.density=1;
+A.x=[x1 x2 x3 x4 x1]';
+A.y=[y1 y2 y3 y4 y1]';
+
+%Write structure
+expwrite(A,filename);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expboxgen.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expboxgen.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expboxgen.m	(revision 11330)
@@ -0,0 +1,99 @@
+function expboxgen(x0,y0,nx,ny,parameter_filename,box_filename)
+%EXPBOXGEN -  creates a domain outline box for a tiff image
+%
+%   This function creates a domain outline box for a .tif image for the 
+%   mosaic tiff. 
+%   x0,y0 and x1,y1 are the cropping coordinates (upper left and lower right 
+%   corners in the larger tiff image).
+%   paramter_filename is the parameter file name for the mosaic tiff image.
+%   box_filename is self explanatory.
+%
+%   Usage:
+%      expboxgen(x0,y0,nx,ny,parameter_filename,box_filename)
+%
+%   See also EXPMASTER, EXPDOC
+
+%initialize
+nrows=-1;
+ncols=-1;
+X0=-1;
+Y0=-1;
+posting=-1;
+
+%first recover necessary information from the paramter_filename.
+fid=fopen(parameter_filename,'r');
+count=1;
+while(1),
+tline=fgetl(fid);
+if ~isstr(tline), break; end;
+
+ind=findstr('ant125m',tline);
+if ~isempty(ind),
+a=strsplit(tline,' ');
+a=a(2); a=char(a); a=a(1:length(a)-1);
+posting=str2num(a);
+end
+
+
+ind=findstr('no. of rows   :',tline);
+if ~isempty(ind),
+a=strsplit(tline,' ');
+nrows=str2num(char(a(length(a))));
+end
+
+ind=findstr('no. of columns:',tline);
+if ~isempty(ind),
+a=strsplit(tline,' ');
+ncols=str2num(char(a(length(a))));
+end
+
+ind=findstr('Upper Left X:',tline);
+if ~isempty(ind),
+a=strsplit(tline,' ');
+X0=str2num(char(a(length(a))));
+end
+
+ind=findstr('Upper Left Y:',tline);
+if ~isempty(ind),
+a=strsplit(tline,' ');
+Y0=str2num(char(a(length(a))));
+end
+
+
+end %while(1),
+
+
+fclose(fid);
+
+if (X0==-1 | Y0==-1 | nrows==-1  | ncols==-1 | posting==-1),
+disp(' ');
+disp(['Could not recover all parameters from ' parameter_filename]);
+disp('Here are the paramters recovered thus far: ');
+disp(['no. of rows: ' num2str(nrows)]);
+disp(['no. of columns: ' num2str(ncols)]);
+disp(['Upper Left X: ' num2str(X0)]);
+disp(['Upper Left Y: ' num2str(Y0)]);
+disp(['Posting: ' num2str(posting)]);
+end
+
+disp(' ');
+disp(['Recovered the following parameters from ' parameter_filename]);
+disp(['no. of rows: ' num2str(nrows)]);
+disp(['no. of columns: ' num2str(ncols)]);
+disp(['Upper Left X: ' num2str(X0)]);
+disp(['Upper Left Y: ' num2str(Y0)]);
+disp(['Posting: ' num2str(posting)]);
+
+%Create X,Y, arrays of coordinates:
+X(1)=X0+x0*posting
+Y(1)=Y0-y0*posting
+X(2)=X(1);
+Y(2)=Y(1)-ny*posting;
+X(3)=X(1)+nx*posting;
+Y(3)=Y(2);
+Y(4)=Y(1);
+X(4)=X(3);
+plot(X,Y,'r*');
+
+%Create box exp file using X and Y. Loop it.
+expgen(box_filename,X,Y,1);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expcoarsen.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expcoarsen.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expcoarsen.m	(revision 11330)
@@ -0,0 +1,74 @@
+function expcoarsen(newfile,oldfile,resolution);
+%EXPCOARSEN - coarsen an exp contour
+%
+%   This routine read an Argus file and remove points with respect to
+%   the resolution (in meters) given in input. 
+%
+%   Usage:
+%      expcoarsen(newfile,oldfile,resolution)
+%
+%   Example:
+%       expcoarsen('DomainOutline.exp','Antarctica.exp',4000)
+
+%Some checks
+if nargin~=3 | nargout
+	error('expcoarsen usage: expcoarsen(newfile,oldfile,resolution)')
+elseif ~exist(oldfile)
+	error(['expcut error message: the file ' oldfile  'does not exist'])
+elseif exist(newfile),
+	choice=input(['A file ' newfile ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return;
+	end
+end
+
+%Get exp oldfile
+[path root ext ver]=fileparts(oldfile);
+A=expread(oldfile,1);
+numprofiles=size(A,2);
+
+%Go through the profiles
+count=1;
+while count<=numprofiles,
+
+	%get number of points and initialize j
+	numpoints=length(A(count).x);
+	j=1;
+
+	%stop if we have reached end of profile (always keep the last point)
+	while j<numpoints,
+
+		%See whether we keep this point or not
+		distance=sqrt((A(count).x(j)-A(count).x(j+1))^2+(A(count).y(j)-A(count).y(j+1))^2);
+		if distance<resolution & j<numpoints-1  %do not remove last point
+			A(count).x(j+1)=[];
+			A(count).y(j+1)=[];
+			numpoints=numpoints-1;
+		else
+			division=floor(distance/resolution)+1;
+			if division>=2,
+				x=linspace(A(count).x(j),A(count).x(j+1),division)';
+				y=linspace(A(count).y(j),A(count).y(j+1),division)';
+				A(count).x=[A(count).x(1:j);x(2:end-1); A(count).x(j+1:end)];
+				A(count).y=[A(count).y(1:j);y(2:end-1); A(count).y(j+1:end)];
+
+				%update current point
+				j=j+1+division-2;
+				numpoints=numpoints+division-2;
+			else
+				%update current point
+				j=j+1;
+			end
+		end
+	end
+	if length(A(count).x)<=1,
+		A(count)=[];
+		numprofiles=numprofiles-1;
+	else
+		count=count+1;
+	end
+end
+
+%write output
+expwrite(A,newfile);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expconcatenate.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expconcatenate.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expconcatenate.m	(revision 11330)
@@ -0,0 +1,56 @@
+function expconcatenate(newfile,oldfile)
+%EXPCONCATENATE - modify several profiles to concatenate them
+% 
+%   this routine reads the profiles of oldfile and enables the user to concatenate
+%   the profiles by clicking on the tips he/she wants to link
+%
+%   Usage:
+%      expconcatenate(newfile,oldfile)
+%
+%   See also EXPMASTER, EXPDOC
+ 
+%Some checks
+if nargin~=2 | nargout
+	error('expconcatenate usage: expconcatenate(newfile,oldfile)')
+elseif ~exist(oldfile)
+	error(['expconcatenate 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'),
+		error('no modification done ... exiting');
+	end
+end
+
+%Get exp oldfile
+[path root ext ver]=fileparts(oldfile);
+A=expread(oldfile,1);
+numprofiles=size(A,2);
+
+%Figure out how nany plots have been done so far 
+g=get(gca,'children'); 
+prevplot=length(g);
+
+%plot existing profile
+hold on
+numpoints=0;
+closed=zeros(numprofiles,1);
+for i=1:numprofiles
+	plot(A(i).x,A(i).y,'-r','MarkerSize',10);
+
+	%update numpoints
+	numpoints=numpoints+size(A(i).x,1);
+
+	%figure out if the profile is closed or not
+	if (A(i).x(1)==A(i).x(end) & A(i).y(1)==A(i).y(end))
+		closed(i)=1;
+	end
+end
+
+%call merge profile routine
+[A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options);
+
+hold off
+
+%write contour using expwrite
+title('New file written, exiting','FontSize',14);
+expwrite(A,newfile);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expcontract.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expcontract.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expcontract.m	(revision 11330)
@@ -0,0 +1,34 @@
+function normal_node=expcontract(newfile,oldfile,distance)
+%EXPCONTRACT - contract or expand a profile, according to the normal.
+% 
+%   Usage:
+%      expcontract(newfile,oldfile,distance)
+%
+%   See also EXPMASTER, EXPDOC
+
+
+contour=expread(oldfile,1);
+num=numel(contour.x);
+
+normal=zeros(num-1,2);
+normal_node=zeros(num-1,2);
+
+for i=1:num-1,
+	normal(i,:)=[ contour.y(i)-contour.y(i+1) contour.x(i+1)-contour.x(i)];
+	normal(i,:)=normal(i,:)/sqrt(normal(i,1)^2+normal(i,2)^2);
+end
+
+normal_node(2:end,:)=[normal(1:end-1,:)+normal(2:end,:)];
+normal_node(1,:)=normal(1,:)+normal(end,:);
+
+normal_node_norm=sqrt(normal_node(:,1).^2+normal_node(:,2).^2);
+normal_node(:,1)=normal_node(:,1)./normal_node_norm;
+normal_node(:,2)=normal_node(:,2)./normal_node_norm;
+
+contour.x(1:end-1)=contour.x(1:end-1)+distance*normal_node(:,1);
+contour.y(1:end-1)=contour.y(1:end-1)+distance*normal_node(:,2);
+
+contour.x(end)=contour.x(1);
+contour.y(end)=contour.y(1);
+
+expwrite(contour,newfile);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expcreatecircle.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expcreatecircle.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expcreatecircle.m	(revision 11330)
@@ -0,0 +1,31 @@
+function expcreatecircle(filename,x0,y0,radius,numberofnodes)
+%EXPCREATECIRCLE - 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:
+%      expcreatecircle(filename,x0,y0,radius,numberofnodes)
+%
+%   See also EXPMASTER, EXPDOC
+
+%Calculate the cartesians coordinates of the points
+x_list=ones(numberofnodes+1,1);
+y_list=ones(numberofnodes+1,1);
+
+theta=(0:2*pi/numberofnodes:2*pi*(1-1/numberofnodes))';
+theta=[theta;0];
+
+x_list=radius*x_list.*cos(theta);
+y_list=radius*y_list.*sin(theta);
+
+%offset x_list and y_list by x0 and y0:
+x_list=x_list+x0;
+y_list=y_list+y0;
+
+contour.x=x_list;
+contour.y=y_list;
+contour.density=1;
+contour.name='circle';
+
+expwrite(contour,filename);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expcreatecontour.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expcreatecontour.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expcreatecontour.m	(revision 11330)
@@ -0,0 +1,36 @@
+function expcreatecontour(filename);
+%EXPCREATECONTOUR - create a contour from a list of points
+%
+%   expcreatecontour: from a list of (x,y) points (retrieve using ginput on an undetermined
+%   number of points: used RETURN key to end input), create an Argus .exp 
+%   file holding the corresponding closed contour.
+%    
+%   Usage:
+%      expcreatecontour(filename)
+%
+%   See also EXPMASTER, EXPDOC
+
+%Get root of filename
+[path root ext ver]=fileparts(filename);
+
+%Get contour
+disp('Click on contour points you desire. Type RETURN to end input of points');
+[x,y]=ginputquick;
+
+%close contour
+x=[x;x(1)];
+y=[y;y(1);];
+
+%plot contour
+hold on;
+plot(x,y,'r-');
+
+%create structure for expwrite routine
+a.x=x;
+a.y=y;
+a.name=root;
+a.density=1;
+
+%write contour using expwrite
+expwrite(a,filename);
+
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expcreateprofile.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expcreateprofile.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expcreateprofile.m	(revision 11330)
@@ -0,0 +1,31 @@
+function expcreateprofile(filename);
+%EXPCREATEPROFILE - create an Argus file from a list of points
+%
+%   expcreateprofile: from a list of (x,y) points (retrieve using ginput on an undetermined
+%   number of points: used RETURN key to end input), create an Argus .exp 
+%   file holding the corresponding open profile.
+%    
+%   Usage:
+%      expcreateprofile(filename)
+%
+%   See also EXPMASTER, EXPDOC
+
+%Get root of filename
+[path root ext ver]=fileparts(filename);
+
+%Get profile
+disp('Click on profile points you desire. Type RETURN to end input of points');
+[x,y]=ginputquick;
+
+%plot contour
+hold on;
+plot(x,y,'r-');
+
+%create structure for expwrite routine
+a.x=x;
+a.y=y;
+a.name=root;
+a.density=1;
+
+%write profile using expwrite
+expwrite(a,filename);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expcut.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expcut.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expcut.m	(revision 11330)
@@ -0,0 +1,56 @@
+function expcut(newfile,oldfile)
+%EXPCUT - cut a part of a profile
+%
+%   this routine reads the profiles of oldfile and enables the user to cut
+%   the profiles by clicking on the tips he/she wants to link
+%
+%   Usage:
+%      expcut(newfile,oldfile)
+%
+%   See also EXPMASTER, EXPDOC
+ 
+%Some checks
+if nargin~=2 | nargout
+	error('expcut usage: expcut(newfile,oldfile)')
+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'),
+		error('no modification done ... exiting');
+	end
+end
+
+%Get exp oldfile
+[path root ext ver]=fileparts(oldfile);
+A=expread(oldfile,1);
+numprofiles=size(A,2);
+
+%Figure out how nany plots have been done so far 
+g=get(gca,'children'); 
+prevplot=length(g);
+
+%plot existing profile
+hold on
+numpoints=0;
+closed=zeros(numprofiles,1);
+for i=1:numprofiles
+	plot(A(i).x,A(i).y,'-r','MarkerSize',10);
+
+	%update numpoints
+	numpoints=numpoints+size(A(i).x,1);
+
+	%figure out if the profile is closed or not
+	if (A(i).x(1)==A(i).x(end) & A(i).y(1)==A(i).y(end))
+		closed(i)=1;
+	end
+end
+
+%call merge profile routine
+[A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options);
+
+hold off
+
+%write contour using expwrite
+title('New file written, exiting','FontSize',14);
+expwrite(A,newfile);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expdisp.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expdisp.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expdisp.m	(revision 11330)
@@ -0,0 +1,48 @@
+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,1);
+
+figure(figurenumber),hold on
+for i=1:length(domain),
+	plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,linestyle,'linewidth',linewidth);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expdoc.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expdoc.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expdoc.m	(revision 11330)
@@ -0,0 +1,36 @@
+function expdoc()
+%EXPDOC - create a doc for EXP routines
+%
+%   Usage:
+%      expdoc()
+
+disp(' ');
+disp('   Utilities dedicated to ARGUS Files (''.exp'' extension)'); 
+disp('     expboxgen: creates a domain outline box for a .tif image for the mosaic tiff');
+disp('            usage: expboxgen(x0,y0,nx,ny,parameter_filename,box_filename)');
+disp('            x0,y0 and nx,ny are the cropping coordinates (upper left and lower right corners in the larger tiff image)');
+disp('            paramter_filename is the parameter file name for the mosaic tiff image. box_filename is self explanatory.');
+disp('     expconcatenate: display all the profiles present in an Argus file and merge them accordingly to the tips selected by the user')
+disp('            usage:  expconcatenate(newfile,oldfile)')
+disp('     expcreatecircle: creates a closed Argus contour centered on (x,y), of radius radius_length. The contour is made of N points');
+disp('            usage: expcreatecircle(filename,x0,y0,radius_length,N)');
+disp('     expcreatecontour: creates a closed Argus contour delimited by the ''clicks'' of the user');
+disp('            usage: expcreatecontour(filename)');
+disp('     expcreateprofile: creates an Argus profile delimited by the ''clicks'' of the user');
+disp('            usage: expcreateprofile(filename)');
+disp('     expcut: display the contents of an Argus file and allow the user cut the profiles');
+disp('            usage: expcut(newfilename,oldfilename)');
+disp('     expdisp: display the contents of an Argus file');
+disp('            usage:  expdisp(filename,[figure number],[line style])');
+disp('     expgen: creates an Argus file from a contour (x,y) and a flag indicating if the contour must be closed or open');
+disp('            usage:  expgen(filename,contours,close_flag)');
+disp('     explink: takes a domain outline made of various segments, and links them together in one domain outline. Use expview to see end result');
+disp('            usage: explink(domainoutline,minthreshold,step)');
+disp('     exptool: allows the user to create, close, merge, remove,... Argus files and save the result in newfile');
+disp('            usage: exptool(newfile,[oldfile1],[oldfile2],[oldfile3],[...]');
+disp('     expread: reads an Argus file and build a structure that holds all the information of the file');
+disp('            usage: expread(file,close_flag)');
+disp('     expselect: display all the profiles of oldfile, the user clicks on the contour he/she wants to remove. Results saved in newfile');
+disp('            usage: expselect(newfile,oldfile)');
+disp('     expwrite: writes an Argus file from a structure given in input???');
+disp('            usage: expwrite(structure,filename)');
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expexcludeoutliers.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expexcludeoutliers.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expexcludeoutliers.m	(revision 11330)
@@ -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/trunk-jpl-damage/src/m/utils/Exp/expflip.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expflip.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expflip.m	(revision 11330)
@@ -0,0 +1,19 @@
+function expflip(domainname)
+%EXPFLIP: flip orientation of all contours and domains in domainname exp file.
+%
+%Usage: expflip('MassFlux1.exp');a
+%
+%
+
+
+
+
+
+a=expread(domainname,1);
+
+for i=1:length(a),
+	a(i).x=flipud(a(i).x);
+	a(i).y=flipud(a(i).y);
+end
+
+expwrite(a,domainname);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expgen.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expgen.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expgen.m	(revision 11330)
@@ -0,0 +1,47 @@
+function expgen(file_name,contours,close_flag);
+%EXPGEN - create an Argus file from x and y arrays
+%
+%   Create .exp domain outline type out of x,y  coordinates. 
+%   The contour defined by arrays x and y should not be closed. 
+%   Generated domain outline will not be closed, except if close_flag is set to 1.
+%
+%   Usage:
+%      expgen(file_name,contours,close_flag)
+%
+%   See also EXPMASTER, EXPDOC
+
+%Check on inputs
+if((close_flag~=0) & (close_flag~=1)),
+error('close flag must be 0 of 1');
+end
+fid=fopen(file_name,'wt');
+
+for i=1:length(contours),
+	if(length(contours(i).x)~=length(contours(i).y)),
+	error('contours x and y coordinates must be of identical size');
+	end
+
+	%get density for this profile.
+	if isfield(contours,'density'),
+		density=contours(i).density;
+	end
+
+	fprintf(fid,'%s\n','## Name:');
+	fprintf(fid,'%s\n','## Icon:0');
+	fprintf(fid,'%s\n','# Points Count Value');
+	if(close_flag==0),
+	fprintf(fid,'%i %i\n',length(contours(i).x),density);
+	else
+	fprintf(fid,'%i %i\n',length(contours(i).x)+1,density);
+	end
+	fprintf(fid,'%s\n','# X pos Y pos');
+	for j=1:length(contours(i).x),
+	 fprintf(fid,'%f %f\n',contours(i).x(j),contours(i).y(j));
+	end  
+
+	if(close_flag==1),
+	fprintf(fid,'%f %f\n',contours(i).x(1),contours(i).y(1));
+	end
+	fprintf(fid,'%s\n','');
+end
+fclose(fid);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/explink.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/explink.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/explink.m	(revision 11330)
@@ -0,0 +1,29 @@
+function explink(domainoutline,minthreshold,step)
+%EXPLINK - allow to link several segments of domain outline together
+%
+%   Takes a domain outline made of various segments, and links them together in one 
+%   domain outline. Use expview to see end result.
+%
+%   Usage:
+%      explink(domainoutline,minthreshold,step)
+%
+%   See also EXPMASTER, EXPDOC
+
+notdone=1;
+
+while notdone,
+
+	for i=1:1000,
+		status=expconcatenate(domainoutline,minthreshold+(i-1)*step);
+		if status==0,
+			return;
+		end
+		if status==1,
+			break;
+		end
+		if status==-1,
+			continue;
+		end
+	end
+end
+
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expll2xy.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expll2xy.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expll2xy.m	(revision 11330)
@@ -0,0 +1,37 @@
+function expll2xy(filename,sgn,central_meridian,standard_parallel)  
+%EXPLL2XY: switch exp argus file from lat,long to x,y
+%   Usage:
+%      expll2xy(filename,sgn,central_meridian,standard_parallel)
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==4,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==2
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help expll2xy
+	error('bad usage');
+end
+
+%read filename: 
+domain=expread(filename,1);
+
+%change to x,y: 
+for i=1:length(domain),
+	[domain(i).x domain(i).y]= ll2xy(domain(i).y,domain(i).x,sgn,delta,slat);
+end
+
+%write back to filename: 
+expwrite(domain,filename);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expmaster.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expmaster.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expmaster.m	(revision 11330)
@@ -0,0 +1,2 @@
+function expmaster(newfile,varargin)
+	disp('expmaster has been renamed exptool due to the unpopularity of its name')
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expopen.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expopen.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expopen.m	(revision 11330)
@@ -0,0 +1,10 @@
+function struct=expopen(newname,oldname)
+%EXPOPEN - read in an exp file, and open all the contours.
+%
+%   Usage:
+%      expopen(newname,oldname)
+%  
+
+
+a=expread(oldname,0); %0 for opening.
+expwrite(a,newname);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/exporientation.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/exporientation.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/exporientation.m	(revision 11330)
@@ -0,0 +1,12 @@
+function exporientation(filename)
+
+a=expread(filename);
+
+dx=diff(a.x);
+dx=[dx;dx(end)];
+
+dy=diff(a.y);
+dy=[dy;dy(end)];
+
+quiver(a.x,a.y,dx,dy);
+
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expremovestraightsegments.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expremovestraightsegments.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expremovestraightsegments.m	(revision 11330)
@@ -0,0 +1,31 @@
+function expremovestraightsegments(newfilename,filename,cutoff)
+%EXPREMOVESTRAIGHTSEGMENTS:  remove straight segments connecting contours.
+%
+% Usage: expremovestraightsegments('argus.exp',100); 
+%
+%
+
+a=expread(filename,1);
+newcontours=a(1);
+
+for i=1:length(a),
+	contour=a(i);
+	
+	s=sqrt(contour.x.^2+contour.y.^2);
+	d=diff(s);
+	
+	pos=find(abs(d)>cutoff);
+	pos=[0;pos;length(contour.x)];
+
+	for j=1:length(pos)-1,
+
+		newcontour=contour;
+		newcontour.x=contour.x(pos(j)+1:pos(j+1));
+		newcontour.y=contour.y(pos(j)+1:pos(j+1));
+		newcontour.nods=length(newcontour.x);
+		newcontours(end+1)=newcontour;
+	end
+end
+newcontours=newcontours(2:end);
+
+expwrite(newcontours,newfilename);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expselect.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expselect.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expselect.m	(revision 11330)
@@ -0,0 +1,61 @@
+function expselect(newfile,oldfile)
+%EXPSELECT - allow to select some profiles
+%
+%   this routine reads the profiles of oldfile
+%   and enables the user to select the profiles 
+%   that he/she wants to keep in newfile
+%
+%   Usage:
+%      expselect(newfile,oldfile)
+%
+%   See also EXPMASTER, EXPDOC
+ 
+%Some checks
+if nargin~=2 | nargout
+	error('expselect usage: expselect(newfile,oldfile)')
+elseif ~exist(oldfile)
+	error(['expselect 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'),
+		error('no modification done ... exiting');
+	end
+end
+
+%Get exp oldfile
+[path root ext ver]=fileparts(oldfile);
+A=expread(oldfile,1);
+numprofiles=size(A,2);
+
+%Figure out how nany plots have been done so far 
+g=get(gca,'children'); 
+prevplot=length(g);
+
+%plot existing profile
+hold on
+numpoints=0;
+closed=zeros(numprofiles,1);
+for i=1:numprofiles
+	plot(A(i).x,A(i).y,'-r','MarkerSize',10);
+
+	%update numpoints
+	numpoints=numpoints+size(A(i).x,1);
+
+	%figure out if the profile is closed or not
+	if (A(i).x(1)==A(i).x(end) & A(i).y(1)==A(i).y(end))
+		closed(i)=1;
+	end
+end
+
+%call merge profile routine
+[A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+
+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
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expsplit.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expsplit.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expsplit.m	(revision 11330)
@@ -0,0 +1,31 @@
+function expsplit(domainoutline)
+%EXPSPLIT - split exp file into sub-contours
+%
+%   This routine reads in a domain outline file (Argus format) and plots all the contours 
+%   This will create as many files there are contours in the domain, each file will be postfix with _i
+%   where i is the contour name. 
+%
+%   Usage:
+%      expsplit(domainoutline)
+%
+%   Example:
+%      expsplit('Domain.exp');
+%
+%   See also EXPMASTER, EXPDOC
+
+%check nargin
+if ~nargin | nargin>1
+	help expsplit
+	error('expsplit error message: bad usage');
+end
+
+[path,root,ext]=fileparts(domainoutline);
+
+%Read file: 
+domains=expread(domainoutline,1);
+
+%split and write contours: 
+for i=1:length(domains),
+	subdomain=domains(i);
+	expwrite(subdomain,[root '_' num2str(i)  ext]);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expsquare.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expsquare.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expsquare.m	(revision 11330)
@@ -0,0 +1,45 @@
+function expbox(filename)
+%EXPBOX - Create a ARGUS file using to 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);
+
+xmiddle=mean(x);
+ymiddle=mean(y);
+
+x1=x(1); y1=y(1);
+x3=x(2); y3=y(2);
+
+Diag=[x1-xmiddle;y1-ymiddle];
+
+Vector=[xmiddle;ymiddle]+[-Diag(2);Diag(1)];
+x2=Vector(1); y2=Vector(2);
+
+Vector=[xmiddle;ymiddle]-[-Diag(2);Diag(1)];
+x4=Vector(1); y4=Vector(2);
+
+%Build Exp structure
+A=struct();
+A.nods=5;
+A.density=1;
+A.x=[x1 x2 x3 x4 x1]';
+A.y=[y1 y2 y3 y4 y1]';
+
+%Write structure
+expwrite(A,filename);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expswapxy.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expswapxy.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expswapxy.m	(revision 11330)
@@ -0,0 +1,23 @@
+function expswapxy(filename)
+%EXPSWAP - swap x and y fields
+% 
+%   Usage:
+%      expswap(file)
+%
+%   See also EXPMASTER, EXPDOC
+
+
+contours=expread(filename,1);
+
+newcontours=contours(1);
+
+for i=1:length(contours), 
+	contour=contours(i);
+	newcontour=contour;
+	newcontour.x=contour.y;
+	newcontour.y=contour.x;
+	newcontours(end+1)=newcontour;
+end
+newcontours=newcontours(2:end);
+
+expwrite(newcontours,filename);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/exptool.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/exptool.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/exptool.m	(revision 11330)
@@ -0,0 +1,342 @@
+function exptool(newfile,varargin)
+%EXPMASTER - allow to create, modify, add, cut, .. segments of domain outline together
+%
+%   this routine is used to create, modify, cut,... an Argus file (.exp)
+%
+%   exptool(newprofile,'optionname',optionvalue)
+%      creation of an argus file newprofile
+%
+%   Available options:
+%      - include: include list of existing ARGUS files
+%      - color: line color (default='r')
+%      - selectioncolor: line color of selected profiles (default='b')
+%      - linestyle (default='-')
+%      - linewidth (default=0.2)
+%      - marker (default='+')
+%      - markersize (default=7)
+%      - markeredgecolor (default='r')
+%
+%   Usage:
+%      exptool(newfile,varargin)
+%
+%   Example:
+%      exptool('domain.exp','include',{'domain1.exp' 'domain2.exp'},'color','g','marker','+')
+%
+%   See also EXPDOC
+
+%recover options
+options=pairoptions(varargin{:});
+
+%Some checks
+if ~nargin | nargout
+	error('exptool usage: exptool(newfile,varargin)')
+elseif exist(newfile,'file'),
+	%recursive call to exptool if file already exists
+	if ~exist(options,'include'),
+		exptool(newfile,'include',newfile,varargin{:});
+		return;
+	end
+
+	%check modification
+	choice=input(['A file ' newfile ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return
+	end
+end
+
+%Add default options
+options=addfielddefault(options,'color','r');
+options=addfielddefault(options,'selectioncolor','b');
+options=addfielddefault(options,'LineStyle','-');
+options=addfielddefault(options,'LineWidth',0.2);
+options=addfielddefault(options,'Marker','+');
+options=addfielddefault(options,'MarkerSize',7);
+options=addfielddefault(options,'MarkerEdgeColor','r');
+
+%put all the argus profiles given in input in one structure A
+A=struct([]);
+numprofiles=0;
+numpoints=0;
+closed=[];
+
+%initialize the variables with files provided by 'include' option
+if exist(options,'include'),
+	files=getfieldvalue(options,'include');
+	if ischar(files), files={files}; end
+	for i=1:length(files),
+		filename=files{i};
+		if ~exist(filename,'file'),
+			error(['exptool error message:, ' filename ' does not exist. Exiting...']);
+		else
+			%read file
+			B=expread(filename,1);
+			%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);
+	button=menu('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
+		'undo',...                                %13
+		'redo',...                                %14
+		'quit');                                  %15
+
+
+	%UNDO??
+	if button==13;
+		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
+	end
+
+	%REDO??
+	if button==14
+		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;
+
+			%QUIT
+		case 15
+
+			loop=0;
+
+		otherwise
+
+			%do nothing
+
+	end
+
+end
+
+hold off
+
+%write contour using expwrite
+title('New file written, exiting...','FontSize',14);
+if isempty(A)
+	disp('Profile empty, no file written')
+else
+	expwrite(A,newfile);
+end
+
+%close window
+close;
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/expxy2ll.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/expxy2ll.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/expxy2ll.m	(revision 11330)
@@ -0,0 +1,37 @@
+function expxy2ll(filename,sgn,central_meridian,standard_parallel)  
+%EXPLL2XY: switch exp argus file from lat,long to x,y
+%   Usage:
+%      expxy2ll(filename,sgn,central_meridian,standard_parallel)
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==4,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==2
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help expxy2ll
+	error('bad usage');
+end
+
+%read filename: 
+domain=expread(filename,1);
+
+%change to x,y: 
+for i=1:length(domain),
+	[domain(i).y domain(i).x]= xy2ll(domain(i).x,domain(i).y,sgn,delta,slat); %watch out to swap lat and long
+end
+
+%write back to filename: 
+expwrite(domain,filename);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/flowlines.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/flowlines.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/flowlines.m	(revision 11330)
@@ -0,0 +1,163 @@
+function flowpath=flowlines(index,x,y,u,v,x0,y0,varargin)
+%FLOWLINES - compute flowlines from a given set of seed points
+%
+%   Usage:
+%      flowpath=flowlines(index,x,y,u,v,x0,y0)
+%
+%   the velocity field is given by the couple (u,v) and the coordinates
+%   of the seed points are (x0,y0). One can use one or several seed 
+%   points
+%
+%   Example:
+%      flowpath=flowlines(md.mesh.elements,md.mesh.x,md.mesh.y,md.vx,md.initialization.vy,x0,y0)
+
+%check input size
+if nargin>8 | nargin<7,
+	help flowlines
+	error('flowlines error message: bad usage');
+end
+
+%check input
+if (length(x)~=length(y) | length(x)~=length(u) | length(x)~=length(v)),
+	error('flowlines error message: x,y,u and v must have the same length');
+end
+if length(x)<3,
+	error('flowlines error message: at least one element is required');
+end
+if length(x0)~=length(y0),
+	error('flowlines error message: x0 and y0 do not have the same length');
+end
+
+%get maxiter and precision
+if nargin==8
+	maxiter=varargin{1};
+else
+	maxiter=200; %maximum number of iterations
+end
+precision=1; %division of each segment (higer precision increases number of segments)
+
+%check seed points
+tria=TriaSearch(index,x,y,x0,y0);
+pos=find(isnan(tria));
+x0(pos)=[];
+y0(pos)=[];
+
+%initialize other variables
+N=length(x0);
+X=x0; Y=y0;
+flowpath=struct('x',cell(N,1),'y',cell(N,1),'name','','density',1);
+for i=1:N,
+	flowpath(i).x=x0(i);
+	flowpath(i).y=y0(i);
+end
+done=zeros(N,1);
+
+%get avegared length of each element
+length_tria=1/3*(sqrt( (x(index(:,1))-x(index(:,2))).^2+(y(index(:,1))-y(index(:,2))).^2 )+...
+	sqrt((x(index(:,1))-x(index(:,3))).^2+(y(index(:,1))-y(index(:,3))).^2 )+...
+	sqrt((x(index(:,2))-x(index(:,3))).^2+(y(index(:,2))-y(index(:,3))).^2 ));
+
+%take velocity for each element
+u=u(index)*[1;1;1]/3;
+v=v(index)*[1;1;1]/3;
+
+%initialization:
+counter=1;
+
+while any(~done) 
+
+	%find current triangle
+	queue=find(~done);
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+
+	%check that the point is actually inside a triangle of the mesh
+	listnan=find(isnan(tria));
+	for i=1:length(listnan)
+		%remove the last point
+		flowpath(queue(listnan(i))).x(end)=[];
+		flowpath(queue(listnan(i))).y(end)=[];
+		done(queue(listnan(i)))=1;
+	end
+	tria(listnan)=[]; 
+	queue(listnan)=[];
+
+	if isempty(tria),
+		break;
+	end
+
+	%velocity of the current triangle and norm it
+	ut=u(tria); vt=v(tria); normv=sqrt(ut.^2+vt.^2);
+	ut=ut./normv;vt=vt./normv;
+
+	%check counter
+	if counter>maxiter
+		disp(['Maximum number of iterations (' num2str(maxiter) ') reached while going forward'])
+		break
+	end
+	counter=counter+1;
+
+	%remove stagnant point
+	done(queue(find(ut==0 & vt==0)))=1;
+
+	%build next point
+	for i=1:length(queue)
+		X(queue(i))=flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision;
+		Y(queue(i))=flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision;
+		flowpath(queue(i)).x=[flowpath(queue(i)).x;flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision];
+		flowpath(queue(i)).y=[flowpath(queue(i)).y;flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision];
+	end
+end
+
+%same process but reverse (vel=-vel) to have a vcomplete flow line
+counter=1;
+X=x0; Y=y0;
+done=zeros(N,1);
+
+while any(~done) 
+
+	%find current triangle
+	queue=find(~done);
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+
+	%check that the point is actually inside a triangle of the mesh
+	listnan=find(isnan(tria));
+	for i=1:length(listnan)
+		%remove the last point
+		flowpath(queue(listnan(i))).x(1)=[];
+		flowpath(queue(listnan(i))).y(1)=[];
+		done(queue(listnan(i)))=1;
+	end
+	tria(listnan)=[]; 
+	queue(listnan)=[];
+
+	if isempty(tria),
+		break;
+	end
+
+	%velocity of the current triangle and norm it
+	ut=-u(tria); vt=-v(tria); normv=sqrt(ut.^2+vt.^2);
+	ut=ut./normv;vt=vt./normv;
+
+	%check counter
+	if counter>maxiter
+		disp(['Maximum number of iterations (' num2str(maxiter) ') reached while going backward'])
+		break
+	end
+	counter=counter+1;
+
+	%remove stagnant point
+	done(queue(find(ut==0 & vt==0)))=1;
+
+	%build next point
+	for i=1:length(queue)
+		X(queue(i))=flowpath(queue(i)).x(1)+ut(i)*length_tria(tria(i))/precision;
+		Y(queue(i))=flowpath(queue(i)).y(1)+vt(i)*length_tria(tria(i))/precision;
+		flowpath(queue(i)).x=[flowpath(queue(i)).x(1)+ut(i)*length_tria(tria(i))/precision; flowpath(queue(i)).x];
+		flowpath(queue(i)).y=[flowpath(queue(i)).y(1)+vt(i)*length_tria(tria(i))/precision; flowpath(queue(i)).y];
+	end
+end
+
+%EXP compatibility
+for i=1:length(queue)
+	flowpath(queue(i)).name=['flowline' num2str(i)];
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/ginputquick.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/ginputquick.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/ginputquick.m	(revision 11330)
@@ -0,0 +1,221 @@
+function [out1,out2,out3] = ginput(arg1)
+%GINPUT - Graphical input from mouse.
+%
+%   [X,Y] = GINPUT(N) gets N points from the current axes and returns 
+%   the X- and Y-coordinates in length N vectors X and Y.  The cursor
+%   can be positioned using a mouse (or by using the Arrow Keys on some 
+%   systems).  Data points are entered by pressing a mouse button
+%   or any key on the keyboard except carriage return, which terminates
+%   the input before N points are entered.
+%
+%   [X,Y] = GINPUT gathers an unlimited number of points until the
+%   return key is pressed.
+% 
+%   [X,Y,BUTTON] = GINPUT(N) returns a third result, BUTTON, that 
+%   contains a vector of integers specifying which mouse button was
+%   used (1,2,3 from left) or ASCII numbers if a key on the keyboard
+%   was used.
+%
+%   Usage:
+%      [out1,out2,out3] = ginput(arg1)
+
+%   Copyright 1984-2005 The MathWorks, Inc.
+%   $Revision: 1.1 $  $Date: 2009/04/03 22:56:26 $
+
+out1 = []; out2 = []; out3 = []; y = [];
+c = computer;
+if ~strcmp(c(1:2),'PC') 
+   tp = get(0,'TerminalProtocol');
+else
+   tp = 'micro';
+end
+
+if ~strcmp(tp,'none') && ~strcmp(tp,'x') && ~strcmp(tp,'micro'),
+   if nargout == 1,
+      if nargin == 1,
+         out1 = trmginput(arg1);
+      else
+         out1 = trmginput;
+      end
+   elseif nargout == 2 || nargout == 0,
+      if nargin == 1,
+         [out1,out2] = trmginput(arg1);
+      else
+         [out1,out2] = trmginput;
+      end
+      if  nargout == 0
+         out1 = [ out1 out2 ];
+      end
+   elseif nargout == 3,
+      if nargin == 1,
+         [out1,out2,out3] = trmginput(arg1);
+      else
+         [out1,out2,out3] = trmginput;
+      end
+   end
+else
+   
+   fig = gcf;
+   figure(gcf);
+   
+   if nargin == 0
+      how_many = -1;
+      b = [];
+   else
+      how_many = arg1;
+      b = [];
+      if  ischar(how_many) ...
+            || size(how_many,1) ~= 1 || size(how_many,2) ~= 1 ...
+            || ~(fix(how_many) == how_many) ...
+            || how_many < 0
+         error('MATLAB:ginput:NeedPositiveInt', 'Requires a positive integer.')
+      end
+      if how_many == 0
+         ptr_fig = 0;
+         while(ptr_fig ~= fig)
+            ptr_fig = get(0,'PointerWindow');
+         end
+         scrn_pt = get(0,'PointerLocation');
+         loc = get(fig,'Position');
+         pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)];
+         out1 = pt(1); y = pt(2);
+      elseif how_many < 0
+         error('MATLAB:ginput:InvalidArgument', 'Argument must be a positive integer.')
+      end
+   end
+   
+   % Suspend figure functions
+   state = uisuspend(fig);
+   
+   toolbar = findobj(allchild(fig),'flat','Type','uitoolbar');
+   if ~isempty(toolbar)
+        ptButtons = [uigettool(toolbar,'Plottools.PlottoolsOff'), ...
+                     uigettool(toolbar,'Plottools.PlottoolsOn')];
+        ptState = get (ptButtons,'Enable');
+        set (ptButtons,'Enable','off');
+   end
+
+   set(fig,'pointer','fullcrosshair');
+   fig_units = get(fig,'units');
+   char = 0;
+
+   % We need to pump the event queue on unix
+   % before calling WAITFORBUTTONPRESS 
+   drawnow
+   
+   while how_many ~= 0
+      % Use no-side effect WAITFORBUTTONPRESS
+      waserr = 0;
+      try
+	keydown = wfbp;
+      catch
+	waserr = 1;
+      end
+      if(waserr == 1)
+         if(ishandle(fig))
+            set(fig,'units',fig_units);
+	    uirestore(state);
+            error('MATLAB:ginput:Interrupted', 'Interrupted');
+         else
+            error('MATLAB:ginput:FigureDeletionPause', 'Interrupted by figure deletion');
+         end
+      end
+      
+      ptr_fig = get(0,'CurrentFigure');
+      if(ptr_fig == fig)
+         if keydown
+            char = get(fig, 'CurrentCharacter');
+            button = abs(get(fig, 'CurrentCharacter'));
+            scrn_pt = get(0, 'PointerLocation');
+            set(fig,'units','pixels')
+            loc = get(fig, 'Position');
+            pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)];
+            set(fig,'CurrentPoint',pt);
+         else
+            button = get(fig, 'SelectionType');
+            if strcmp(button,'open') 
+               button = 1;
+            elseif strcmp(button,'normal') 
+               button = 1;
+            elseif strcmp(button,'extend')
+               button = 2;
+            elseif strcmp(button,'alt') 
+               button = 3;
+            else
+               error('MATLAB:ginput:InvalidSelection', 'Invalid mouse selection.')
+            end
+         end
+         pt = get(gca, 'CurrentPoint');
+         
+         how_many = how_many - 1;
+         
+         if(char == 13) % & how_many ~= 0)
+            % if the return key was pressed, char will == 13,
+            % and that's our signal to break out of here whether
+            % or not we have collected all the requested data
+            % points.  
+            % If this was an early breakout, don't include
+            % the <Return> key info in the return arrays.
+            % We will no longer count it if it's the last input.
+            break;
+         end
+
+         out1 = [out1;pt(1,1)];
+         y = [y;pt(1,2)];
+         b = [b;button];
+      end
+   end
+   
+   uirestore(state);
+   if ~isempty(toolbar) && ~isempty(ptButtons)
+        set (ptButtons(1),'Enable',ptState{1});
+        set (ptButtons(2),'Enable',ptState{2});
+   end
+   set(fig,'units',fig_units);
+   
+   if nargout > 1
+      out2 = y;
+      if nargout > 2
+         out3 = b;
+      end
+   else
+      out1 = [out1 y];
+   end
+
+   line(out1,y);
+   line([out1(length(out1)) out1(1)],[y(length(y)) y(1)]);
+   
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function key = wfbp
+%WFBP   Replacement for WAITFORBUTTONPRESS that has no side effects.
+
+fig = gcf;
+current_char = [];
+
+% Now wait for that buttonpress, and check for error conditions
+waserr = 0;
+try
+  h=findall(fig,'type','uimenu','accel','C');   % Disabling ^C for edit menu so the only ^C is for
+  set(h,'accel','');                            % interrupting the function.
+  keydown = waitforbuttonpress;
+  current_char = double(get(fig,'CurrentCharacter')); % Capturing the character.
+  if~isempty(current_char) && (keydown == 1)           % If the character was generated by the 
+	  if(current_char == 3)                       % current keypress AND is ^C, set 'waserr'to 1
+		  waserr = 1;                             % so that it errors out. 
+	  end
+  end
+  
+  set(h,'accel','C');                                 % Set back the accelerator for edit menu.
+catch
+  waserr = 1;
+end
+drawnow;
+if(waserr == 1)
+   set(h,'accel','C');                                % Set back the accelerator if it errored out.
+   error('MATLAB:ginput:Interrupted', 'Interrupted');
+end
+
+if nargout>0, key = keydown; end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/addcontour.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/addcontour.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/addcontour.m	(revision 11330)
@@ -0,0 +1,50 @@
+function [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ADDCONTOUR - add a closed contour
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options)
+		   
+	title('click to add a point to the new profile, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	x=[];
+	y=[];
+
+	while loop
+
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				x(end+1)=x(1);
+				y(end+1)=y(1);
+				A(end+1).x=x; 
+				A(end).y=y; 
+				A(end).name=root; 
+				A(end).density=1; 
+				numprofiles=numprofiles+1;
+				numpoints=numpoints+length(x);
+				closed(end+1)=1;
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/addendprofile.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/addendprofile.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/addendprofile.m	(revision 11330)
@@ -0,0 +1,86 @@
+function [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ADDENDPROFILE - add point at the end of a n existing profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if ~any(~closed)
+		disp('all profiles are closed')
+		return
+	end	   
+	%select a profile first
+	if numprofiles>1
+		%first step, select a profile
+		isclosed=1;
+		title('click on a profile, RETURN to exit','FontSize',14)
+		while isclosed
+			[xi,yi] = ginput(1);
+			if ~isempty(xi)
+				%get the closest point 
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if closed(profsel)
+					disp('selected profile is closed, make another selection')
+				else
+					isclosed=0;
+				end
+
+			else
+				%RETURN -> out
+				return
+			end
+		end
+	else
+		profsel=1;
+	end
+
+	%initialize x and y
+	x=A(profsel).x;
+	y=A(profsel).y;
+
+	%plot the selected profile
+	hold on
+	plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+		'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+	loop=1;
+	while loop
+
+		%first step, select a profile
+		title('click to add point to the selected profile, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize')+2,'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				A(profsel).x=x; 
+				A(profsel).y=y; 
+				A(profsel).name=root; 
+				A(profsel).density=1; 
+				numpoints=numpoints+length(x);
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/addinsideprofile.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/addinsideprofile.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/addinsideprofile.m	(revision 11330)
@@ -0,0 +1,79 @@
+function [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ADDINSIDEPROFILE - add apoint inside a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<2
+		disp('at least two points are required, exiting...')
+		return
+	end	   
+	hold on
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	loop=1;
+	while loop
+
+		%first step, select a segment
+		title('click on a segment, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		%first click
+		if ~isempty(xi)
+
+			%get the closest segment
+			[profsel indsel]=closestsegment(A,numprofiles,xi,yi);
+
+			%check that at least one segment exists
+			if indsel==0
+				disp('at least two points in one profile are required, exiting...')
+				return
+			end
+
+			%highlight selected segment
+			plot([A(profsel).x(indsel) A(profsel).x(indsel+1)],[A(profsel).y(indsel) A(profsel).y(indsel+1)],...
+				'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+			%next click
+			title('click on the new point''s location, RETURN to exit','FontSize',14)
+			[xi,yi,but] = ginput(1);
+
+			%second click
+			if ~isempty(xi)
+
+				%add point to A
+				A(profsel).x=[A(profsel).x(1:indsel,1); xi; A(profsel).x(indsel+1:end,1)];
+				A(profsel).y=[A(profsel).y(1:indsel,1); yi; A(profsel).y(indsel+1:end,1)];
+				numpoints=numpoints+1;
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+
+			else
+				%RETURN->exit
+				return
+			end
+		else
+			%RETURN-> exit
+			return
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/addprofile.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/addprofile.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/addprofile.m	(revision 11330)
@@ -0,0 +1,48 @@
+function [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ADDPROFILE - add a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+		   
+	title('click to add a point to the new profile, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	x=[];
+	y=[];
+
+	while loop
+
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				A(end+1).x=x; 
+				A(end).y=y; 
+				A(end).name=root; 
+				A(end).density=1; 
+				numprofiles=numprofiles+1;
+				numpoints=numpoints+length(x);
+				closed(end+1)=0;
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/closeprofile.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/closeprofile.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/closeprofile.m	(revision 11330)
@@ -0,0 +1,68 @@
+function [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%CLOSEPROFILE - close one or several profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile to be closed')
+		return
+	end
+		   
+	title('click on the profiles to be closed, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks,
+		if numprofiles==0    
+			disp('no profile present, exiting...')
+			return            
+		end  
+		if ~any(~closed),
+			disp('All the profiles are closed, exiting...')
+			return
+		end
+
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it from the selection
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			elseif closed(profsel),
+				%profile already closed, do nothing
+				disp('selected profile aready closed, make another selection'),
+			else
+				%add the profile to the list to be closed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%close the profiles
+			for i=1:length(selection),
+				A(selection(i)).x(end+1)=A(selection(i)).x(1);
+				A(selection(i)).y(end+1)=A(selection(i)).y(1);
+				numpoints=numpoints+1;
+				closed(selection(i))=1;
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/closestpoint.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/closestpoint.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/closestpoint.m	(revision 11330)
@@ -0,0 +1,21 @@
+function [profsel indsel]=closestpoint(A,numprofiles,xi,yi)
+%CLOSESTPOINT - find the closest point of a profile
+%
+%   This routine find the point of the profile A that is the closest
+%   to (xi,yi) and return the number of the profile and the number of
+%   the point
+%
+%   Usage:
+%     [profsel indsel]=closestpoint(A,numprofiles,xi,yi) 
+
+	%loop over the points of each profile, find the closest to (xi,yi)
+	for i=1:numprofiles,
+		distance=(xi-A(i).x).^2+(yi-A(i).y).^2;
+		[newdistance p]=min(distance);
+		if ((i==1) | (newdistance<olddistance)),
+			indsel=p;
+			profsel=i;
+			olddistance=newdistance;
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/closestsegment.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/closestsegment.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/closestsegment.m	(revision 11330)
@@ -0,0 +1,28 @@
+function [profsel indsel]=closestsegment(A,numprofiles,xi,yi)
+%CLOSESTSEGMENT - find the closest segment of a profile
+%
+%   This routine find the segment of the profile A that is the closest
+%   to (xi,yi) and return the number of the profile and the number of
+%   the first point belonging to this closest segment
+%
+%   Usage:
+%     [profsel indsel]=closestsegment(A,numprofiles,xi,yi) 
+
+	%loop over the middles of each profile, find the closest to (xi,yi)
+	profsel=0;
+	indsel=0;
+	first=1;
+	for i=1:numprofiles,
+		if length(A(i).x)>1
+			middles=[(A(i).x(1:end-1)+A(i).x(2:end))/2 (A(i).y(1:end-1)+A(i).y(2:end))/2];
+			distance=(xi-middles(:,1)).^2+(yi-middles(:,2)).^2;
+			[newdistance p]=min(distance);
+			if (first | (newdistance<olddistance)),
+				first=0;
+				indsel=p;
+				profsel=i;
+				olddistance=newdistance;
+			end
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/cutarea.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/cutarea.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/cutarea.m	(revision 11330)
@@ -0,0 +1,152 @@
+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);
+									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;
+									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
+									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;
+									numprofiles=numprofiles+1;
+									numpoints=numpoints-(p1-p2-1);
+								end
+							else
+								%only point removal
+								n=length(A(selection).x);
+								x(1:p2-1)=[];x(p1-p2+2:end)=[];%it should have been x(p2+1:end)
+								y(1:p2-1)=[];y(p1-p2+2:end)=[];
+								A(selection).x=x;
+								A(selection).y=y;
+								numpoints=numpoints-(n-length(A(selection).x));
+								closed(selection)=0;
+							end
+						end
+
+						%plot new profile
+						undoplots(prevplot);
+						for i=1:numprofiles
+							plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+								'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+						end
+						points=[];
+
+					end
+				end
+			end
+		else
+			%RETRUN-> quit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/cutprofile.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/cutprofile.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/cutprofile.m	(revision 11330)
@@ -0,0 +1,79 @@
+function [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%CUTPROFILE - cut a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<2
+		disp('at least two points are needed')
+		return
+	end	   
+	hold on
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	loop=1;
+	while loop
+
+		%select a segment
+		title('click the segment to cut, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest segment
+			[profsel indsel]=closestsegment(A,numprofiles,xi,yi);
+
+			%check that at least one segment exists
+			if indsel==0
+				disp('at least 2 points are required');
+				return,
+			end
+
+			if ((closed(profsel) & length(A(profsel).x)<3) | (~closed(profsel) & length(A(profsel).x)<2))
+				disp('at least 2 points are required, make another selection');
+			else
+				%cut A
+				if closed(profsel)
+					%open the contour
+					A(profsel).x=[A(profsel).x(indsel+1:end-1,1);A(profsel).x(1:indsel,1)];
+					A(profsel).y=[A(profsel).y(indsel+1:end-1,1);A(profsel).y(1:indsel,1)];
+					numpoints=numpoints-1;
+					closed(profsel)=0;
+				else
+					%cut the contour in 2 profiles
+					A(end+1).x=A(profsel).x(indsel+1:end,1);
+					A(end).y=A(profsel).y(indsel+1:end,1);
+					A(end).name=root; 
+					A(end).density=1; 
+					A(profsel).x=A(profsel).x(1:indsel,1);
+					A(profsel).y=A(profsel).y(1:indsel,1);
+					numprofiles=numprofiles+1;
+					closed(end+1)=0;
+				end
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+			end
+		else
+			%RETURN->exit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/mergeprofiles.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/mergeprofiles.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/mergeprofiles.m	(revision 11330)
@@ -0,0 +1,152 @@
+function [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options);
+%MERGEPROFILES - merge profiles
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile. The user must select the two tips that
+%   he/she wants to merge
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+hold on
+loop=1;
+
+%Take all the tips coordinates of open profiles
+counter=1; tips=[];
+for i=1:numprofiles
+	if ~closed(i),
+		%x and y coord, profile number, 1 if beginning, 2 and if end
+		if length(A(i).x)==1,
+			tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+			counter=counter+1;
+		else
+			tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+			tips(counter+1,:) = [A(i).x(end) A(i).y(end) i  2];
+			counter=counter+2;
+		end
+	end
+end
+
+if size(tips,1)<2
+	disp('at least one unclosed profile is required')
+	return
+end
+
+%plot the tips only
+plot(tips(:,1),tips(:,2),...
+	'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+firsttip=1;
+
+%loop (at least 2 clicks needed)
+while loop
+
+	%some checks
+	if size(tips,1)<2
+		disp('at least one unclosed profiles are required')
+		return
+	end
+
+	%select a point
+	if firsttip
+		title('click on the first tip, RETURN to exit','FontSize',14)
+	else
+		title('click on the second tip, RETURN to exit','FontSize',14)
+	end
+
+	[xi,yi] = ginput(1);
+
+	if ~isempty(xi)
+
+		if firsttip
+			%find the selected tip
+			distance=(xi-tips(:,1)).^2+(yi-tips(:,2)).^2;
+			[dmin tip1]=min(distance);
+			numprofile1=tips(tip1,3);
+			firsttip=0;
+
+			%remove tip1 from tips list
+			newtips=tips;
+			newtips(tip1,:)=[];
+
+			%plot selected tip
+			plot(tips(tip1,1),tips(tip1,2),...
+				'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(A(numprofile1).x,A(numprofile1).y,...
+				'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+
+		%second selection
+		else
+			distance=(xi-newtips(:,1)).^2+(yi-newtips(:,2)).^2;
+			[dmin tip2]=min(distance);
+			numprofile2=newtips(tip2,3);
+
+			if numprofile1==numprofile2
+				%close the profile
+				A(numprofile1).x(end+1)=A(numprofile1).x(1);
+				A(numprofile1).y(end+1)=A(numprofile1).y(1);
+				numpoints=numpoints+1;
+				closed(numprofile1)=1;
+
+			else
+
+				if tips(tip1,4)==1 & newtips(tip2,4)==1,
+					A(numprofile1).x=[flipud(A(numprofile2).x); A(numprofile1).x];
+					A(numprofile1).y=[flipud(A(numprofile2).y); A(numprofile1).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==1 & newtips(tip2,4)==2,
+					A(numprofile1).x=[A(numprofile2).x; A(numprofile1).x];
+					A(numprofile1).y=[A(numprofile2).y; A(numprofile1).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==2 & newtips(tip2,4)==1,
+					A(numprofile1).x=[A(numprofile1).x; A(numprofile2).x];
+					A(numprofile1).y=[A(numprofile1).y; A(numprofile2).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==2 & newtips(tip2,4)==2,
+					A(numprofile1).x=[A(numprofile1).x; flipud(A(numprofile2).x)];
+					A(numprofile1).y=[A(numprofile1).y; flipud(A(numprofile2).y)];
+					numprofiles=numprofiles-1;
+				end
+
+				%delete profile2
+				A(numprofile2)=[];
+				closed(numprofile2)=[];
+
+			end
+
+			%update tips
+			counter=1; tips=[];
+			for i=1:numprofiles
+				if ~closed(i),
+					%x and y coord, profile number, 1 if beginning, 2 and if end
+					if length(A(i).x)==1,
+						tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+						counter=counter+1;
+					else
+						tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+						tips(counter+1,:) = [A(i).x(end) A(i).y(end) i  2];
+						counter=counter+2;
+					end
+				end
+			end
+
+			%plot new profile
+			undoplots(prevplot);
+			for i=1:numprofiles
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+			if ~isempty(tips)
+				plot(tips(:,1),tips(:,2),...
+					'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			end
+
+			%back to beginning
+			firsttip=1;
+		end
+	else
+		%RETRUN-> quit
+		loop=0;
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/modifyposition.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/modifyposition.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/modifyposition.m	(revision 11330)
@@ -0,0 +1,77 @@
+function [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options);
+%MODIFYPOSITION - modify the prosition of a point of a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting..')
+		return
+	end
+
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	while loop
+
+		%select a point to be modified 
+		title('click on the point to be modified, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest point
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			%plot the point in blue
+			plot(A(profsel).x(indsel),A(profsel).y(indsel),...
+				'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+			%select new location
+			title('click on the new location, RETURN to exit','FontSize',14)
+			[xi,yi] = ginput(1);
+
+			if ~isempty(xi)
+
+				%modification of its coordinates
+				A(profsel).x(indsel)=xi;
+				A(profsel).y(indsel)=yi;
+
+				%modify the last point if the profile is closed and indsel=end or 1
+				if closed(profsel)
+					if indsel==1 
+						A(profsel).x(end)=xi;
+						A(profsel).y(end)=yi;
+					elseif indsel==length(A(profsel).x)
+						A(profsel).x(1)=xi;
+						A(profsel).y(1)=yi;
+					end
+				end
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+			else
+				%RETURN-> exit
+				loop=0;
+			end
+		else
+			%RETURN-> exit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/removepoints.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/removepoints.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/removepoints.m	(revision 11330)
@@ -0,0 +1,85 @@
+function [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+%REMOVEPOINTS - remove a point from a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end
+
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+	end
+
+	while loop
+
+		%check that at least one point is present
+		if numpoints==0
+			disp('at least one point are needed')
+			return
+		end	   
+
+		%select a point to be deleted
+		title('click on the point to be removed, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest point
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			%remove point of A
+			A(profsel).x(indsel)=[];
+			A(profsel).y(indsel)=[];
+
+			%unclose the domain if only 2 points remaining
+			if closed(profsel)
+				if length(A(profsel).x)==3
+					A(profsel).x(end)=[];
+					A(profsel).y(end)=[];
+					numpoints=numpoints-1;
+					closed(profsel)=0;
+				end
+			end
+
+			%remove the last point if the profile is closed and indsel=end or 1
+			if closed(profsel)
+				if indsel==1 
+					A(profsel).x(end)=A(profsel).x(1);
+					A(profsel).y(end)=A(profsel).y(1);
+				elseif indsel==length(A(profsel).x)
+					A(profsel).x(1)=A(profsel).x(end);
+					A(profsel).y(1)=A(profsel).y(end);
+				end
+			end
+			numpoints=numpoints-1;
+
+			%plot new profile
+			undoplots(prevplot);
+			for i=1:numprofiles
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+					'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				if length(A(i).x)==1
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker','o');
+				end
+			end
+
+		else
+			%RETURN-> exit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/removeprofile.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/removeprofile.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/removeprofile.m	(revision 11330)
@@ -0,0 +1,56 @@
+function [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%REMOVEPROFILE - delete a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	title('click on the profiles to be removed, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks
+		if numprofiles==0
+			disp('no profile to be removed, exiting...')
+			return
+		end
+		   
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			else
+				%add the profile to the list to be removed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%remove the profiles
+			selection=sort(selection);
+			for i=1:length(selection),
+				numprofiles=numprofiles-1;
+				numpoints=numpoints-length(A(selection(i)-(i-1)).x);
+				A(selection(i)-(i-1))=[];
+				closed(selection(i)-(i-1))=[];
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/removeseveralpoints.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/removeseveralpoints.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/removeseveralpoints.m	(revision 11330)
@@ -0,0 +1,130 @@
+function [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+%REMOVESEVERALPOINTS - remove several point
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<3
+		disp('at least 3 points are required, exiting...')
+		return
+	end	   
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	points=[];
+
+	%loop (at least 3 clicks needed)
+	while loop
+
+		%some checks
+		if numpoints<3
+			disp('at least 3 points are required, exiting...')
+			return
+		end
+
+		%select a point
+		if isempty(points)
+			title('click on the first tip, RETURN to exit','FontSize',14)
+		elseif length(points)==1
+			title('click on the second tip, RETURN to exit','FontSize',14)
+		else
+			title('click in the middle of the area to be removed, RETURN to exit','FontSize',14)
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			%get the closest point
+			%first time, look at all profiles
+			if isempty(points)
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if ((closed(profsel) & length(A(profsel).x)<4) |  (~closed(profsel) & length(A(profsel).x)<3)),
+					disp('the selected profile has less than 3 points, make another selection');
+				else
+					selection=profsel;
+					points(end+1)=indsel;
+					plot(A(profsel).x,A(profsel).y,...
+						'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+					text(A(selection).x(indsel),A(selection).y(indsel),num2str(1),'FontSize',14,'background',[0.7 0.7 0.9]);
+				end
+				%disp(['p1= ' num2str(indsel)]),
+			else
+				%get the 2d or 3d point for the given contou
+				[profsel indsel]=closestpoint(A(selection),1,xi,yi);
+				if ismember(indsel,points)
+					disp('the selected points must be distinct')
+				else
+					%second click?
+					if length(points)==1,
+						points(end+1)=indsel;
+						text(A(selection).x(indsel),A(selection).y(indsel),num2str(2),'FontSize',14,'background',[0.7 0.7 0.9]);
+						%disp(['p2= ' num2str(indsel)]),
+					%third click?
+					else
+						p1=points(1); p2=points(2); p3=indsel;
+						%disp(['p3= ' num2str(indsel)]),
+						if p1<p2
+							if p3>p1 & p3<p2
+								A(selection).x(p1+1:p2-1)=[];
+								A(selection).y(p1+1:p2-1)=[];
+								numpoints=numpoints-(p2-p1-1);
+							else
+								A(selection).x=A(selection).x(p1:p2);
+								A(selection).y=A(selection).y(p1:p2);
+								numpoints=numpoints-(numpoints-1-p2)-(p1-1);
+								if closed(selection)
+									%reattach the tips
+									A(selection).x(end+1)=A(selection).x(1);
+									A(selection).y(end+1)=A(selection).y(1);
+									numpoints=numpoints+1;
+								end
+							end
+						else
+							if p3>p2 & p3<p1
+								A(selection).x(p2+1:p1-1)=[];
+								A(selection).y(p2+1:p1-1)=[];
+								numpoints=numpoints-(p1-p2-1);
+							else
+								A(selection).x=A(selection).x(p2:p1);
+								A(selection).y=A(selection).y(p2:p1);
+								numpoints=numpoints-(numpoints-1-p1)-(p2-1);
+								if closed(selection)
+									%reattach the tips
+									A(selection).x(end+1)=A(selection).x(1);
+									A(selection).y(end+1)=A(selection).y(1);
+									numpoints=numpoints+1;
+								end
+							end
+						end
+
+						%plot new profiles
+						undoplots(prevplot);
+						for i=1:numprofiles
+							plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+								'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+						end
+						points=[];
+
+					end
+				end
+			end
+		else
+			%RETRUN-> quit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/undoplots.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/undoplots.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/manipulation/undoplots.m	(revision 11330)
@@ -0,0 +1,12 @@
+function  undoplots(prevplot)
+%UNDOPLOTS - undo plots
+%
+%   Usage:undoplots(prevplot)
+
+	%erase all previous plots
+	g=get(gca,'children');
+	L=length(g);
+	for i=1:L-prevplot
+		delete(g(i));
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/expread.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/expread.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/expread.m	(revision 11330)
@@ -0,0 +1,91 @@
+function Struct=expread(filename,whole);
+%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,whole)
+%  
+%   Example:
+%      Struct=expread('domainoutline.exp')
+%      Struct=expread('domainoutline.exp',1)
+%
+%   See also EXPDOC, EXPWRITEASVERTICES
+
+%some checks
+if ~exist(filename),
+	error(['expread error message: file ' filename ' not found!']);
+end
+if nargin<2,
+	whole=1;
+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:',6), break; end
+
+	%Get Info
+	A=fscanf(fid,'%s %s %s %s',4);
+	if ~strncmp(A,'#Points',7), break; end
+
+	%Get number of nods 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;
+		%skip last coordinate if whole=0,
+		if whole==0
+			Struct(count).nods=Struct(count).nods-1;
+			Struct(count).x   =Struct(count).x(1:end-1,1);
+			Struct(count).y   =Struct(count).y(1:end-1,1);
+		end
+	else
+		Struct(count).closed=false;
+	end
+
+end
+
+%close file
+fclose(fid);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/expwrite.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/expwrite.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/expwrite.m	(revision 11330)
@@ -0,0 +1,38 @@
+function expwrite(a,filename);
+%EXPWRITE - write an Argus file from a structure given in input
+%
+%   This routine write an Argus file form a structure containing the fields:
+%   x and y of the coordinates of the points.
+%   The first argument is the structure containing the points coordinates 
+%   and the second one the file to be write.
+%
+%   Usage:
+%      expwrite(a,filename)
+% 
+%   Example:
+%      expwrite(coordstruct,'domainoutline.exp')
+%
+%   See also EXPDOC, EXPREAD, EXPWRITEASVERTICES
+
+fid=fopen(filename,'w');
+for n=1:length(a),
+   
+   if isfield(a,'name'),
+	   if ~isempty(a(n).name),
+		   fprintf(fid,'%s%s\n','## Name:',a(n).name);
+	   else
+		   fprintf(fid,'%s\n','## Name:');
+	   end
+   else
+	   fprintf(fid,'%s\n','## Name:');
+   end
+   
+   fprintf(fid,'%s\n','## Icon:0');
+   fprintf(fid,'%s\n','# Points Count Value');
+   fprintf(fid,'%i %f\n',[length(a(n).x) a(n).density]);
+   fprintf(fid,'%s\n','# X pos Y pos');
+	fprintf(fid,'%10.10f %10.10f\n',[a(n).x a(n).y]');
+	fprintf(fid,'\n','');
+   
+end
+fclose(fid);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/newline.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/newline.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/newline.m	(revision 11330)
@@ -0,0 +1,8 @@
+function new_line(fid)
+%NEW_LINE - add a new line in a a file
+%
+%   Used by exp generators and readers. 
+%   DO NOT USE
+
+A='';
+fprintf(fid,'\n',A);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/read_file.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/read_file.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/read_file.m	(revision 11330)
@@ -0,0 +1,42 @@
+function struct=read_file(name,whole);
+%READ_FILE - ???
+%
+%   Usage:
+%      struct=read_file(name,whole)
+
+fid=fopen(name,'r');
+i=0;
+while (~feof(fid)),
+   i=i+1;
+   A=readline(fid,2);
+A=readline(fid,2);
+A=readline(fid,4);
+[A,bytecount]=fscanf(fid,'%i %f',[1 2]);
+if whole==1,
+   struct(i).nods=A(1);
+else
+   struct(i).nods=A(1)-1;
+end
+A=readline(fid,5);
+
+struct(i).x=zeros(struct(i).nods,1);
+struct(i).y=zeros(struct(i).nods,1);
+
+for n=1:struct(i).nods,
+   [A,bytecount]=fscanf(fid,'%f %f',[1 2]);
+   struct(i).x(n)=A(1);
+   struct(i).y(n)=A(2);
+end
+if whole==0,
+   fscanf(fid,'%f %f',[1 2]);
+end
+
+end
+fclose(fid);
+
+
+
+
+
+
+
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/readfile.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/readfile.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/readfile.m	(revision 11330)
@@ -0,0 +1,14 @@
+function string=readfile(filename)
+%READFILE - ???
+%
+%   Usage:
+%      string=readfile(filename)
+
+string='';
+fid=fopen(filename);
+while(1),
+	tline=fgets(fid);
+	if ~ischar(tline), break, end
+	string=[string  tline];
+end
+fclose(fid);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/writefile.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/writefile.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/readwrite/writefile.m	(revision 11330)
@@ -0,0 +1,14 @@
+function writefile(filename,string)
+%WRITEFILE - write a file from a string
+%
+%   useful to recovert an exp file from md.domainoutline
+%
+%   Usage:
+%      writefile(filename,string)
+%
+%   Example:
+%      writefile('DomainOutline.exp',md.domainoutline)
+
+fid = fopen(filename,'wt');
+fprintf(fid,string);
+fclose(fid);
Index: /issm/trunk-jpl-damage/src/m/utils/Exp/zinput.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Exp/zinput.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Exp/zinput.m	(revision 11330)
@@ -0,0 +1,211 @@
+function  [out_regs] = zinput(arg1)
+% ZINPUT - Graphical input from mouse with zoom
+%   
+%   [OUT_REGS] = ZINPUT(N) gets N points or regions from the
+%   current axes and returns the X- and Y-ranges in a length Nx4
+%   matrix OUT_REGS. 
+%   The cursor can be positioned using a mouse. Data points are entered by
+%   pressing the right mouse button, the region of the current axis
+%   are selected with the middle button, left button is for
+%   zooming,  single cklick zooms in, click-and drag zooms to
+%   region (and doubble-click should zoom out - feature pending).
+%   Any key on the keyboard except carriage return zooms out to the
+%   orignal axis except carriage return, which terminates the input
+%   before N points are entered.
+%   
+%   [OUT_REGS] = ZINPUT gathers an unlimited number of points until the
+%   return key is pressed.
+%   
+%   Usage:
+%      [out_regs] = zinput(arg1)
+%
+%   See also GINPUT
+
+% Copyright Bjorn Gustavsson 20050314
+
+ax0 = axis;
+out_regs = [];
+c = computer;
+if ~strcmp(c(1:2),'PC') 
+  tp = get(0,'TerminalProtocol');
+else
+  tp = 'micro';
+end
+
+if ~strcmp(tp,'none') & ~strcmp(tp,'x') & ~strcmp(tp,'micro') & 0,
+  % I dont know about this so better make short-cut and blindly try
+  % what works for X in all environments - sorry about that.
+else
+  
+  fig = gcf;
+  figure(gcf);
+  
+  if nargin == 0
+    how_many = inf;
+    b = [];
+  else
+    how_many = arg1;
+    b = [];
+    if  isstr(how_many) ...
+          | size(how_many,1) ~= 1 | size(how_many,2) ~= 1 ...
+          | ~(fix(how_many) == how_many) ...
+          | how_many < 0
+      error('Requires a positive integer.');
+    end
+    if how_many == 0
+      ptr_fig = 0;
+      while(ptr_fig ~= fig)
+        ptr_fig = get(0,'PointerWindow');
+      end
+      scrn_pt = get(0,'PointerLocation');
+      loc = get(fig,'Position');
+      pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)];
+      out1 = pt(1); y = pt(2);
+    elseif how_many < 0
+      error('Argument must be a positive integer.');
+    end
+  end
+  
+  % Remove figure button functions
+  state = uisuspend(fig);
+  pointer = get(gcf,'pointer');
+  set(gcf,'pointer','fullcrosshair');
+  
+  fig_units = get(fig,'units');
+  char = 0;
+  while  size(out_regs,1) < how_many
+    % Use no-side effect WAITFORBUTTONPRESS
+    waserr = 0;
+    try
+      keydown = wfbp;
+    catch
+      waserr = 1;
+    end
+    if(waserr == 1)
+      if(ishandle(fig))
+        set(fig,'units',fig_units);
+        uirestore(state);
+        error('Interrupted');
+      else
+        error('Interrupted by figure deletion');
+      end
+    end
+    
+    ptr_fig = get(0,'CurrentFigure');
+    if(ptr_fig == fig)
+      if keydown
+        axis(ax0);
+        char = get(fig, 'CurrentCharacter');
+      else
+        char = get(fig, 'CurrentCharacter');
+        button = abs(get(fig, 'CurrentCharacter'));
+        
+        pnt = get(gcf,'currentpoint');
+        xy1 = get(gca,'currentpoint');
+        rbbox([pnt 0 0],pnt)
+        xy2 = get(gca,'currentpoint');
+        selection_type = get(gcf,'selectiontype');
+        
+        if all(xy1==xy2)
+          ax1 = axis;
+          
+          dx = abs(ax1(2)-ax1(1));
+          dy = abs(ax1(4)-ax1(3));
+          
+          xmin = max(ax1(1),xy1(1)-dx/4);
+          xmax = min(ax1(2),xy1(1)+dx/4);
+          ymin = max(ax1(3),xy1(1,2)-dy/4);
+          ymax = min(ax1(4),xy1(1,2)+dy/4);
+          zoom2ax = [xmin xmax ymin ymax];
+        else
+          %%% zoom to selected rectangle
+          zoom2ax = [sort([xy1(1,1) xy2(1,1)]) sort([xy1(1,2) xy2(1,2)])];
+        end
+        
+        switch selection_type
+         case 'normal'
+          axis(zoom2ax)
+          reg = [];
+         case 'alt'
+          reg = axis;
+          axis(ax0)
+         case 'extend'
+          reg = xy1(1,[1 1 2 2]);
+          axis(ax0)
+         otherwise %%% open (doubleclick in linux)
+          axis(ax0);
+          reg = [];
+        end
+      end
+      pt = get(gca, 'CurrentPoint');
+      
+      if (char == 'r')
+        rmi = size(out_regs,1);
+        if rmi > 0
+          out_regs(rmi,:) = [];
+        end
+        set(fig, 'CurrentCharacter','q')
+        char = 'q';
+        reg = [];
+      end
+      if(char == 13) % & how_many ~= 0)
+                     % if the return key was pressed, char will == 13,
+                     % and that's our signal to break out of here whether
+                     % or not we have collected all the requested data
+                     % points.  
+                     % If this was an early breakout, don't include
+                     % the <Return> key info in the return arrays.
+                     % We will no longer count it if it's the last input.
+        break;
+      end
+      
+      if ~isempty(reg)
+        out_regs = [out_regs;reg];
+      end
+    end
+    %[size(out_regs,1), how_many, size(out_regs,1) < how_many]
+  end
+  
+  uirestore(state);
+  set(gcf,'pointer','arrow');
+  set(fig,'units',fig_units);
+  set(fig, 'CurrentCharacter','q');
+  
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function key = wfbp
+%WFBP   Replacement for WAITFORBUTTONPRESS that has no side effects.
+
+fig = gcf;
+current_char = [];
+
+% Now wait for that buttonpress, and check for error conditions
+waserr = 0;
+try
+  h=findall(fig,'type','uimenu','accel','C');   % Disabling ^C for edit menu so the only ^C is for
+  set(h,'accel','');                            % interrupting the function.
+  keydown = waitforbuttonpress;
+  current_char = double(get(fig,'CurrentCharacter')); % Capturing the character.
+  if~isempty(current_char) & (keydown == 1)           % If the character was generated by the 
+    if(current_char == 3)                       % current keypress AND is ^C, set 'waserr'to 1
+      waserr = 1;                             % so that it errors out. 
+    end
+  end
+  
+  set(h,'accel','C');                                 % Set back the accelerator for edit menu.
+catch
+  waserr = 1;
+end
+drawnow;
+if(waserr == 1)
+  set(h,'accel','C');                                % Set back the accelerator if it errored out.
+  error('Interrupted');
+end
+
+selection_type = get(gcf,'selectiontype');
+if strcmp(selection_type,'open')
+  axis(ax0)
+end
+if nargout>0, key = keydown; end
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Index: /issm/trunk-jpl-damage/src/m/utils/Geometry/FlagElements.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Geometry/FlagElements.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Geometry/FlagElements.m	(revision 11330)
@@ -0,0 +1,57 @@
+function flag=FlagElements(md,region),
+%FLAGELEMENTS - flag the elements in an region
+%
+%   The region can be given with an exp file, a list of elements.
+%
+%   Usage: 
+%      flag=FlagElements(md,region);
+%
+%   Example:
+%      flag=FlagElements(md,'all');
+%      flag=FlagElements(md,'');
+%      flag=FlagElements(md,'Domain.exp');
+%      flag=FlagElements(md,'~Domain.exp');
+%      flag=FlagElements(md,md.mask.elementongroundedice);
+
+	if ischar(region),
+		if isempty(region),
+			flag=zeros(md.mesh.numberofelements,1);
+			invert=0;
+		elseif strcmpi(region,'all')
+			flag=ones(md.mesh.numberofelements,1);
+			invert=0;
+		else
+			%make sure that we actually don't want the elements outside the domain outline!
+			if strcmpi(region(1),'~'),
+				region=region(2:length(region));
+				invert=1;
+			else
+				invert=0;
+			end
+
+			%does the region domain outline exist or do we have to look for xlim,ylim in basinzoom?
+			if ~exist(region,'file'),
+				if (length(region)>3 & ~strcmp(region(end-3),'.exp')),
+					error(['Error: File ' region ' not found!']);
+				end
+				[xlim,ylim]=basinzoom('basin',region);
+				flag_nodes=double(md.mesh.x<xlim(2) & md.mesh.x>xlim(1) &  md.mesh.y<ylim(2) & md.mesh.y>ylim(1));
+				flag=prod(flag_nodes(md.mesh.elements),2);
+			else
+				%ok, flag elements
+				flag=ContourToMesh(md.mesh.elements(:,1:3),md.mesh.x,md.mesh.y,region,'element',1);
+			end
+		end
+		if invert,
+			flag=~flag;
+		end
+	elseif isfloat(region) | islogical(region),
+		if size(region,1)~=md.mesh.numberofelements,
+			help FlagElements
+			error('Flaglist for region must be of same size as number of elements in model');
+		end
+		flag=region;
+	else
+		error('Invalid region option');
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Geometry/SegIntersect.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Geometry/SegIntersect.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Geometry/SegIntersect.m	(revision 11330)
@@ -0,0 +1,81 @@
+function bool=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:
+%      bool=SegIntersect(seg1,seg2)
+
+bool=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 vectot to segB
+
+test1=n2'*O2A;
+test2=n2'*O2B;
+
+if test1*test2>0
+	bool=0;
+	return;
+end
+
+test3=n1'*O1C;
+test4=n1'*O1D;
+
+if test3*test4>0
+	bool=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 (->bool=1)
+	if (O1C-O1A)*(O1D-O1A)<0
+		bool=1;
+		return;
+	end
+	if (O1C-O1B)*(O1D-O1B)<0
+		bool=1;
+		return;
+	end
+	if (O1A-O1C)*(O1B-O1C)<0
+		bool=1;
+		return;
+	end
+	if (O1A-O1D)*(O1B-O1D)<0
+		bool=1;
+		return;
+	end
+
+	 %test if the 2 segments have the same middle (->bool=1)
+	if O2O1==0
+		bool=1;
+		return;
+	end
+
+	%else
+	bool=0;
+	return;
+
+end
+
Index: /issm/trunk-jpl-damage/src/m/utils/Geometry/find_point.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Geometry/find_point.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Geometry/find_point.m	(revision 11330)
@@ -0,0 +1,11 @@
+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)
+
+distance=sqrt((tabx-pointx).^2+(taby-pointy).^2);
+f=find(distance==min(min(distance)));
Index: /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/gradient_perso.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/gradient_perso.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/gradient_perso.m	(revision 11330)
@@ -0,0 +1,91 @@
+function [ax,ay ]=gradient_perso(a,dx,dy,n);
+%GRADIENT_PERSO - gradient computation
+%
+%   INPUT a,dx,dy,n where a is the scalar value, dx and dy the spacing of one pixel
+%   in a and n is the width wanted in the gradient computation, in pixels.
+%
+%   Usage:
+%      [ax,ay ]=gradient_perso(a,dx,dy,n)
+
+s=size(a);
+ax=zeros(s(1),s(2));
+ay=zeros(s(1),s(2));
+
+for k=n+1:s(1)-n,
+   if mod(k,10)==0,
+      disp(k/s(1)*100);
+   end
+   
+   for j=n+1:s(2)-n,
+      if isnan(a(k,j)),
+         ax(k,j)=NaN;
+         ay(k,j)=NaN;
+      else
+         temp=a(k,j);
+         temp2=a(k,j);
+         
+         count=1;
+         while ~isnan(a(k,j+count)),
+            temp=[temp a(k,j+count)];
+            count=count+1;
+            if count>n,
+               count=count-1;
+               break;
+            end
+            
+         end
+         count=1;
+         while ~isnan(a(k,j-count)),
+            temp=[a(k,j-count) temp];
+            count=count+1;
+            if count>n,
+               count=count-1;
+               break;
+            end
+            
+         end
+         
+         count=1;
+         while ~isnan(a(k+count,j)),
+            temp2=[temp2 a(k+count,j)];
+            count=count+1;
+               if count>n,
+               count=count-1;
+               break;
+            end
+         
+         end
+         count=1;
+         while ~isnan(a(k-count,j)),
+            temp2=[a(k-count,j) temp2];
+            count=count+1;
+               if count>n,
+               count=count-1;
+               break;
+            end
+         
+         end
+    	   
+         if length(temp)==1,
+            ax(k,j)=NaN;
+         else
+            ax(k,j)=(temp(length(temp))-temp(1))/(length(temp)-1)/dx;
+         end
+         
+         if length(temp2)==1,
+            ay(k,j)=NaN;
+         else
+            ay(k,j)=(temp2(length(temp2))-temp2(1))/(length(temp2)-1)/dy;
+         end
+         
+      end
+   end
+end
+
+         
+          
+          
+          
+          
+          
+      
Index: /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/im_resize.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/im_resize.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/im_resize.m	(revision 11330)
@@ -0,0 +1,16 @@
+function newimg = im_resize(img,nw,nh)
+%IM_RESIZE - resize an image using bicubic interpolation
+%
+%   NEWIMG = IM_RESIZE(IMG,NW,NH) Given input image IMG,
+%   returns a new image NEWIMG of size NWxNH.
+%
+% Matthew Dailey 2000
+
+  if nargin ~= 3
+    error('usage: im_resize(image,new_wid,new_ht)');
+  end;
+  
+  ht_scale = size(img,1) / nh;
+  wid_scale = size(img,2) / nw;
+  
+  newimg = interp2(img,(1:nw)*wid_scale,(1:nh)'*ht_scale,'cubic');
Index: /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/immerge.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/immerge.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/immerge.m	(revision 11330)
@@ -0,0 +1,43 @@
+function out = immerge(bg, fg, coef)
+% Creates an image 'out' of same type as bg.
+% 'out' has 'bg' as background, and 'fg' (transparent, 
+% weighted by 'coef') above 'bg'.
+% Useful when one cannot use OpenGL as renderer, but still 
+% wants to have transparency!
+% 'out', 'bg', and 'fg' are RGB images.
+%
+% merged = immerged(bg, fg, coef)
+%	- bg matrix of type double or uint8
+%	- fg matrix of type double or uint8
+%	- coef is a scalar between 0 and 1, or a matrix of 
+%	  such scalars, same size as 'fg' and 'bg' (AlphaData).
+%
+% Suggestions for future development:
+%	- allow to have 'coef' referring to the AlphaMap
+%	- allow 'coef' to take values between 1 and 64.
+%
+% Gauthier Fleutot 28-07-2004
+% fleutotg@esiee.fr
+
+intOutput = 0;	% if we want the output to be of type integer
+
+if ~isa(bg, 'double')
+	bg = double(bg);	% because '-' isn't defined for uint8
+	intOutput = 1;
+end
+if ~isa(fg, 'double')
+	fg = double(fg);	% because '-' isn't defined for uint8
+end
+
+dif = fg-bg;
+
+if size(coef) == [1 1]
+	out = bg + coef.*dif;
+else
+	coef = cat(3,coef,coef,coef);	% extend the coef matric in the 3rd dim.
+	out = bg + coef .* dif;
+end
+
+if intOutput == 1
+	out = uint8(out);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/mean_congrid.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/mean_congrid.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/mean_congrid.m	(revision 11330)
@@ -0,0 +1,59 @@
+function res=mean_congrid(a,n,choice);
+%MEAN_CONGRID - average the values around a pixel
+%
+%   INPUT a,n,choice, where a is the matrix, and n the size of the area averaged around
+%   one pixel, odd number. choice=1 if the NaN values remain NaN values.
+%
+%   Usage:
+%      res=mean_congrid(a,n,choice)
+
+s=size(a);
+aa=a;
+pos=find(isnan(aa));
+aa(pos)=0;
+
+if (mod(n,2)==0),
+   disp('Cannot rebin, the dimensions of the matrix and n are not compatible');
+   break
+end
+mm=(n-1)/2;
+
+res=zeros(s(1),s(2));
+
+for m=mm+1:s(1)-mm,
+   if mod(m,10)==0,
+      disp(m/s(1)*100);
+   end
+   
+   for l=mm+1:s(2)-mm,
+      
+      
+      if sum(sum(~isnan(a(m-mm:m+mm,l-mm:l+mm))))~=0,
+      res(m,l)=sum(...
+                   sum(...
+                   ~isnan(...
+                          a(m-mm:m+mm,l-mm:l+mm)...
+                          ).*...
+                          aa(m-mm:m+mm,l-mm:l+mm)...
+                       )...
+                   )...
+                   /sum(sum(~isnan(a(m-mm:m+mm,l-mm:l+mm))));
+             else
+                res(m,l)=NaN;
+             end
+             
+   end
+end
+
+if choice==1,
+   pos=find(isnan(a));
+   res(pos)=NaN;
+end
+
+   
+
+
+
+
+
+
Index: /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/rebin.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/rebin.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/rebin.m	(revision 11330)
@@ -0,0 +1,44 @@
+function res=rebin(a,n);
+%REBIN - average values of a matrix by bloc
+%
+%   INPUT a,n, where a is the matrix, and n the size of the area averaged around
+%   one pixel
+%
+%   Usage:
+%      res=rebin(a,n)
+
+s=size(a);
+
+if (mod(s(1)/n,2)~=0 | mod(s(2)/n,2)~=0),
+   disp('Cannot rebin, the dimensions of the matrix and n are not compatible');
+   break
+end
+
+res=zeros(s(1)/n,s(2)/n);
+
+for m=1:s(1)/n,
+   for l=1:s(2)/n,
+      if sum(sum(~isnan(a((m-1)*n+1:m*n,(l-1)*n+1:l*n))))~=0,
+      res(m,l)=sum(...
+                   sum(...
+                       ~isnan(...
+                              a((m-1)*n+1:m*n,(l-1)*n+1:l*n)...
+                              ).*...
+                       a((m-1)*n+1:m*n,(l-1)*n+1:l*n)...
+                       )...
+                   )...
+                   /sum(sum(~isnan(a((m-1)*n+1:m*n,(l-1)*n+1:l*n))));
+             else
+                res(m,l)=NaN;
+             end
+             
+   end
+end
+
+   
+
+
+
+
+
+
Index: /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/transp.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/transp.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/ImageProcessing/transp.m	(revision 11330)
@@ -0,0 +1,10 @@
+bg = uint8(255.*rand(100, 100, 3));
+imview(bg);
+
+fg(:, :, 1) = uint8(255 .*(cumsum(ones(100, 100)) ./ 100));%
+fg(:, :, 2) = uint8(zeros(100));
+fg(:, :, 3) = flipud(fg(:, :, 1));
+imview(fg);
+
+res=immerge(bg, fg, .3);
+imview(res);
Index: /issm/trunk-jpl-damage/src/m/utils/Interp/FieldFindVarNames.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Interp/FieldFindVarNames.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Interp/FieldFindVarNames.m	(revision 11330)
@@ -0,0 +1,153 @@
+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
Index: /issm/trunk-jpl-damage/src/m/utils/Interp/FillHole.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Interp/FillHole.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Interp/FillHole.m	(revision 11330)
@@ -0,0 +1,39 @@
+function field=FillHole(index,x,y,field)
+%FILLHOLE - fill mesh data that has holes in it (hole is defined by field==NaN). Get the nearest neighboors to fill the holes.
+%
+%   Usage:
+%      surface=FillHole(index,x,y,surface)
+%
+%   Example:
+%      md.geometry.surface=FillHole(md.mesh.elements,x,md.mesh.y,md.geometry.surface)
+%
+
+%some checks
+if nargin~=4 | nargout~=1
+	help FillHole
+	error('FillHole error message: bad usage');
+end
+
+if length(x)~=length(y),
+	error('plugdata error message: x and y should have the same length');
+end
+
+
+pos_hole=find(isnan(field));
+pos_full=find(~isnan(field));
+
+%reduce our field to not include any holes: 
+field_noholes=field(pos_full);
+x_noholes=x(pos_full);
+y_noholes=y(pos_full);
+
+for i=1:length(pos_hole)
+
+	if (mod(i,100)==0),
+		fprintf('\b\b\b\b\b\b\b%5.2f%s',i/length(pos_hole)*100,' %');
+	end
+
+	%search the node on the closest to i, that is not in a hole either
+	[d posd]=min(sqrt((x(pos_hole(i))-x_noholes).^2+(y(pos_hole(i))-y_noholes).^2));
+	field(pos_hole(i))=field_noholes(posd);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Interp/InterpFromFile.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Interp/InterpFromFile.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Interp/InterpFromFile.m	(revision 11330)
@@ -0,0 +1,44 @@
+function data_out=InterpFromFile(x,y,filename,default_value)
+%INTERPFROMFILE - load data and interpolate on the given nodes
+%
+%   load a matlab file (extension .mat) which holds 3 or 4 variables
+%   and interpolate the data on the mesh and plug it onto the model.
+%
+%   o 3 variables
+%     - a vector x (if the name of the variable do not begin with "x", an error can appear)
+%     - a vector y (if the name of the variable do not begin with "y", an error can appear)
+%     - a vector or matrix data (if the name of the variable do not begin with the field name, an error can appear)
+%   o 4 variables
+%     - a vector x (if the name of the variable do not begin with "x", an error can appear)
+%     - a vector y (if the name of the variable do not begin with "y", an error can appear)
+%     - a matrix with 3 columns (if the name of the variable do not begin with "index" or "elements", an error can appear)
+%     - a vector data (if the name of the variable do not begin with the field name, an error can appear)
+%
+%   Usage:
+%      data=InterpFromFile(x,y,filename,default_value);
+%
+%   Example:
+%      md.geometry.surface=InterpFromFile(md.mesh.x,md.mesh.y,'surfacefile.mat',0);
+%
+%   See also: PLUGVELOCITIES, INTERPFROMGRID, INTERPFROMMESH2D, INTERPFROMMESH3D
+
+%some checks
+if nargin~=4 | nargout~=1
+	help InterpFromFile
+	error('plugdata error message: bad usage');
+end
+if ~exist(filename)
+	error(['plugdata error message: file ' filename  ' does not exist']);
+end
+if length(x)~=length(y),
+	error('plugdata error message: x and y should have the same length');
+end
+
+%load file
+Names=FieldFindVarNames(filename);
+Data=load(filename);
+if strcmpi(Names.interp,'node'),
+	data_out=InterpFromGridToMesh(Data.(Names.xname),Data.(Names.yname),Data.(Names.dataname),x,y,default_value);
+else
+	data_out=InterpFromMeshToMesh2d(Data.(Names.indexname),Data.(Names.xname),Data.(Names.yname),Data.(Names.dataname),x,y);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Interp/PatchToVec.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Interp/PatchToVec.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Interp/PatchToVec.m	(revision 11330)
@@ -0,0 +1,21 @@
+function vec=PatchToVec(Patch);
+%PATCHTOVEC - converts a patch to a vector by averaging over each vertex
+%
+%   Usage:
+%      vec=PatchToVec(Patch)
+
+%if the patch is P0: we have element values, return an element vector
+switch(size(Patch.value,2)),
+	case 1,
+		vec(Patch.element)=Patch.value;
+	case 3,
+		connectivity=sparse(Patch.index(:),1,1);
+		value       =sparse(Patch.index(:),1,Patch.value(:));
+		vec=full(value./connectivity);
+	case 6,
+		connectivity=sparse(Patch.index(:),1,1);
+		value       =sparse(Patch.index(:),1,Patch.value(:));
+		vec=full(value./connectivity);
+	otherwise,
+		error('interpolation not supported yet');
+	end
Index: /issm/trunk-jpl-damage/src/m/utils/Interp/VelFindVarNames.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Interp/VelFindVarNames.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Interp/VelFindVarNames.m	(revision 11330)
@@ -0,0 +1,122 @@
+function Names=VelFindVarNames(filename)
+%VELFINDVARNAMES - find names of variables in a velocity data set file
+%
+%   This routines looks at the variables contained in a file and finds out
+%   the names of the variables that are needed for an interpolation (x,y,vx,vy)
+%   or (index,x,y,vx,vy)
+%
+%   Usage:
+%      Names=VelFindVarNames(filename)
+%
+%   Example:
+%      Names=VelFindVarNames('velocities.mat')
+%
+%   See also: INTERPFROMFILE, GRIDDATA
+
+%some checks
+if nargin~=1 | nargout~=1
+	help VelFindVarNames
+	error('VelFindVarNames error message: bad usage');
+end
+if ~exist(filename)
+	error(['VelFindVarNames error message: file ' filename  ' does not exist']);
+end
+
+%Get variables
+A=whos('-file',filename);
+
+%find x,y,vx and vy
+xenum=NaN; yenum=NaN; vxenum=NaN; vyenum=NaN; indexenum=NaN;
+if length(A)==4,
+	isnode=1;
+	for i=1:4
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		else
+			if (strcmpi(A(i).name(end),'x') | strncmpi(A(i).name,'vx',2));
+				vxenum=i;
+			elseif (strcmpi(A(i).name(end),'y') | strncmpi(A(i).name,'vy',2));
+				vyenum=i;
+			end
+		end
+	end
+elseif length(A)==5,
+	isnode=0;
+	for i=1:5
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		elseif (strcmpi(A(i).name(1),'index') | strcmpi(A(i).name(1),'elements'));
+			indexenum=i;
+		else
+			if (strcmpi(A(i).name(end),'x') | strncmpi(A(i).name,'vx',2));
+				vxenum=i;
+			elseif (strcmpi(A(i).name(end),'y') | strncmpi(A(i).name,'vy',2));
+				vyenum=i;
+			end
+		end
+	end
+else
+	error(['VelFindVarNames error message: file ' filename  ' not supported yet (it should hold 4 variables x,y,vx and vy (for nodes) OR 5 variables  x,y,index,vx and vy (for mesh))']);
+end
+
+%assum that we have found at least vxenum and vyenum
+if ( isnan(vxenum) | isnan(vyenum))
+	error(['VelFindVarNames error message: file ' filename  ' not supported yet (the velocities should be named vx and vy)']);
+end
+
+%find index
+if (~isnode & isnan(indexenum)),
+	for i=1:5
+		lengthi=min(A(i).size);
+		if (lengthi==3),
+			indexenum=i;
+		end
+	end
+	if isnan(indexenum),
+		error(['VelFindVarNames error message: file ' filename  ' not supported yet (index not found)']);
+	end
+end
+
+%find x y
+if (isnan(xenum) | isnan(yenum))
+
+	%check the size
+	if A(vxenum).size(1)==A(vxenum).size(2),
+		error(['VelFindVarNames error message: file ' filename  ' not supported (velocities is a square matrix, save x and y with another name)']);
+	end
+	if ~(A(vxenum).size(1)==A(vyenum).size(1) & A(vxenum).size(2)==A(vyenum).size(2)),
+		error(['VelFindVarNames error message: file ' filename  ' not supported (vx and vy matrices do not have the same size)']);
+	end
+
+	%find xenum and yenum
+	for i=1:4
+		lengthi=max(A(i).size);
+		if ((i~=vxenum) & (lengthi==A(vxenum).size(1) | lengthi==A(vxenum).size(1)+1)),
+			yenum=i;
+		elseif ((i~=vxenum) & (lengthi==A(vxenum).size(2) | lengthi==A(vxenum).size(2)+1)),
+			xenum=i;
+		end
+	end
+
+	%last check
+	if (isnan(xenum) | isnan(yenum))
+		error(['plugdata error message: file ' filename  ' not supported yet']);
+	end
+end
+
+%create output
+Names=struct();
+Names.xname=A(xenum).name;
+Names.yname=A(yenum).name;
+Names.vxname=A(vxenum).name;
+Names.vyname=A(vyenum).name;
+if ~isnode,
+	Names.indexname=A(indexenum).name; 
+	Names.interp='mesh';
+else
+	Names.interp='node';
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Interp/plugvelocities.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Interp/plugvelocities.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Interp/plugvelocities.m	(revision 11330)
@@ -0,0 +1,41 @@
+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
+
+%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;
Index: /issm/trunk-jpl-damage/src/m/utils/Kml/exp2kml.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Kml/exp2kml.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Kml/exp2kml.m	(revision 11330)
@@ -0,0 +1,19 @@
+function exp2kml(input,output)
+%EXP2KML: transform Argus exp file to kml
+%
+% Usage:    exp2kml('temp.exp','temp2.kml')
+%
+%
+
+
+%First, read exp file
+domain=expread(input,1);
+
+
+%then transform: 
+string=ge_plot(domain.x,domain.y,'name',domain.name);
+
+%open kml file for writing: 
+fid=fopen(output,'w');
+fprintf(fid,'%s',string);
+fclose(fid);
Index: /issm/trunk-jpl-damage/src/m/utils/Kml/kml2exp.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Kml/kml2exp.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Kml/kml2exp.m	(revision 11330)
@@ -0,0 +1,29 @@
+function kml2exp(input,output)
+%KML2EXP: transform kml file Argus exp file.
+%
+% Usage:    kmltoexp('temp.kml','temp2.exp')
+%
+%
+
+
+
+
+%First, read polygon kml file.
+structure=kml_shapefile(input);
+	
+%create exp file: 
+domain=struct();
+for i=1:length(structure),
+
+	if isfield(structure,'name'),
+		domain(end+1).name=structure(i).name;
+	else
+		domain(end+1).name='NaN';
+	end
+
+	domain(end).density=1;
+	domain(end).x=structure(i).X;
+	domain(end).y=structure(i).Y;
+end
+domain=domain(2:end);
+expwrite(domain,output);
Index: /issm/trunk-jpl-damage/src/m/utils/Kml/kml2expg.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Kml/kml2expg.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Kml/kml2expg.m	(revision 11330)
@@ -0,0 +1,13 @@
+function kml2expg(filename)
+
+	[path,name,ext]=fileparts(filename);
+
+	if strcmpi(ext,'.kmz'),
+		eval(['!unzip ' filename]);
+		eval(['!mv doc.kml ' name '.kml']);
+		kml2exp([name '.kml'],[name '.exp']);
+		expll2xy([name '.exp'],1);
+	end
+
+	kml2exp([name '.kml'],[name '.exp']);
+	expll2xy([name '.exp'],1);
Index: /issm/trunk-jpl-damage/src/m/utils/LatLong/ll2xy.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/LatLong/ll2xy.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/LatLong/ll2xy.m	(revision 11330)
@@ -0,0 +1,66 @@
+function [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)  
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==5,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==3
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help ll2xy
+	error('bad usage');
+end
+
+% Conversion constant from degrees to radians
+cde  = 57.29577951;
+% Radius of the earth in meters
+re   = 6378.273*10^3;
+% Eccentricity of the Hughes ellipsoid squared
+ex2   = .006693883;
+% Eccentricity of the Hughes ellipsoid
+ex    =  sqrt(ex2);
+
+latitude  = abs(lat) * pi/180.;
+longitude = (lon + delta) * pi/180.;
+
+% compute X and Y in grid coordinates.
+T = tan(pi/4-latitude/2) ./ ((1-ex*sin(latitude))./(1+ex*sin(latitude))).^(ex/2);
+
+if (90 - slat) <  1.e-5 
+	rho = 2.*re*T/sqrt((1.+ex)^(1.+ex)*(1.-ex)^(1.-ex));
+else
+	sl  = slat*pi/180.;
+	tc  = tan(pi/4.-sl/2.)/((1.-ex*sin(sl))/(1.+ex*sin(sl)))^(ex/2.);
+	mc  = cos(sl)/sqrt(1.0-ex2*(sin(sl)^2));
+	rho = re*mc*T/tc;
+end
+
+y = -rho .* sgn .* cos(sgn.*longitude);
+x =  rho .* sgn .* sin(sgn.*longitude);
+
+[cnt1,cnt2] = find(latitude >= pi / 2.);
+
+if cnt1
+	x(cnt1,1) = 0.0;
+	y(cnt1,1) = 0.0;
+end
Index: /issm/trunk-jpl-damage/src/m/utils/LatLong/pargenerate.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/LatLong/pargenerate.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/LatLong/pargenerate.m	(revision 11330)
@@ -0,0 +1,45 @@
+function pargenerate(filename,xm,ym,data,varargin)
+%PARGENERATE - generate parameter file for images ala Rignot
+%
+%   Usage: 
+%      pargenerate(filename,data,xm,ym,options);
+%
+%   Supported options:
+%      - title: dataset title
+%      - latitude: standard latitude (degree)
+%      - meridian: meridian (degree)
+%      - format: binary format
+
+%process options
+options=pairoptions(varargin{:});
+Title=getfieldvalue(options,'title','N/A');
+latitude=getfieldvalue(options,'latitude','N/A');
+meridian=getfieldvalue(options,'meridian','N/A');
+format=getfieldvalue(options,'format','single');
+
+%Get data info
+[nlines ncols]=size(data);
+xmin=min(xm);
+ymax=max(ym);
+postx=abs(xm(2)-xm(1));
+posty=abs(ym(2)-ym(1));
+
+%Open header file and get machine type
+fid=fopen(filename,'wt');
+[filename, permission, machineformat, encoding] = fopen(fid);
+
+%write header file
+fprintf(fid,'%s\n','ISSM gridded dataset parameter file');
+fprintf(fid,'%s%s\n','title: ',Title);
+fprintf(fid,'%s  \n','DEM_projection: PS');
+fprintf(fid,'%s%s\n','data_format: ',format);
+fprintf(fid,'%s%s\n','endian:      ',machineformat);
+fprintf(fid,'%s%d\n','width:  ',ncols);
+fprintf(fid,'%s%d\n','nlines: ',nlines);
+fprintf(fid,'%s%g%s\n','PS_secant_lat:    ',latitude,'   decimal degrees');
+fprintf(fid,'%s%g%s\n','PS_meridian_long: ',meridian,'   decimal degrees');
+fprintf(fid,'%s%-15.10g\n','PS_corner_north:  ',ymax);
+fprintf(fid,'%s%-15.10g\n','PS_corner_east:   ',xmin);
+fprintf(fid,'%s%g%s\n','PS_post_north:    ',postx,' m');
+fprintf(fid,'%s%g%s\n','PS_post_east:     ',posty,' m');
+fclose(fid);
Index: /issm/trunk-jpl-damage/src/m/utils/LatLong/utm2ll.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/LatLong/utm2ll.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/LatLong/utm2ll.m	(revision 11330)
@@ -0,0 +1,117 @@
+function  [Lat,Lon] = utm2ll(xx,yy,utmzone)
+% -------------------------------------------------------------------------
+% [Lat,Lon] = utm2ll(x,y,utmzone)
+%
+% Description: Function to convert vectors of UTM coordinates into Lat/Lon vectors (WGS84).
+% Some code has been extracted from UTMIP.m function by Gabriel Ruiz Martinez.
+%
+% Inputs:on)
+%    -3.485713    7.801235 -119.955246  -17.759537  -94.799019  121.640266
+%
+% Example 2: If you need Lat/Lon coordinates in Degrees, Minutes and Seconds
+% [Lat, Lon]=utm2ll(x,y,utmzone);
+% LatDMS=dms2mat(deg2dms(Lat))
+%LatDMS =
+%    40.00         18.00         55.55
+%    46.00         17.00          2.01
+%    37.00         34.00         40.17
+%    28.00         38.00         44.33
+%    38.00         51.00         19.96
+%    25.00          3.00         42.41
+% LonDMS=dms2mat(deg2dms(Lon))
+%LonDMS =
+%    -3.00         29.00          8.61
+%     7.00         48.00          4.40
+%  -119.00         57.00         18.93
+%   -17.00         45.00         34.33
+%   -94.00         47.00         56.47
+%   121.00         38.00         24.96
+%
+% Author:
+%   Rafael Palacios
+%   Universidad Pontificia Comillas
+%   Madrid, Spain
+% Version: Apr/06, Jun/06, Aug/06
+% Aug/06: corrected m-Lint warnings
+%-------------------------------------------------------------------------
+
+% Argument checking
+%
+error(nargchk(3, 3, nargin)); %3 arguments required
+n1=length(xx);
+n2=length(yy);
+n3=size(utmzone,1);
+if (n1~=n2 || n1~=n3)
+	error('x,y and utmzone vectors should have the same number or rows');
+end
+c=size(utmzone,2);
+if (c~=4)
+	error('utmzone should be a vector of strings like "30 T"');
+end
+
+% Memory pre-allocation
+%
+Lat=zeros(n1,1);
+Lon=zeros(n1,1);
+
+% Main Loop
+%
+for i=1:n1
+	if (utmzone(i,4)>'X' || utmzone(i,4)<'C')
+		fprintf('utm2ll: Warning utmzone should be a vector of strings like "30 T", not "30 t"\n');
+	end
+	if (utmzone(i,4)>'M')
+		hemis='N';   % Northern hemisphere
+	else
+		hemis='S';
+	end
+
+	x=xx(i);
+	y=yy(i);
+	zone=str2double(utmzone(i,1:2));
+
+	sa = 6378137.000000 ; sb = 6356752.314245;
+
+	%   e = ( ( ( sa ^ 2 ) - ( sb ^ 2 ) ) ^ 0.5 ) / sa;
+	e2 = ( ( ( sa ^ 2 ) - ( sb ^ 2 ) ) ^ 0.5 ) / sb;
+	e2cuadrada = e2 ^ 2;
+	c = ( sa ^ 2 ) / sb;
+	%   alpha = ( sa - sb ) / sa;             %f
+	%   ablandamiento = 1 / alpha;   % 1/f
+
+	X = x - 500000;
+
+	if hemis == 'S' || hemis == 's'
+		Y = y - 10000000;
+	else
+		Y = y;
+	end
+
+	S = ( ( zone * 6 ) - 183 );
+	lat =  Y / ( 6366197.724 * 0.9996 );
+	v = ( c / ( ( 1 + ( e2cuadrada * ( cos(lat) ) ^ 2 ) ) ) ^ 0.5 ) * 0.9996;
+	a = X / v;
+	a1 = sin( 2 * lat );
+	a2 = a1 * ( cos(lat) ) ^ 2;
+	j2 = lat + ( a1 / 2 );
+	j4 = ( ( 3 * j2 ) + a2 ) / 4;
+	j6 = ( ( 5 * j4 ) + ( a2 * ( cos(lat) ) ^ 2) ) / 3;
+	alfa = ( 3 / 4 ) * e2cuadrada;
+	beta = ( 5 / 3 ) * alfa ^ 2;
+	gama = ( 35 / 27 ) * alfa ^ 3;
+	Bm = 0.9996 * c * ( lat - alfa * j2 + beta * j4 - gama * j6 );
+	b = ( Y - Bm ) / v;
+	Epsi = ( ( e2cuadrada * a^ 2 ) / 2 ) * ( cos(lat) )^ 2;
+	Eps = a * ( 1 - ( Epsi / 3 ) );
+	nab = ( b * ( 1 - Epsi ) ) + lat;
+	senoheps = ( exp(Eps) - exp(-Eps) ) / 2;
+	Delt = atan(senoheps / (cos(nab) ) );
+	TaO = atan(cos(Delt) * tan(nab));
+	longitude = (Delt *(180 / pi ) ) + S;
+	latitude = ( lat + ( 1 + e2cuadrada* (cos(lat)^ 2) - ( 3 / 2 ) * e2cuadrada * sin(lat) * cos(lat) * ( TaO - lat ) ) * ( TaO - lat ) ) * ...
+		(180 / pi);
+
+	Lat(i)=latitude;
+	Lon(i)=longitude;
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/LatLong/xy2ll.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/LatLong/xy2ll.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/LatLong/xy2ll.m	(revision 11330)
@@ -0,0 +1,72 @@
+function [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel)
+%XY2LL - converts xy to lat long
+%
+%   Converts Polar  Stereographic (X,Y) coordinates for the polar regions to
+%   latitude and longitude Stereographic (X,Y) coordinates for the polar
+%   regions.
+%   Author: Michael P. Schodlok, December 2003 (map2xy.m)
+%
+%   Usage:
+%      [lat,lon] = xy2ll(x,y,sgn);
+%      [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel);
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==5,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==3
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help xy2ll
+	error('bad usage');
+end
+
+% Conversion constant from degrees to radians
+cde  = 57.29577951;
+% Radius of the earth in meters
+re   = 6378.273*10^3;
+% Eccentricity of the Hughes ellipsoid squared
+ex2   = .006693883;
+% Eccentricity of the Hughes ellipsoid
+ex    =  sqrt(ex2);
+
+sl  = slat*pi/180.;
+rho = sqrt(x.^2 + y.^2);
+cm = cos(sl) / sqrt(1.0 - ex2 * (sin(sl)^2));
+T = tan((pi / 4.0) - (sl / 2.0)) / ((1.0 - ex * sin(sl)) / (1.0 + ex * sin(sl)))^(ex / 2.0);
+
+if  abs(slat-90.) < 1.e-5
+	T = rho * sqrt((1. + ex)^(1. + ex) * (1. - ex)^(1. - ex)) / 2. / re;
+else
+	T = rho * T / (re * cm);
+end
+
+chi = (pi / 2.0) - 2.0 * atan(T);
+lat = chi + ((ex2 / 2.0) + (5.0 * ex2^2.0 / 24.0) + (ex2^3.0 / 12.0)) * ...
+	sin(2 * chi) + ((7.0 * ex2^2.0 / 48.0) + (29.0 * ex2^3 / 240.0)) * ...
+	sin(4.0 * chi) + (7.0 * ex2^3.0 / 120.0) * sin(6.0 * chi) ;
+
+lat = sgn * lat;
+lon = atan2(sgn * x,-sgn * y);
+lon = sgn * lon;
+
+[res1,res2] = find(rho <= 0.1);
+if res1
+	lat(res1,1) = 90. * sgn;
+	lon(res1,1) = 0.0;
+end
+
+lon = lon * 180. / pi;
+lat = lat * 180. / pi;
+lon = lon - delta; 
Index: /issm/trunk-jpl-damage/src/m/utils/Math/fixdec.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Math/fixdec.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Math/fixdec.m	(revision 11330)
@@ -0,0 +1,41 @@
+function y = fixdec(x, n)
+%FIXDEC -  Round towards zero with a specified number of decimals.
+%
+%   This routine rounds the elements of X to N decimals.
+%
+%   Usage:
+%      y = fixdec(x, n)
+%
+%   Example:
+%      fixdec(10*sqrt(2) + i*pi/10, 4) returns 14.1421 + 0.3141i
+%
+%   See also: FIX, FLOOR, CEIL, ROUND, FIXDIG, ROUNDDEC, ROUNDDIG.
+
+%   Author:      Peter J. Acklam
+%   Time-stamp:  2004-09-22 20:08:10 +0200
+%   E-mail:      pjacklam@online.no
+%   URL:         http://home.online.no/~pjacklam
+
+   % Check number of input arguments.
+   error(nargchk(2, 2, nargin));
+
+   % Quick exit if either argument is empty.
+   if (isempty(x) |isempty(n))
+      y = [];
+      return
+   end
+
+   % Get size of input arguments.
+   size_x   = size(x);
+   size_n   = size(n);
+   scalar_x = all(size_x == 1);           % True if x is a scalar.
+   scalar_n = all(size_n == 1);           % True if n is a scalar.
+
+   % Check size of input arguments.
+   if ~scalar_x & ~scalar_n & ~isequal(size_x, size_n)
+      error(['When both arguments are non-scalars they must have' ...
+             ' the same size']);
+   end
+
+   f = 10.^n;
+   y = fix(x .* f) ./ f;
Index: /issm/trunk-jpl-damage/src/m/utils/Math/isnans.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Math/isnans.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Math/isnans.m	(revision 11330)
@@ -0,0 +1,15 @@
+function returnvalue=isnans(array)
+%ISNANS: figure out if an array is nan. wrapper to isnan from matlab which stupidly does not allow this test  for structures!
+%
+%  Usage:    isnans(array)
+%
+%  See also : ISNAN 
+
+
+if isstruct(array), 
+	returnvalue=0;
+elseif iscell(array)
+	returnvalue=0;
+else
+	returnvalue=isnan(array);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Math/round_ice.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Math/round_ice.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Math/round_ice.m	(revision 11330)
@@ -0,0 +1,38 @@
+function new_x=round_ice(x,numnonzeros)
+%ROUND_ICE - rounds up x so that it has only numnonzeros non zero digits
+%
+%   numnonzeros must be an integer larger or equal to 1
+%
+%   Usage:
+%      new_x=round_ice(x,numnonzeros)
+
+%some checks
+if (nargin ~=2 | nargout>1),
+	error('round_ice usage: new_x=round_ice(x,numonzeros)');
+end
+if ~isnumeric(x)
+	error('round_ice error message: x must be a number and numzeros an integer');
+end
+if round(numnonzeros)~=numnonzeros
+	error('round_ice error message: numnonzeros must be an integer larger or equal to 1')
+end
+if any(numnonzeros<1)
+	error('round_ice error message: numnonzeros must be an integer larger or equal to 1')
+end
+if (length(numnonzeros)~=1 & size(numnonzeros)~=size(x))
+	error('round_ice error message: numnonzeros must be an integer larger or equal to 1 or a list of integers of length length(x)')
+end
+
+%figure out how long x is
+lengthx=ceil(log10(abs(x)));
+
+%if x contains 0, lengthx=-Inf
+lengthx(isinf(lengthx))=1;
+
+%get its sign
+si=sign(x);
+
+%rule out zeros
+new_x=si.*round(abs(x).*10.^(-lengthx+numnonzeros)).*10.^(lengthx-numnonzeros);
+
+
Index: /issm/trunk-jpl-damage/src/m/utils/Meca/carter.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Meca/carter.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Meca/carter.m	(revision 11330)
@@ -0,0 +1,28 @@
+function attenuation=carter(temperature)
+%CARTER - attenuation as a function of temperature
+%
+%   TWO WAY - Attenuation (in dB/m) as a function of temperature (K)
+%   From Carter at al. 2007 (Radar-based subglacial lake classification in Antarctica)
+%   Figure 4
+%
+%   Usage:
+%      attenuation=carter(temperature)
+
+if(temperature<0)
+	error('input temperature should be in Kelvin (positive)');
+end
+T=temperature-273.15;
+
+Temp=[-50 -45 -40 -35 -30 -25 -20 -15 -10 -5 0]';
+A=[0.0015 0.002 0.003 0.0042 0.0055 0.0083 0.012 0.0175 0.026 0.038 0.055]';
+
+%Now, do a cubic fit between Temp and B: 
+[cfun,gof,output]=fit(Temp,A,'cubicspline');
+%breaks=cfun.p.breaks;
+%coeff=cfun.p.coefs;
+
+%Calculate attenuation
+attenuation=cfun(T);
+
+%Make it a 2 way attenuation
+attenuation=2*attenuation;
Index: /issm/trunk-jpl-damage/src/m/utils/Meca/effective_value.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Meca/effective_value.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Meca/effective_value.m	(revision 11330)
@@ -0,0 +1,18 @@
+function effective_value=effective_value(A)
+%EFFECTIVE_VALUE - compute the effective value of any matrix
+%
+%   effective(A)= 1/sqrt(2)*sqrt(sum(Aij^2))
+%
+%   Usage:
+%      effective_value=effective_value(A)
+
+[row,col]=size(A);
+
+SUM=0;
+for i=1:row
+    for j=1:col
+        SUM=SUM+A(i,j)^2;
+    end
+end
+
+effective_value=1/sqrt(2)*sqrt(SUM);
Index: /issm/trunk-jpl-damage/src/m/utils/Meca/glen_coefficients.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Meca/glen_coefficients.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Meca/glen_coefficients.m	(revision 11330)
@@ -0,0 +1,26 @@
+function [A ,B]=glen_coefficients(Ao,T);
+%GLEN_COEFFICIENTS - compute A and B, given the temperature and Ao
+%
+%   Ao,T according to patterson,Ao in s-1kPa-3.
+%   values range between 3.9 and 5.3*10^-16;
+%   Return: A in s-1kPa-3. B in Pa.a1/3
+%
+%   Usage:
+%      [A ,B]=glen_coefficients(Ao,T)
+
+To=263;
+R=8.314;
+E1=139000;
+E2=60000;
+
+%For T>263,
+Ac1=Ao*exp(E1/R/To);
+%For T<263,
+Ac2=Ao*exp(E2/R/To);
+
+A=Ac1*exp(-E1/R./T);
+pos=find(T<263);
+A(pos)=Ac2*exp(-E2/R./T(pos));
+
+B=(A*365*24*3600).^(-1/3);
+
Index: /issm/trunk-jpl-damage/src/m/utils/Meca/lithostaticpressure.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Meca/lithostaticpressure.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Meca/lithostaticpressure.m	(revision 11330)
@@ -0,0 +1,7 @@
+function pressure=lithostaticpressure(rho_ice,g,s,z);
+%LITHOSTATICPRESSURE - compute the lithostatic pressure
+%
+%   Usage:
+%      pressure=lithostacticpressure(rho_ice,g,surface,z)
+
+pressure=rho_ice*g*(s-z);
Index: /issm/trunk-jpl-damage/src/m/utils/Meca/paterson.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Meca/paterson.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Meca/paterson.m	(revision 11330)
@@ -0,0 +1,42 @@
+function rigidity=paterson(temperature)
+%PATERSON - figure out the rigidity of ice for a given temperature
+%
+%   rigidigty (in s^(1/3)Pa) is the flow law paramter in the flow law sigma=B*e(1/3) (Paterson, p97). 
+%   temperature is in Kelvin degrees
+%
+%   Usage:
+%      rigidity=paterson(temperature)
+
+if(temperature<0)
+	error('input temperature should be in Kelvin (positive)');
+end
+T=temperature-273.15;
+
+%The routine below is equivalent to:
+
+% n=3; T=temperature-273;
+% %From paterson,
+% Temp=[0;-2;-5;-10;-15;-20;-25;-30;-35;-40;-45;-50];
+% A=[6.8*10^-15;2.4*10^-15;1.6*10^-15;4.9*10^-16;2.9*10^-16;1.7*10^-16;9.4*
+% 10^-17;5.1*10^-17;2.7*10^-17;1.4*10^-17;7.3*10^-18;3.6*10^-18];;%s-1(kPa-3)
+% %Convert into rigidity B
+% B=A.^(-1/n)*10^3; %s^(1/3)Pa
+% %Now, do a cubic fit between Temp and B: 
+% fittedmodel=fit(Temp,B,'cubicspline');
+% rigidity=fittedmodel(temperature);
+
+rigidity=zeros(length(T),1);
+pos1=find(T<=-45);           rigidity(pos1)=10^8*(-0.000292866376675*(T(pos1)+50).^3+ 0.011672640664130*(T(pos1)+50).^2  -0.325004442485481*(T(pos1)+50)+  6.524779401948101);
+pos2=find(-45<=T & T<-40);   rigidity(pos2)=10^8*(-0.000292866376675*(T(pos2)+45).^3+ 0.007279645014004*(T(pos2)+45).^2  -0.230243014094813*(T(pos2)+45)+  5.154964909039554);
+pos3=find(-40<=T & T<-35);   rigidity(pos3)=10^8*(0.000072737147457*(T(pos3)+40).^3+  0.002886649363879*(T(pos3)+40).^2  -0.179411542205399*(T(pos3)+40)+  4.149132666831214);
+pos4=find(-35<=T & T<-30);   rigidity(pos4)=10^8*(-0.000086144770023*(T(pos4)+35).^3+ 0.003977706575736*(T(pos4)+35).^2  -0.145089762507325*(T(pos4)+35)+  3.333333333333331);
+pos5=find(-30<=T & T<-25);   rigidity(pos5)=10^8*(-0.000043984685769*(T(pos5)+30).^3+ 0.002685535025386*(T(pos5)+30).^2  -0.111773554501713*(T(pos5)+30)+  2.696559088937191);
+pos6=find(-25<=T & T<-20);   rigidity(pos6)=10^8*(-0.000029799523463*(T(pos6)+25).^3+ 0.002025764738854*(T(pos6)+25).^2  -0.088217055680511*(T(pos6)+25)+  2.199331606342181);
+pos7=find(-20<=T & T<-15);   rigidity(pos7)=10^8*(0.000136920904777*(T(pos7)+20).^3+  0.001578771886910*(T(pos7)+20).^2  -0.070194372551690*(T(pos7)+20)+  1.805165505978111);
+pos8=find(-15<=T & T<-10);   rigidity(pos8)=10^8*(-0.000899763781026*(T(pos8)+15).^3+ 0.003632585458564*(T(pos8)+15).^2  -0.044137585824322*(T(pos8)+15)+  1.510778053489523);
+pos9=find(-10<=T & T<-5);    rigidity(pos9)=10^8*(0.001676964325070*(T(pos9)+10).^3-  0.009863871256831*(T(pos9)+10).^2  -0.075294014815659*(T(pos9)+10)+  1.268434288203714);
+pos10=find(-5<=T & T<-2);    rigidity(pos10)=10^8*(-0.003748937622487*(T(pos10)+5).^3+0.015290593619213*(T(pos10)+5).^2  -0.048160403003748*(T(pos10)+5)+  0.854987973338348);
+pos11=find(-2<=T);           rigidity(pos11)=10^8*(-0.003748937622488*(T(pos11)+2).^3-0.018449844983174*(T(pos11)+2).^2  -0.057638157095631*(T(pos11)+2)+  0.746900791092860);
+
+%Now make sure that rigidity is positive
+pos=find(rigidity<0);        rigidity(pos)=10^6;
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/BamgCall.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/BamgCall.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/BamgCall.m	(revision 11330)
@@ -0,0 +1,84 @@
+function md=BamgCall(md,field,hmin,hmax,gradation,epsilon),
+%BAMGCALL - call bam
+%
+%   build a metric using the Hessian of the given field
+%   call Bamg and the output mesh is plugged onto the model
+%   -hmin = minimum edge length (m)
+%   -hmax = maximum edge length (m)
+%   -gradation = maximum edge length gradation between 2 elements
+%   -epsilon = average error on each element (m/yr)
+%
+%   Usage:
+%      md=BamgCall(md,field,hmin,hmax,gradation,epsilon);
+%
+%   Example:
+%      md=BamgCall(md,md.inversion.vel_obs,1500,10^8,1.3,0.9);
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%Compute Hessian
+t1=clock; fprintf('%s','      computing Hessian...');
+hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,field,'node');
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%Compute metric
+t1=clock; fprintf('%s','      computing metric...');
+if length(md.nodeonwater)==md.mesh.numberofvertices,
+	pos=find(md.nodeonwater);
+else
+	pos=[];
+end
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+fid=fopen('carre0.met','w');
+fprintf(fid,'%i %i\n',md.mesh.numberofvertices,3);
+fprintf(fid,'%i %i %i\n',metric');
+fclose(fid);
+
+fid=fopen('carre0.mesh','w');
+
+%initialiation
+fprintf(fid,'%s %i\n','MeshVersionFormatted',0);
+
+%dimension
+fprintf(fid,'\n%s\n%i\n','Dimension',2);
+
+%Vertices
+fprintf(fid,'\n%s\n%i\n\n','Vertices',md.mesh.numberofvertices);
+fprintf(fid,'%8g %8g %i\n',[md.mesh.x md.mesh.y ones(md.mesh.numberofvertices,1)]');
+
+%Triangles
+fprintf(fid,'\n\n%s\n%i\n\n','Triangles',md.mesh.numberofelements);
+fprintf(fid,'%i %i %i %i\n',[md.mesh.elements ones(md.mesh.numberofelements,1)]');
+numberofelements1=md.mesh.numberofelements;
+
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call bamg
+fprintf('%s\n','      call Bamg...');
+system(['bamg -ratio ' num2str(gradation) ' -splitpbedge -nbv 1000000 -M carre0.met -b carre0.mesh -o carre1.mesh']);
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+A=meshread('carre1.mesh');
+md.mesh.x=A.x;
+md.mesh.y=A.y;
+md.z=zeros(A.nods,1);
+md.mesh.elements=A.index;
+md.mesh.numberofvertices=A.nods;
+md.mesh.numberofelements=A.nels;
+numberofelements2=md.mesh.numberofelements;
+t2=clock;fprintf('%s\n\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%display number of elements
+fprintf('\n%s %i','      inital number of elements:',numberofelements1);
+fprintf('\n%s %i\n\n','      new    number of elements:',numberofelements2);
+
+%clean up:
+system('rm carre0.mesh carre0.met carre1.mesh carre1.mesh.gmsh');
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/BamgCallFromMetric.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/BamgCallFromMetric.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/BamgCallFromMetric.m	(revision 11330)
@@ -0,0 +1,65 @@
+function md=BamgCallFromMetric(md,metric,gradation),
+%BAMGCALL - call bam
+%
+%   call Bamg and the output mesh is plugged onto the model
+%   -gradation = maximum edge length gradation between 2 elements
+%
+%   Usage:
+%      md=BamgCallFromMetric(md,metric,gradation);
+%
+%   Example:
+%      md=BamgCall(md,metric,1500,10^8,1.3,0.9);
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+fid=fopen('carre0.met','w');
+fprintf(fid,'%i %i\n',md.mesh.numberofvertices,3);
+fprintf(fid,'%i %i %i\n',metric');
+fclose(fid);
+
+fid=fopen('carre0.mesh','w');
+
+%initialiation
+fprintf(fid,'%s %i\n','MeshVersionFormatted',0);
+
+%dimension
+fprintf(fid,'\n%s\n%i\n','Dimension',2);
+
+%Vertices
+fprintf(fid,'\n%s\n%i\n\n','Vertices',md.mesh.numberofvertices);
+fprintf(fid,'%8g %8g %i\n',[md.mesh.x md.mesh.y ones(md.mesh.numberofvertices,1)]');
+
+%Triangles
+fprintf(fid,'\n\n%s\n%i\n\n','Triangles',md.mesh.numberofelements);
+fprintf(fid,'%i %i %i %i\n',[md.mesh.elements ones(md.mesh.numberofelements,1)]');
+numberofelements1=md.mesh.numberofelements;
+
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call bamg
+fprintf('%s\n','      call Bamg...');
+system(['bamg -ratio ' num2str(gradation) ' -splitpbedge -nbv 1000000 -M carre0.met -b carre0.mesh -o carre1.mesh']);
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+A=meshread('carre1.mesh');
+md.mesh.x=A.x;
+md.mesh.y=A.y;
+md.z=zeros(A.nods,1);
+md.mesh.elements=A.index;
+md.mesh.numberofvertices=A.nods;
+md.mesh.numberofelements=A.nels;
+numberofelements2=md.mesh.numberofelements;
+t2=clock;fprintf('%s\n\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%display number of elements
+fprintf('\n%s %i','      inital number of elements:',numberofelements1);
+fprintf('\n%s %i\n\n','      new    number of elements:',numberofelements2);
+
+%clean up:
+system('rm carre0.mesh carre0.met carre1.mesh carre1.mesh.gmsh');
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/ComputeHessian.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/ComputeHessian.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/ComputeHessian.m	(revision 11330)
@@ -0,0 +1,60 @@
+function hessian=ComputeHessian(index,x,y,field,type)
+%COMPUTEHESSIAN - compute hessian matrix from a field
+%
+%   Compute the hessian matrix of a given field
+%   return the three components Hxx Hxy Hyy
+%   for each element or each node
+%
+%   Usage:
+%      hessian=ComputeHessian(index,x,y,field,type)
+%
+%   Example:
+%      hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,md.inversion.vel_obs,'node')
+
+%some variables
+numberofnodes=length(x);
+numberofelements=size(index,1);
+
+%some checks
+if length(field)~=numberofnodes & length(field)~=numberofelements,
+	error('ComputeHessian error message: the given field size not supported yet');
+end
+if strcmpi(type,'node') & strcmpi(type,'element'),
+	error('ComputeHessian error message: only ''node'' or ''element'' type supported yet');
+end
+
+%initialization
+line=index(:);
+linesize=3*numberofelements;
+
+%get areas and  nodal functions coefficients N(x,y)=alpha x + beta y + gamma 
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+areas=GetAreas(index,x,y);
+
+%comput weights that holds the volume of all the element holding the node i
+weights=sparse(line,ones(linesize,1),repmat(areas,3,1),numberofnodes,1);
+
+%compute field on nodes if on elements
+if length(field)==numberofelements,
+	field=sparse(line,ones(linesize,1),repmat(areas.*field,3,1),numberofnodes,1)./weights ;
+end
+
+%Compute gradient for each element
+grad_elx=sum(field(index).*alpha,2); 
+grad_ely=sum(field(index).*beta,2);
+
+%Compute gradient for each node (average of the elements around)
+gradx=sparse(line,ones(linesize,1),repmat(areas.*grad_elx,3,1),numberofnodes,1);
+grady=sparse(line,ones(linesize,1),repmat(areas.*grad_ely,3,1),numberofnodes,1);
+gradx=gradx./weights;
+grady=grady./weights;
+
+%Compute hessian for each element
+hessian=[sum(gradx(index).*alpha,2) sum(grady(index).*alpha,2) sum(grady(index).*beta,2)];
+
+if strcmpi(type,'node')
+	%Compute Hessian on the nodes (average of the elements around)
+	hessian=[sparse(line,ones(linesize,1),repmat(areas.*hessian(:,1),3,1),numberofnodes,1)./weights ...
+		sparse(line,ones(linesize,1),repmat(areas.*hessian(:,2),3,1),numberofnodes,1)./weights ...
+		sparse(line,ones(linesize,1),repmat(areas.*hessian(:,3),3,1),numberofnodes,1)./weights ];
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/ComputeMetric.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/ComputeMetric.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/ComputeMetric.m	(revision 11330)
@@ -0,0 +1,66 @@
+function metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos)
+%COMPUTEMETRIC - compute metric from an Hessian
+%
+%   Usage:
+%      metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos)
+%      pos is contains the positions where the metric is wished to be maximized (water?)
+%
+%   Example:
+%      metric=ComputeMetric(hessian,2/9,10^-1,100,10^5,find(md.nodeonwater)
+
+%first, find the eigen values of eah line of H=[hessian(i,1) hessian(i,2); hessian(i,2)  hessian(i,3)]
+a=hessian(:,1); b=hessian(:,2); d=hessian(:,3);
+lambda1=0.5*((a+d)+sqrt(4*b.^2+(a-d).^2));
+lambda2=0.5*((a+d)-sqrt(4*b.^2+(a-d).^2));
+pos1=find(lambda1==0);
+pos2=find(lambda2==0);
+pos3=find(b==0 & lambda1==lambda2);
+
+%Modify the eigen values to control the shape of the elements
+lambda1=min(max(abs(lambda1)*scale/epsilon,1/hmax^2),1/hmin^2);
+lambda2=min(max(abs(lambda2)*scale/epsilon,1/hmax^2),1/hmin^2);
+
+%compute eigen vectors
+norm1=sqrt(8*b.^2+2*(d-a).^2+2*(d-a).*sqrt((a-d).^2+4*b.^2));
+v1x=2*b./norm1;
+v1y=((d-a)+sqrt((a-d).^2+4*b.^2))./norm1;
+norm2=sqrt(8*b.^2+2*(d-a).^2-2*(d-a).*sqrt((a-d).^2+4*b.^2));
+v2x=2*b./norm2;
+v2y=((d-a)-sqrt((a-d).^2+4*b.^2))./norm2;
+
+v1x(pos3)=1; v1y(pos3)=0;
+v2x(pos3)=0; v2y(pos3)=1;
+
+%Compute new metric (for each node M=V*Lambda*V^-1)
+metric=full([(v1x.*v2y-v1y.*v2x).^(-1).*(lambda1.*v2y.*v1x-lambda2.*v1y.*v2x) ...
+	(v1x.*v2y-v1y.*v2x).^(-1).*(lambda1.*v1y.*v2y-lambda2.*v1y.*v2y) ...
+	(v1x.*v2y-v1y.*v2x).^(-1).*(-lambda1.*v2x.*v1y+lambda2.*v1x.*v2y)]);
+
+%some corrections for 0 eigen values
+metric(pos1,:)=repmat([1/hmax^2 0 1/hmax^2],length(pos1),1);
+metric(pos2,:)=repmat([1/hmax^2 0 1/hmax^2],length(pos2),1);
+
+%take care of water elements
+metric(pos,:)=repmat([1/hmax^2 0 1/hmax^2],length(pos),1);
+
+%take care of NaNs if any (use Matlab eig in a loop)
+[pos posj]=find(isnan(metric)); clear posj;
+if ~isempty(pos),
+	fprintf(' %i %s',length(pos),'NaN found in the metric. Use Matlab routine...');
+	for i=1:length(pos)
+		H=[hessian(pos(i),1) hessian(pos(i),2)
+		hessian(pos(i),2) hessian(pos(i),3)];
+		[u,v]=eig(full(H));
+		lambda1=v(1,1);
+		lambda2=v(2,2);
+		v(1,1)=min(max(abs(lambda1)*scale/epsilon,1/hmax^2),1/hmin^2);
+		v(2,2)=min(max(abs(lambda2)*scale/epsilon,1/hmax^2),1/hmin^2);
+
+		metricTria=u*v*u^(-1);
+		metric(pos(i),:)=[metricTria(1,1) metricTria(1,2) metricTria(2,2)];
+	end
+end
+
+if any(isnan(metric)),
+	error('ComputeMetric error message: NaN in the metric despite our efforts...')
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/ElementsFromEdge.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/ElementsFromEdge.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/ElementsFromEdge.m	(revision 11330)
@@ -0,0 +1,15 @@
+function edgeelements=ElementsFromEdge(elements,A,B) 
+%ELEMENTSFROMEDGE: find elements connected to one edge defined by nodes A and B
+%
+% Usage: edgeelements=ElementsFromEdge(elements,A,B) 
+%
+% Eg:    edgeelements=ElementsFromEdge(md.mesh.elements,tip1,tip2)
+%
+%
+edgeelements=find(...
+(elements(:,1)==A & elements(:,2)==B )| ...
+(elements(:,1)==A & elements(:,3)==B )| ...
+(elements(:,2)==A & elements(:,3)==B )| ...
+(elements(:,2)==A & elements(:,1)==B )| ...
+(elements(:,3)==A & elements(:,1)==B )| ...
+(elements(:,3)==A & elements(:,2)==B ));
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/FixMesh.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/FixMesh.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/FixMesh.m	(revision 11330)
@@ -0,0 +1,45 @@
+function  [index2 x2 y2 value2]=FixMesh(index,x,y,value)
+%FixMesh fix mesh with broken triangles, orphan vertices, etc ...
+%
+% Usage: 
+%            [index2 x2 y2 value2]=FixMesh(index,x,y,value)
+%            where index,x,y is a delaunay triangulation, 
+%                  value is a field on the input triangulation, with values at the vertices
+%                  index2,x2,y2,value2 is the repaired triangulation, with new values on new vertices
+%
+%
+
+%duplicate inputs
+index2=index;
+x2=x;
+y2=y;
+value2=value;
+
+%First, look for orphan vertices, and take them out.
+flags=zeros(length(x2),1); flags(index2)=1;
+orphans=find(flags==0);
+
+while ~isempty(orphans),
+
+	%take the first orphan, the lower numbered, and take it out
+	orphan=orphans(1);
+
+	%first x,y,value
+	x2(orphan)=[];
+	y2(orphan)=[];
+	value2(orphan)=[];
+
+	%now, the index:
+	pos=find(index2>orphan); index2(pos)=index2(pos)-1;
+	
+	%look again for orphans on new mesh
+	flags=zeros(length(x2),1);flags(index2)=1;
+	orphans=find(flags==0);
+end
+
+%Check all triangles are well oriented.
+aires=GetAreas(index2,x2,y2);
+pos=find(aires<0);
+temp=index2(pos,1);
+index2(pos,1)=index2(pos,2);
+index2(pos,2)=temp;
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/GetAreas.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/GetAreas.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/GetAreas.m	(revision 11330)
@@ -0,0 +1,51 @@
+function areas=GetAreas(index,x,y,varargin)
+%GETAREAS - compute areas or volumes of elements
+%
+%   compute areas of triangular elements or volumes 
+%   of pentahedrons
+%
+%   Usage:
+%      areas  =GetAreas(index,x,y);
+%      volumes=GetAreas(index,x,y,z);
+%
+%   Examples:
+%      areas  =GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+%      volumes=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y,md.z);
+
+%get number of elements and number of nodes
+nels=size(index,1);
+nods=length(x);
+if nargin==4, z=varargin{1}; end
+
+%some checks
+if nargout~=1 | (nargin~=3 & nargin~=4),
+	help GetAreas
+	error('GetAreas error message: bad usage')
+end
+if ((length(y)~=nods) | (nargin==4 & length(z)~=nods)),
+	error('GetAreas error message: x,y and z do not have the same length')
+end
+if max(index(:))>nods,
+	error(['GetAreas error message: index should not have values above ' num2str(nods) ])
+end
+if (nargin==3 & size(index,2)~=3),
+	error('GetAreas error message: index should have 3 columns for 2d meshes.')
+end
+if (nargin==4 & size(index,2)~=6),
+	error('GetAreas error message: index should have 6 columns for 3d meshes.')
+end
+
+%initialization
+areas=zeros(nels,1);
+x1=x(index(:,1)); x2=x(index(:,2)); x3=x(index(:,3));
+y1=y(index(:,1)); y2=y(index(:,2)); y3=y(index(:,3));
+
+%compute the volume of each element
+if nargin==3,
+	%compute the surface of the triangle
+	areas=(0.5*((x2-x1).*(y3-y1)-(y2-y1).*(x3-x1)));
+else
+	%V=area(triangle)*1/3(z1+z2+z3)
+	thickness=mean(z(index(:,4:6)),2)-mean(z(index(:,1:3)),2);
+	areas=(0.5*((x2-x1).*(y3-y1)-(y2-y1).*(x3-x1))).*thickness;
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/GetCharacteristicLength.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/GetCharacteristicLength.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/GetCharacteristicLength.m	(revision 11330)
@@ -0,0 +1,45 @@
+function length=GetCharacteristicLength(index,x,y,varargin)
+%GETCHARACTERISTICLENGTH - compute characteristic length for a mesh
+%
+%   compute characteristic lengths of every element of a mesh.
+%
+%   Usage:
+%      length  =GetCharacteristicLength(index,x,y);
+%      length  =GetCharacteristicLength(index,x,y,z);
+%
+%   Examples:
+%      length  =GetCharacteristicLength(md.mesh.elements,md.mesh.x,md.mesh.y);
+%      length  =GetCharacteristicLength(md.mesh.elements,md.mesh.x,md.mesh.y,md.z);
+
+
+%get number of elements and number of nodes
+nels=size(index,1);
+nods=numel(x);
+
+%some checks
+if nargout~=1 | (nargin~=3 & nargin~=4),
+	help GetCharacteristicLength
+	error('GetCharacteristicLength error message: bad usage')
+end
+if ((numel(y)~=nods) | (nargin==4 & numel(z)~=nods)),
+	error('GetCharacteristicLength error message: x,y and z do not have the same length')
+end
+if max(index(:))>nods,
+	error(['GetCharacteristicLength error message: index should not have values above ' num2str(nods) ])
+end
+if (nargin==3 & size(index,2)~=3),
+	error('GetCharacteristicLength error message: index should have 3 columns for 2d meshes.')
+end
+if (nargin==4 & size(index,2)~=6),
+	error('GetCharacteristicLength error message: index should have 6 columns for 3d meshes.')
+end
+
+%get areas or volumes.
+areas=GetAreas(index,x,y,varargin{:});
+
+%for a 2d mesh: 
+if nargin==3,
+	length=sqrt(2*areas);
+else
+	error('not supported yet');
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/GetNodalFunctionsCoeff.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/GetNodalFunctionsCoeff.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/GetNodalFunctionsCoeff.m	(revision 11330)
@@ -0,0 +1,56 @@
+function [alpha beta varargout]=GetNodalFunctionsCoeff(index,x,y)
+%GETNODELFUNCTIONSCOEFF - compute nodal functions coefficients
+%
+%   Compute the coefficients alpha beta and optionaly gamma of
+%   2d triangular elements. For each element, the nodal function
+%   is defined as:
+%   N(x,y)=sum(i=1:3) alpha_i * x + beta_i * y + gamma_i
+%
+%   Usage:
+%      [alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+%      [alpha beta gamma]=GetNodalFunctionsCoeff(index,x,y);
+%
+%   Example:
+%      [alpha beta gamma]=GetNodalFunctionsCoeff(md.mesh.elements,md.mesh.x,md.mesh.y);
+
+%make columns out of x and y
+x=x(:); y=y(:);
+
+%get nels and nods
+nels=size(index,1);
+nods=length(x);
+
+%some checks
+if nargin~=3 | (nargout~=2 & nargout~=3),
+	help GetNodalFunctionsCoeff
+	error('GetNodalFunctionsCoeff error message: bad usage')
+end
+if length(y)~=nods,
+	error('GetNodalFunctionsCoeff error message: x and y do not have the same length')
+end
+if max(index(:))>nods,
+	error(['GetNodalFunctionsCoeff error message: index should not have values above ' num2str(nods) ])
+end
+if size(index,2)~=3,
+	error('GetNodalFunctionsCoeff error message: only 2d meshes supported. index should have 3 columns.')
+end
+
+%initialize output
+alpha=zeros(nels,3);
+beta=zeros(nels,3);
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
+x1=x(index(:,1)); x2=x(index(:,2)); x3=x(index(:,3));
+y1=y(index(:,1)); y2=y(index(:,2)); y3=y(index(:,3));
+invdet=1./(x1.*(y2-y3)-x2.*(y1-y3)+x3.*(y1-y2));
+
+%get alpha and beta
+alpha=[invdet.*(y2-y3) invdet.*(y3-y1) invdet.*(y1-y2)];
+beta =[invdet.*(x3-x2) invdet.*(x1-x3) invdet.*(x2-x1)];
+
+%get gamma if requested
+if nargout==3,
+	gamma=zeros(nels,3);
+	gamma=[invdet.*(x2.*y3-x3.*y2) invdet.*(y1.*x3-y3.*x1) invdet.*(x1.*y2-x2.*y1)];
+	varargout{1}=gamma;
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/MergeMetrics.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/MergeMetrics.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/MergeMetrics.m	(revision 11330)
@@ -0,0 +1,15 @@
+function metric=MergeMetrics(metric1,metric2)
+
+M1xx=metric1(:,1); M1xy=metric1(:,2); M1yy=metric1(:,3);
+M1lambda1=0.5*((M1xx+M1yy)+sqrt(4*M1xy.^2+(M1xx-M1yy).^2));
+M1lambda2=0.5*((M1xx+M1yy)-sqrt(4*M1xy.^2+(M1xx-M1yy).^2));
+lambda1=min(M1lambda1,M1lambda2);
+
+M2xx=metric1(:,1); M2xy=metric1(:,2); M2yy=metric1(:,3);
+M2lambda1=0.5*((M2xx+M2yy)+sqrt(4*M2xy.^2+(M2xx-M2yy).^2));
+M2lambda2=0.5*((M2xx+M2yy)-sqrt(4*M2xy.^2+(M2xx-M2yy).^2));
+lambda2=min(M2lambda2,M2lambda2);
+
+metric=metric1;
+pos=find(lambda2<lambda1);
+metric(pos,:)=metric2(pos,:);
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/MeshQuality.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/MeshQuality.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/MeshQuality.m	(revision 11330)
@@ -0,0 +1,82 @@
+function quality=MeshQuality(md,epsilon,hmin,hmax);
+%MESHQUALITY - compute mesh quality
+%
+%   Usage:
+%      MeshQuality(md,epsilon,hmin,hmax);
+
+%Get some variables from the model
+index=md.mesh.elements;
+x=md.mesh.x;
+y=md.mesh.y;
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%Compute Hessian
+hessian=ComputeHessian(index,x,y,md.inversion.vel_obs,'node');
+
+%Compute metric
+if length(md.nodeonwater)==md.mesh.numberofvertices,
+	pos=find(md.nodeonwater);
+else
+	pos=[];
+end
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos);
+
+%Get Areas
+areas=GetAreas(index,x,y);
+
+%length edges vectors
+e1x=[x(index(:,2))-x(index(:,1))];
+e1y=[y(index(:,2))-y(index(:,1))];
+e2x=[x(index(:,3))-x(index(:,2))];
+e2y=[y(index(:,3))-y(index(:,2))];
+e3x=[x(index(:,1))-x(index(:,3))];
+e3y=[y(index(:,1))-y(index(:,3))];
+
+%metric of each the 3 nodes for each element
+M1=metric(index(:,1),:);
+M2=metric(index(:,2),:);
+M3=metric(index(:,3),:);
+
+%Get edge length in the metric
+L1=1/2*(sqrt(e2x.*(M2(:,1).*e2x+M2(:,2).*e2y)+e2y.*(M2(:,2).*e2x+M2(:,3).*e2y))+sqrt(e1x.*(M1(:,1).*e1x+M1(:,2).*e1y)+e1y.*(M1(:,2).*e1x+M1(:,3).*e1y)));
+L2=1/2*(sqrt(e3x.*(M3(:,1).*e3x+M3(:,2).*e3y)+e3y.*(M3(:,2).*e3x+M3(:,3).*e3y))+sqrt(e2x.*(M2(:,1).*e2x+M2(:,2).*e2y)+e2y.*(M2(:,2).*e2x+M2(:,3).*e2y)));
+L3=1/2*(sqrt(e1x.*(M1(:,1).*e1x+M1(:,2).*e1y)+e1y.*(M1(:,2).*e1x+M1(:,3).*e1y))+sqrt(e3x.*(M3(:,1).*e3x+M3(:,2).*e3y)+e3y.*(M3(:,2).*e3x+M3(:,3).*e3y)));
+
+%area in the metric
+V=1/3*areas.*(sqrt(M1(:,1).*M1(:,3)-M1(:,2).^2)+sqrt(M2(:,1).*M2(:,3)-M2(:,2).^2)+sqrt(M3(:,1).*M3(:,3)-M3(:,2).^2));
+
+%compute quality:
+quality=4*sqrt(3)*V./(L1+L2+L3);
+
+%compute error
+a=hessian(:,1); b=hessian(:,2); d=hessian(:,3);
+a=a(index)*[1;1;1]/3;
+b=b(index)*[1;1;1]/3;
+d=d(index)*[1;1;1]/3;
+lambda1=0.5*((a+d)+sqrt(4*b.^2+(a-d).^2));
+lambda2=0.5*((a+d)-sqrt(4*b.^2+(a-d).^2));
+lambda1=min(max(abs(lambda1)*scale/epsilon,1/hmax^2),1/hmin^2);
+lambda2=min(max(abs(lambda2)*scale/epsilon,1/hmax^2),1/hmin^2);
+if length(md.nodeonwater)==md.mesh.numberofvertices;
+	pos=find(md.nodeonwater);
+	lambda1(pos)=0;
+	lambda2(pos)=0;
+end
+lambda1=lambda1(index)*[1;1;1]/3;
+lambda2=lambda2(index)*[1;1;1]/3;
+
+lambdamax=max(lambda1,lambda2);
+hmax=max(max(sqrt(e1x.^2+e1y.^2),sqrt(e2x.^2+e2y.^2)),sqrt(e3x.^2+e3y.^2));
+epsilon=scale*hmax.^2.*lambdamax;
+
+%display
+%X=0:0.1:4; hist(quality,X); xlim([0 3]); title('mesh quality distribution','FontSize',14);
+%plotmodel(md,'data',epsilon,'title','Interpolation error','figure',2)
+disp(sprintf('\n%s','Mesh Quality'));
+disp(sprintf('   %s %g','Average Mesh quality: ',mean(quality)));
+disp(sprintf('   %s %g','Worst Element quality:',max(quality)));
+disp(sprintf('\n%s','Interpolation Error'));
+disp(sprintf('   %s %g %s','Average interpolation error:',mean(epsilon),'m/yr'));
+disp(sprintf('   %s %g %s','Maximum interpolation error:',max(epsilon),'m/yr'));
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/NodeInElement.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/NodeInElement.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/NodeInElement.m	(revision 11330)
@@ -0,0 +1,41 @@
+function node_in_element=NodeInElement(newx,newy,elements,x,y,nodeconnectivity);
+%NODEINELEMENT: find for a list of nodes (in newx,newy), which elements in the mesh (elements,x,y) they belong to.
+%
+%  Usage: node_in_element=NodeInElement(newx,newy,elements,x,y,md.mesh.vertexconnectivity);
+%
+%  See also Nodeconnectivity
+%
+epsilon=10^-10;
+
+%compute some quantities that will speed up the process
+x3x1=x(elements(:,1))-x(elements(:,3));
+y3y1=y(elements(:,1))-y(elements(:,3));
+x3x2=x(elements(:,2))-x(elements(:,3));
+y3y2=y(elements(:,2))-y(elements(:,3));
+x3=x(elements(:,3));
+y3=y(elements(:,3));
+delta=x(elements(:,2)).*y(elements(:,3))-y(elements(:,2)).*x(elements(:,3))-x(elements(:,1)).*y(elements(:,3))+y(elements(:,1)).*x(elements(:,3))+x(elements(:,1)).*y(elements(:,2))-y(elements(:,1)).*x(elements(:,2));
+
+%max connectivity:
+max_connectivity=max(nodeconnectivity(:,end));
+node_in_element=zeros(length(newx),max_connectivity+1); %last column is the number of elements to which the row node is connected.
+
+for i=1:length(newx),
+	x0=newx(i);
+	y0=newy(i);
+	
+	%first area coordinate
+	area_1=(y3y2.*(x0-x3)-x3x2.*(y0-y3))./delta;
+	%second area coordinate
+	area_2=(x3x1.*(y0-y3)-y3y1.*(x0-x3))./delta;
+	%third area coordinate
+	area_3=1-area_1-area_2;
+	
+	%get elements for which all area coordinates are positive (meaning (x0,y0) belongs to these elements
+	pos=find((area_1>=0-epsilon) & (area_2>=0-epsilon) & (area_3>=0-epsilon));
+
+	num_elements=length(pos);
+
+	node_in_element(i,1:num_elements)=pos;
+	node_in_element(i,end)=num_elements;
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/ProfileProjectOntoMesh.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/ProfileProjectOntoMesh.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/ProfileProjectOntoMesh.m	(revision 11330)
@@ -0,0 +1,66 @@
+function mesh_profile=ProfileProjectOntoMesh(md,profile)
+%PROFILEPROJECTONTOMESH: project a profile (made of arbitrary points) onto a mesh, so that we end 
+%                        up with a list of segments self contained onto elements.
+%
+% Usage: mesh_profile=ProfileProjectOntoMesh(md,profile)
+%
+% See also intersections.m
+
+%make a curve out of the mesh, to use the intersections routine.
+rows=[md.mesh.elements md.mesh.elements(:,1)]'; rows=rows(:);
+x=md.mesh.x(rows);
+y=md.mesh.y(rows);
+
+%[x0,y0] = intersections(profile.x,profile.y,x,y,1);
+[x0,y0,indices,j] = intersections(profile.x,profile.y,x,y);
+
+%  sort intersections to create segments in order and continuous along profile
+[indices,isort]=sort(indices);
+j =j (isort);
+x0=x0(isort);
+y0=y0(isort);
+
+%process x0,y0 so they do not include profile.x or profile.y
+processed_indices=[];
+processed_x=[];
+processed_y=[];
+for i=1:numel(indices),
+	if(((indices(i)-floor(indices(i)))~=0) && ((ceil(indices(i))-indices(i))~=0))
+		processed_indices=[processed_indices;floor(indices(i))];
+		processed_x=[processed_x;x0(i)];
+		processed_y=[processed_y;y0(i)];
+	end
+end
+
+%now merge profile.x,profile.y with processed_x,processed_y, at locations processed_indices:
+newx=profile.x;
+newy=profile.y;
+
+count=1;
+for i=1:numel(profile.x),
+	pos=find(processed_indices==i);
+	if ~isempty(pos),
+		newx=[newx(1:count); processed_x(pos); newx(count+1:end)];
+		newy=[newy(1:count); processed_y(pos); newy(count+1:end)];
+		count=count+length(pos)+1;
+	end
+end
+
+%now, for each node, figure out which element it belongs to.
+node_in_element=NodeInElement(newx,newy,md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.vertexconnectivity);
+
+% eliminate nodes that don't fall in any element
+% (profile may start and/or end externally and/or cross holes in the model)
+
+ind=find(node_in_element(:,9)>0);
+newx=newx(ind,:);
+newy=newy(ind,:);
+node_in_element=node_in_element(ind,:);
+
+mesh_profile=[newx(1:end-1) newy(1:end-1) newx(2:end) newy(2:end) zeros(length(newy(2:end)),1)];
+
+%find which element each segment belongs to.
+for i=1:length(newx)-1,
+	common=intersect(node_in_element(i,1:node_in_element(i,end)), node_in_element(i+1,1:node_in_element(i+1,end)));
+	mesh_profile(i,end)=common(1);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/YamsCall.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/YamsCall.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/YamsCall.m	(revision 11330)
@@ -0,0 +1,104 @@
+function md=YamsCall(md,field,hmin,hmax,gradation,epsilon),
+%YAMSCALL - call yams
+%
+%   build a metric using the Hessian of the given field
+%   call Yams and the output mesh is plugged onto the model
+%   -hmin = minimum edge length (m)
+%   -hmax = maximum edge length (m)
+%   -gradation = maximum edge length gradation between 2 elements
+%   -epsilon = average error on each element (m/yr)
+%
+%   Usage:
+%      md=YamsCall(md,field,hmin,hmax,gradation,epsilon);
+%
+%   Example:
+%      md=YamsCall(md,md.inversion.vel_obs,1500,10^8,1.3,0.9);
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%Compute Hessian
+t1=clock; fprintf('%s','      computing Hessian...');
+hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,field,'node');
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%Compute metric
+t1=clock; fprintf('%s','      computing metric...');
+if length(md.mask.vertexonwater)==md.mesh.numberofvertices,
+	pos=find(md.mask.vertexonwater);
+else
+	pos=[];
+end
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+save -ascii carre0.met  metric
+
+fid=fopen('carre0.mesh','w');
+
+%initialiation
+fprintf(fid,'\n%s\n%i\n','MeshVersionFormatted',1);
+
+%dimension
+fprintf(fid,'\n%s\n%i\n','Dimension',2);
+
+%Vertices
+fprintf(fid,'\n%s\n%i\n\n','Vertices',md.mesh.numberofvertices);
+fprintf(fid,'%8g %8g %i\n',[md.mesh.x md.mesh.y zeros(md.mesh.numberofvertices,1)]');
+
+%Triangles
+fprintf(fid,'\n\n%s\n%i\n\n','Triangles',md.mesh.numberofelements);
+fprintf(fid,'%i %i %i %i\n',[md.mesh.elements zeros(md.mesh.numberofelements,1)]');
+numberofelements1=md.mesh.numberofelements;
+	
+%Deal with rifts
+if ~isnan(md.rifts.riftstruct),
+	
+	%we have the list of triangles that make up the rift. keep those triangles around during refinement.
+	triangles=[];
+	for i=1:size(md.rifts.riftstruct,1),
+		triangles=[triangles md.rifts(i).segments(:,3)'];
+	end
+
+	fprintf(fid,'\n\n%s\n%i\n\n','RequiredTriangles',length(triangles));
+	fprintf(fid,'%i\n',triangles);
+end
+
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call yams
+fprintf('%s\n','      call Yams...');
+if ispc
+	%windows
+	system(['yams2-win -O 1 -v -0 -ecp -hgrad ' num2str(gradation)  ' carre0 carre1']);
+elseif ismac
+	%Macosx
+	system(['yams2-osx -O 1 -v -0 -ecp -hgrad ' num2str(gradation)  ' carre0 carre1']);
+else
+	%Linux
+	system(['yams2-linux -O 1 -v -0 -ecp -hgrad ' num2str(gradation)  ' carre0 carre1']);
+end
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+Tria=load('carre1.tria');
+Coor=load('carre1.coor');
+md.mesh.x=Coor(:,1);
+md.mesh.y=Coor(:,2);
+md.mesh.z=zeros(size(Coor,1),1);
+md.mesh.elements=Tria;
+md.mesh.numberofvertices=size(Coor,1);
+md.mesh.numberofelements=size(Tria,1);
+numberofelements2=md.mesh.numberofelements;
+t2=clock;fprintf('%s\n\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%display number of elements
+fprintf('\n%s %i','      inital number of elements:',numberofelements1);
+fprintf('\n%s %i\n\n','      new    number of elements:',numberofelements2);
+
+%clean up:
+system('rm carre0.mesh carre0.met carre1.tria carre1.coor carre1.meshb');
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/argusmesh.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/argusmesh.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/argusmesh.m	(revision 11330)
@@ -0,0 +1,96 @@
+function md=argusmesh(md,infile)
+%ARGUSMESH - load an Argus mesh onto a model
+%
+%   Convert an Argus mesh contained in a file into
+%   fields needed for the mesh in a model md.
+%
+%   Usage:
+%      md=argusmesh(md,infile)
+%
+%   Example:
+%     md=argusmesh(md,'TriMesh.exp')
+
+%some argument check: 
+if nargin~=2 | nargout~=1,
+	help argustomodel;
+	error('argustomodel error message: bad usage');
+end
+
+%determine root of infile: strip extension
+[a,root,b,c]=fileparts(infile);
+
+%inform user we start the script: 
+disp(['   Translating argus file ''' infile ''' into matlab model object']);
+
+%open infile: 
+fileid=fopen(infile,'r');
+if fileid==-1,
+	error(['Could not open file ' infile  ' for reading']);
+end
+
+%Read first line of the argus mesh: node and element parameters
+[buffer,bytecount]=fscanf(fileid,'%i %i %i %i',[1 4]);
+if bytecount~=4, 
+	error(['Problem reading ' infile ' file at line #1']);
+end
+nel=buffer(1);
+nods=buffer(2);
+num_element_parameters=buffer(3);
+num_node_parameters=buffer(4);
+disp(['      argus model '''   root ''' contains ' num2str(nel) ' elements and ' num2str(nods) ' nodes.']);
+
+%initialize elements and nodes
+elements=zeros(nel,3);
+element_parameters=zeros(nel,num_element_parameters);
+x=zeros(nods,1);
+y=zeros(nods,1);
+z=zeros(nods,1);
+node_parameters=zeros(nods,num_node_parameters);
+
+%read nodes:
+format_string='%s %i %f %f ';
+for n=1:num_node_parameters,
+	format_string=[format_string ' %i '];
+end
+
+for n=1:nods,
+	[buffer,bytecount]=fscanf(fileid,format_string,[1,num_node_parameters+4]);
+	x(n)=buffer(3);
+	y(n)=buffer(4);
+	node_parameters(n,:)=buffer(5:length(buffer));
+end
+
+%read elements: 
+format_string='%s %i %i %i %i';
+for n=1:num_element_parameters,
+	format_string=[format_string ' %i '];
+end
+for n=1:nel,
+	[buffer,bytecount]=fscanf(fileid,format_string,[1,num_element_parameters+5]);
+	elements(n,:)=buffer(3:5);
+	element_parameters(n,:)=buffer(6:length(buffer));
+end
+
+%Create a name and a note for this model: 
+notes=['Model created by Argus from input file: ' infile ' and parameter file: ' root '.par on: ' date];
+name=root;
+
+%Finally, use model constructor to build a complete model: 
+md.mesh.elements=elements;
+md.mesh.x=x;
+md.mesh.y=y;
+md.z=z;
+md.mesh.numberofvertices=size(md.mesh.x,1);
+md.mesh.numberofelements=size(md.mesh.elements,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+md.mesh.dimension=2;
+md=addnote(md,notes);
+
+%Add segments and nodes on boundary
+md.mesh.segments=findsegments(md);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary(md.mesh.segments(:,1))=1;
+md.mesh.vertexonboundary(md.mesh.segments(:,2))=1;
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/intersections.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/intersections.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/intersections.m	(revision 11330)
@@ -0,0 +1,279 @@
+function [x0,y0,iout,jout] = intersections(x1,y1,x2,y2,robust)
+%INTERSECTIONS Intersections of curves.
+%   Computes the (x,y) locations where two curves intersect.  The curves
+%   can be broken with NaNs or have vertical segments.
+%
+% Example:
+%   [X0,Y0] = intersections(X1,Y1,X2,Y2,ROBUST);
+%
+% where X1 and Y1 are equal-length vectors of at least two points and
+% represent curve 1.  Similarly, X2 and Y2 represent curve 2.
+% X0 and Y0 are column vectors containing the points at which the two
+% curves intersect.
+%
+% ROBUST (optional) set to 1 or true means to use a slight variation of the
+% algorithm that might return duplicates of some intersection points, and
+% then remove those duplicates.  The default is true, but since the
+% algorithm is slightly slower you can set it to false if you know that
+% your curves don't intersect at any segment boundaries.  Also, the robust
+% version properly handles parallel and overlapping segments.
+%
+% The algorithm can return two additional vectors that indicate which
+% segment pairs contain intersections and where they are:
+%
+%   [X0,Y0,I,J] = intersections(X1,Y1,X2,Y2,ROBUST);
+%
+% For each element of the vector I, I(k) = (segment number of (X1,Y1)) +
+% (how far along this segment the intersection is).  For example, if I(k) =
+% 45.25 then the intersection lies a quarter of the way between the line
+% segment connecting (X1(45),Y1(45)) and (X1(46),Y1(46)).  Similarly for
+% the vector J and the segments in (X2,Y2).
+%
+% You can also get intersections of a curve with itself.  Simply pass in
+% only one curve, i.e.,
+%
+%   [X0,Y0] = intersections(X1,Y1,ROBUST);
+%
+% where, as before, ROBUST is optional.
+
+% Version: 1.10, 25 February 2008
+% Author:  Douglas M. Schwarz
+% Email:   dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu
+% Real_email = regexprep(Email,{'=','*'},{'@','.'})
+
+
+% Theory of operation:
+%
+% Given two line segments, L1 and L2,
+%
+%   L1 endpoints:  (x1(1),y1(1)) and (x1(2),y1(2))
+%   L2 endpoints:  (x2(1),y2(1)) and (x2(2),y2(2))
+%
+% we can write four equations with four unknowns and then solve them.  The
+% four unknowns are t1, t2, x0 and y0, where (x0,y0) is the intersection of
+% L1 and L2, t1 is the distance from the starting point of L1 to the
+% intersection relative to the length of L1 and t2 is the distance from the
+% starting point of L2 to the intersection relative to the length of L2.
+%
+% So, the four equations are
+%
+%    (x1(2) - x1(1))*t1 = x0 - x1(1)
+%    (x2(2) - x2(1))*t2 = x0 - x2(1)
+%    (y1(2) - y1(1))*t1 = y0 - y1(1)
+%    (y2(2) - y2(1))*t2 = y0 - y2(1)
+%
+% Rearranging and writing in matrix form,
+%
+%  [x1(2)-x1(1)       0       -1   0;      [t1;      [-x1(1);
+%        0       x2(2)-x2(1)  -1   0;   *   t2;   =   -x2(1);
+%   y1(2)-y1(1)       0        0  -1;       x0;       -y1(1);
+%        0       y2(2)-y2(1)   0  -1]       y0]       -y2(1)]
+%
+% Let's call that A*T = B.  We can solve for T with T = A\B.
+%
+% Once we have our solution we just have to look at t1 and t2 to determine
+% whether L1 and L2 intersect.  If 0 <= t1 < 1 and 0 <= t2 < 1 then the two
+% line segments cross and we can include (x0,y0) in the output.
+%
+% In principle, we have to perform this computation on every pair of line
+% segments in the input data.  This can be quite a large number of pairs so
+% we will reduce it by doing a simple preliminary check to eliminate line
+% segment pairs that could not possibly cross.  The check is to look at the
+% smallest enclosing rectangles (with sides parallel to the axes) for each
+% line segment pair and see if they overlap.  If they do then we have to
+% compute t1 and t2 (via the A\B computation) to see if the line segments
+% cross, but if they don't then the line segments cannot cross.  In a
+% typical application, this technique will eliminate most of the potential
+% line segment pairs.
+
+
+% Input checks.
+error(nargchk(2,5,nargin))
+
+% Adjustments when fewer than five arguments are supplied.
+switch nargin
+	case 2
+		robust = true;
+		x2 = x1;
+		y2 = y1;
+		self_intersect = true;
+	case 3
+		robust = x2;
+		x2 = x1;
+		y2 = y1;
+		self_intersect = true;
+	case 4
+		robust = true;
+		self_intersect = false;
+	case 5
+		self_intersect = false;
+end
+
+% x1 and y1 must be vectors with same number of points (at least 2).
+if sum(size(x1) > 1) ~= 1 || sum(size(y1) > 1) ~= 1 || ...
+		length(x1) ~= length(y1)
+	error('X1 and Y1 must be equal-length vectors of at least 2 points.')
+end
+% x2 and y2 must be vectors with same number of points (at least 2).
+if sum(size(x2) > 1) ~= 1 || sum(size(y2) > 1) ~= 1 || ...
+		length(x2) ~= length(y2)
+	error('X2 and Y2 must be equal-length vectors of at least 2 points.')
+end
+
+
+% Force all inputs to be column vectors.
+x1 = x1(:);
+y1 = y1(:);
+x2 = x2(:);
+y2 = y2(:);
+
+% Compute number of line segments in each curve and some differences we'll
+% need later.
+n1 = length(x1) - 1;
+n2 = length(x2) - 1;
+xy1 = [x1 y1];
+xy2 = [x2 y2];
+dxy1 = diff(xy1);
+dxy2 = diff(xy2);
+
+% Determine the combinations of i and j where the rectangle enclosing the
+% i'th line segment of curve 1 overlaps with the rectangle enclosing the
+% j'th line segment of curve 2.
+[i,j] = find(repmat(min(x1(1:end-1),x1(2:end)),1,n2) <= ...
+	repmat(max(x2(1:end-1),x2(2:end)).',n1,1) & ...
+	repmat(max(x1(1:end-1),x1(2:end)),1,n2) >= ...
+	repmat(min(x2(1:end-1),x2(2:end)).',n1,1) & ...
+	repmat(min(y1(1:end-1),y1(2:end)),1,n2) <= ...
+	repmat(max(y2(1:end-1),y2(2:end)).',n1,1) & ...
+	repmat(max(y1(1:end-1),y1(2:end)),1,n2) >= ...
+	repmat(min(y2(1:end-1),y2(2:end)).',n1,1));
+
+% For one segment in x1,y1, i and j are returned as row vectors.  They
+% need to be column vectors, or iout and jout below will err out.
+% (jes, 6/11/10)
+
+if (size(i,1) == 1)
+    i=i';
+end
+if (size(j,1) == 1)
+    j=j';
+end
+
+% Find segments pairs which have at least one vertex = NaN and remove them.
+% This line is a fast way of finding such segment pairs.  We take
+% advantage of the fact that NaNs propagate through calculations, in
+% particular subtraction (in the calculation of dxy1 and dxy2, which we
+% need anyway) and addition.
+% At the same time we can remove redundant combinations of i and j in the
+% case of finding intersections of a line with itself.
+if self_intersect
+	remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2)) | j <= i + 1;
+else
+	remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2));
+end
+i(remove) = [];
+j(remove) = [];
+
+% Initialize matrices.  We'll put the T's and B's in matrices and use them
+% one column at a time.  AA is a 3-D extension of A where we'll use one
+% plane at a time.
+n = length(i);
+T = zeros(4,n);
+AA = zeros(4,4,n);
+AA([1 2],3,:) = -1;
+AA([3 4],4,:) = -1;
+AA([1 3],1,:) = dxy1(i,:).';
+AA([2 4],2,:) = dxy2(j,:).';
+B = -[x1(i) x2(j) y1(i) y2(j)].';
+
+% Loop through possibilities.  Trap singularity warning and then use
+% lastwarn to see if that plane of AA is near singular.  Process any such
+% segment pairs to determine if they are colinear (overlap) or merely
+% parallel.  That test consists of checking to see if one of the endpoints
+% of the curve 2 segment lies on the curve 1 segment.  This is done by
+% checking the cross product
+%
+%   (x1(2),y1(2)) - (x1(1),y1(1)) x (x2(2),y2(2)) - (x1(1),y1(1)).
+%
+% If this is close to zero then the segments overlap.
+
+% If the robust option is false then we assume no two segment pairs are
+% parallel and just go ahead and do the computation.  If A is ever singular
+% a warning will appear.  This is faster and obviously you should use it
+% only when you know you will never have overlapping or parallel segment
+% pairs.
+
+if robust
+	overlap = false(1,n);
+	warning_state = warning('off','MATLAB:singularMatrix');
+	% Use try-catch to guarantee original warning state is restored.
+	try
+		lastwarn('')
+		for k = 1:n
+			T(:,k) = AA(:,:,k)\B(:,k);
+			[unused,last_warn] = lastwarn;
+			lastwarn('')
+			if strcmp(last_warn,'MATLAB:singularMatrix')
+				% Force in_range(k) to be false.
+				T(1,k) = NaN;
+				% Determine if these segments overlap or are just parallel.
+				overlap(k) = rcond([dxy1(i(k),:);xy2(j(k),:) - xy1(i(k),:)]) < eps;
+			end
+		end
+		warning(warning_state)
+	catch
+		warning(warning_state)
+		rethrow(lasterror)
+	end
+	% Find where t1 and t2 are between 0 and 1 and return the corresponding
+	% x0 and y0 values.
+	in_range = T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) <= 1 & T(2,:) <= 1;
+	% For overlapping segment pairs the algorithm will return an
+	% intersection point that is at the center of the overlapping region.
+	if any(overlap)
+		ia = i(overlap);
+		ja = j(overlap);
+		% set x0 and y0 to middle of overlapping region.
+		T(3,overlap) = (max(min(x1(ia),x1(ia+1)),min(x2(ja),x2(ja+1))) + ...
+			min(max(x1(ia),x1(ia+1)),max(x2(ja),x2(ja+1)))).'/2;
+		T(4,overlap) = (max(min(y1(ia),y1(ia+1)),min(y2(ja),y2(ja+1))) + ...
+			min(max(y1(ia),y1(ia+1)),max(y2(ja),y2(ja+1)))).'/2;
+		selected = in_range | overlap;
+	else
+		selected = in_range;
+	end
+	xy0 = T(3:4,selected).';
+	
+	% Remove duplicate intersection points.
+	[xy0,index] = unique(xy0,'rows');
+	x0 = xy0(:,1);
+	y0 = xy0(:,2);
+	
+	% Compute how far along each line segment the intersections are.
+	if nargout > 2
+		sel_index = find(selected);
+		sel = sel_index(index);
+		iout = i(sel) + T(1,sel).';
+		jout = j(sel) + T(2,sel).';
+	end
+else % non-robust option
+	for k = 1:n
+		[L,U] = lu(AA(:,:,k));
+		T(:,k) = U\(L\B(:,k));
+	end
+	
+	% Find where t1 and t2 are between 0 and 1 and return the corresponding
+	% x0 and y0 values.
+	in_range = T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) < 1 & T(2,:) < 1;
+	x0 = T(3,in_range).';
+	y0 = T(4,in_range).';
+	
+	% Compute how far along each line segment the intersections are.
+	if nargout > 2
+		iout = i(in_range) + T(1,in_range).';
+		jout = j(in_range) + T(2,in_range).';
+	end
+end
+
+% Plot the results (useful for debugging).
+% plot(x1,y1,x2,y2,x0,y0,'ok');
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/isconnected.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/isconnected.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/isconnected.m	(revision 11330)
@@ -0,0 +1,13 @@
+function flag=isconnected(elements,A,B)
+%ISCONNECTED: are two nodes connected by a triangulation?
+%
+%   Usage: flag=isconnected(elements,A,B)
+%
+%
+
+elements=ElementsFromEdge(elements,A,B);
+if isempty(elements),
+	flag=0;
+else
+	flag=1;
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/meshread.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/meshread.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/meshread.m	(revision 11330)
@@ -0,0 +1,41 @@
+function Struct=meshread(filename);
+
+%some checks
+if ~exist(filename),
+	error(['meshread error message: file ' filename ' not found!']);
+end
+
+fid=fopen(filename,'r');
+
+while (~feof(fid)),
+
+	A=fscanf(fid,'%s',1);
+
+	if strcmp(A,'MeshVersionFormatted');
+		Struct.Version=fscanf(fid,'%s',1);
+
+	elseif strcmp(A,'Dimension'),
+		Struct.Dimension=fscanf(fid,'%i',1);
+
+	elseif strcmp(A,'Vertices'),
+		Struct.nods=fscanf(fid,'%i',1);
+		A=fscanf(fid,'%f %f %f',[3 Struct.nods]);
+		Struct.x=A(1,:)';
+		Struct.y=A(2,:)';
+
+	elseif strcmp(A,'Triangles'),
+		Struct.nels=fscanf(fid,'%i',1);
+		A=fscanf(fid,'%i %i %i',[4 Struct.nels]);
+		Struct.index=A(1:3,:)';
+
+	elseif strcmp(A,'Quadrilaterals'),
+		Struct.nels=fscanf(fid,'%i',1);
+		A=fscanf(fid,'%i %i %i %i',[5 Struct.nels]);
+		Struct.index=A(1:4,:)';
+	else
+		%do nothing
+
+	end
+end
+
+fclose(fid);
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/rifttipsonmesh.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/rifttipsonmesh.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/rifttipsonmesh.m	(revision 11330)
@@ -0,0 +1,26 @@
+function tips=rifttipsonmesh(md,riftoutline)
+%RIFTTIPSONMESH: identify, using a rift outline, the nodes that are tips of 
+%                rifts.
+
+%read rifts from outline file
+rifts=expread(riftoutline,1);
+
+tips=[];
+
+for i=1:length(rifts),
+	rift=rifts(i);
+
+	x_tip=rift.x(1);
+	y_tip=rift.y(1);
+	
+	index=find_point(md.mesh.x,md.mesh.y,x_tip,y_tip);
+	tips(end+1)=index;
+
+	x_tip=rift.x(end);
+	y_tip=rift.y(end);
+	
+	index=find_point(md.mesh.x,md.mesh.y,x_tip,y_tip);
+	tips(end+1)=index;
+
+end
+
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/roundmesh.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/roundmesh.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/roundmesh.m	(revision 11330)
@@ -0,0 +1,34 @@
+function md=roundmesh(md,radius,resolution)
+%ROUNDMESH - create an unstructured round mesh 
+%
+%   This script will generate a structured round mesh
+%   - radius     : specifies the radius of the circle in meters
+%   - resolution : specifies the resolution in meters
+%
+%   Usage:
+%      md=roundmesh(md,radius,resolution)
+
+%First we have to create the domain outline 
+
+%Get number of points on the circle
+pointsonedge=floor((2*pi*radius) / resolution);
+
+%Calculate the cartesians coordinates of the points
+x_list=ones(pointsonedge,1); y_list=ones(pointsonedge,1);
+theta=(0:2*pi/pointsonedge:2*pi*(1-1/pointsonedge))';
+x_list=radius*x_list.*cos(theta);
+y_list=radius*y_list.*sin(theta);
+A=struct('x',x_list,'y',y_list,'density',1);
+expgen('RoundDomainOutline.exp',A,1);
+
+%Call Bamg
+md=triangle(md,'RoundDomainOutline.exp',resolution);
+%md=bamg(md,'domain','RoundDomainOutline.exp','hmin',resolution);
+
+%move the closest node to the center
+[mini pos]=min(md.mesh.x.^2+md.mesh.y.^2);
+md.mesh.x(pos)=0;
+md.mesh.y(pos)=0;
+
+%delete domain
+delete('RoundDomainOutline.exp')
Index: /issm/trunk-jpl-damage/src/m/utils/Mesh/squaremesh.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Mesh/squaremesh.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Mesh/squaremesh.m	(revision 11330)
@@ -0,0 +1,78 @@
+function md=squaremesh(md,Lx,Ly,nx,ny)
+%SQUAREMESH - create a structured square mesh 
+%
+%   This script will generate a structured square mesh
+%   Lx and Ly are the dimension of the domain (in meters)
+%   nx anx ny are the number of nodes in the x and y direction
+%   The coordinates x and y returned are in meters.
+%
+%   Usage:
+%      [md]=squaremesh(md,Lx,Ly,nx,ny)
+
+%get number of elements and number of nodes
+nel=(nx-1)*(ny-1)*2;
+nods=nx*ny;
+
+%initialization
+segments=zeros(0,3);
+index=zeros(nel,3);
+x=zeros(nx*ny,1);
+y=zeros(nx*ny,1);
+
+%create coordinates
+for n=1:nx,
+	for m=1:ny,
+		x((n-1)*ny+m)=(n-1);
+		y((n-1)*ny+m)=(m-1);
+	end
+end
+
+%create index
+for n=1:(nx-1)
+	for m=1:(ny-1),
+		A=(n-1)*ny+m;
+		B=A+1;
+		C=n*ny+m;
+		D=C+1;
+		index((n-1)*(ny-1)*2+2*(m-1)+1,:)=[A C B];
+		index((n-1)*(ny-1)*2+2*m,:)=[B C D];
+	end
+end
+
+%Scale  x and y
+x=x/max(x)*Lx;
+y=y/max(y)*Ly;
+
+%create segments
+segments=zeros(2*(nx-1)+2*(ny-1),3);
+%left edge:
+segments(1:ny-1,:)=[[2:ny]' [1:ny-1]' 2*[1:ny-1]'-1];
+%right edge:
+segments(ny:2*(ny-1),:)=[[ny*(nx-1)+1:nx*ny-1]' [ny*(nx-1)+2:nx*ny]' 2*[(ny-1)*(nx-2)+1:(nx-1)*(ny-1)]'];
+%front edge:
+segments(2*(ny-1)+1:2*(ny-1)+(nx-1),:)=[[2*ny:ny:ny*nx]' [ny:ny:ny*(nx-1)]' [2*(ny-1):2*(ny-1):2*(nx-1)*(ny-1)]'];
+%back edge
+segments(2*(ny-1)+(nx-1)+1:2*(nx-1)+2*(ny-1),:)=[[1:ny:(nx-2)*ny+1]' [ny+1:ny:ny*(nx-1)+1]' [1:2*(ny-1):2*(nx-2)*(ny-1)+1]'];
+
+%plug coordinates and nodes
+md.mesh.x=x;
+md.mesh.y=y;
+md.mesh.z=zeros(nods,1);
+md.mesh.numberofvertices=nods;
+md.mesh.vertexonboundary=zeros(nods,1);md.mesh.vertexonboundary(segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(nods,1);
+md.mesh.vertexonsurface=ones(nods,1);
+
+%plug elements
+md.mesh.elements=index;
+md.mesh.segments=segments;
+md.mesh.numberofelements=nel;
+md.mesh.elementonbed=ones(nel,1);
+md.mesh.elementonsurface=ones(nel,1);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%plug other field
+md.mesh.dimension=2;
Index: /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/create_region.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/create_region.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/create_region.m	(revision 11330)
@@ -0,0 +1,15 @@
+function create_region(name)
+%CREATE_REGION - create region  ????
+%
+%   very temporary function.
+%   
+%   Usage: 
+%      create_region(name)
+
+eval(['mkdir ' name]);
+eval(['cd ' name ]);
+!mkdir Delivery Exp_Par Results
+cd Exp_Par
+!cp ../../RonneShelf/Exp_Par/* ./
+!rm -rf Hole*
+eval(['!mv Ronne.par ' name '.par']);
Index: /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/findarg.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/findarg.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/findarg.m	(revision 11330)
@@ -0,0 +1,51 @@
+function  vals=findarg(arglist,field)
+%FINDARG - find argument associated to a field in a list
+%
+%   This function parses through an argument list (typically varargin in a routine)
+%   looking for a character array equal to field. Once this is found, we return the 
+%   next value in the varargin (if possible). 
+%   Because field might appear several times in the argument list, we return a structure 
+%   holding all these values. 
+%   Note that all comparisons to field value are case independent.
+%
+%   Usage:
+%      vals=findarg(arglist,field)
+%
+%   Example:
+%      routine foobar calls vals=findarg('Data',varargin)
+%      with varargin='Data',1,'Data','foo','Plot','velocity','Arrow',4
+%      findarg would return the following structure: vals(1).value=1, vals(2).value='foo'; 
+
+%some argument checking: 
+if ((nargin==0) | (nargout==0)),
+	help findarg;
+	error('findarg error message');
+end
+
+if ~ischar(field),
+	error('findarg error message: field should be a string');
+end
+
+if ~iscell(arglist),
+	error('findarg error message: argument list should be a cell array.');
+end
+
+%Recover data to plot
+founddata=0;
+
+for i=1:(length(arglist)-1), %data in arglist comes in pairs, hence the -1.
+	if ischar(arglist{i}),
+		if (strcmpi(arglist{i},field)),
+			founddata=founddata+1;
+			if founddata==1,
+				vals.value=arglist{i+1};
+			else
+				vals(end+1).value=arglist{i+1};
+			end
+		end
+	end
+end
+
+if founddata==0,
+	vals=[];
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/netcdf.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/netcdf.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/netcdf.m	(revision 11330)
@@ -0,0 +1,136 @@
+function S = netcdf(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
Index: /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/netcdf2struct.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/netcdf2struct.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/netcdf2struct.m	(revision 11330)
@@ -0,0 +1,27 @@
+function S=netcdf2struct(File)
+%NETCDF2STRUCT - load netcdf file and convert to a matlab structure
+%
+%   Usage:
+%      S=netcdf2struct(File);
+
+%Read netcdf file
+data=netcdf(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
Index: /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/structtoobj.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/structtoobj.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Miscellaneous/structtoobj.m	(revision 11330)
@@ -0,0 +1,16 @@
+function obj=structtoobj(obj,S),
+%Convert struct to object
+
+	%Get object and structure fields
+	structfields=fields(S);
+	objprops    =properties(class(obj));
+
+	%recover object properties
+	for i=1:length(structfields),
+		fieldname =structfields{i};
+		if ismember(fieldname,objprops),
+			fieldvalue=getfield(S,fieldname);
+			obj=setfield(obj,fieldname,fieldvalue);
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Model/loadmodel.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Model/loadmodel.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Model/loadmodel.m	(revision 11330)
@@ -0,0 +1,40 @@
+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)
+	error(['loadmodel error message: file ' path ' does not exist']);
+end
+
+try,
+	%recover model on file and name it md
+	warning off MATLAB:unknownElementsNowStruc;
+	warning off MATLAB:load:classNotFound
+	struc=load(path,'-mat');
+	warning on MATLAB:unknownElementsNowStruc;
+	warning on MATLAB:load:classNotFound
+
+	name=char(fieldnames(struc));
+	if size(name,1)>1,
+		error(['loadmodel error message: file ' path ' contains several variables. Only one model should be present.']); 
+	end
+	md=struc.(name);
+	if nargout,
+		varargout{1}=md;
+	else
+		assignin('caller',name,md);
+	end
+catch me
+	disp(getReport(me))
+	error(['could not load model ' path]);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Model/loadmodellist.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Model/loadmodellist.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Model/loadmodellist.m	(revision 11330)
@@ -0,0 +1,50 @@
+function varargout=loadmodellist(path)
+%LOADMODELLIST- load a model using built-in load module
+%
+%   check that modellist prototype has not changed. if so, adapt to new modellist prototype.
+%
+%   Usage:
+%      mds=loadmodellist(path)
+%      loadmodellist path
+
+%check nargout
+if nargout>1,
+	error('loadmodellist usage error: mds=loadmodellist(path)');
+end
+%check existence
+if ~exist(path)
+	error(['loadmodellist error message: file ' path ' does not exist']);
+end
+
+%check that the file is readable
+[stat,mess]=fileattrib(path);
+if( stat==0 | mess.UserRead~=1),
+	error(['loadmodellist error message: file ' path ' is not readable (permission dinied).']);
+end
+
+%check number of variables
+if length(whos('-file',path))>1,
+	error(['loadmodellist error message: file ' path ' contains several variables. Only one model should be present.']);
+end
+
+try,
+	struc=load(path,'-mat');
+
+	%get name of model variable
+	fieldname=char(fieldnames(struc));
+	mds=eval(['struc.' fieldname]);
+	if ~strcmpi(class(mds),'model'),
+		mds2=modellist;
+		mds2=structtomodel(mds2,mds);
+		mds=mds2;
+		clear mds2;
+	end
+	if nargout,
+		varargout{1}=mds;
+	else
+		assignin('caller',fieldname,mds);
+	end
+catch me
+	disp(getReport(me))
+	error(['could not load model ' path]);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Numerics/cfl_step.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Numerics/cfl_step.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Numerics/cfl_step.m	(revision 11330)
@@ -0,0 +1,23 @@
+function maxtime=cfl_step(md,vx,vy);
+%CFL_STEP - return the maximum time step for the model in years
+%
+%   Dt < c / ( u/Dx +v/Dy )
+%
+%   Usage:
+%      maxtime=cfl_step(md,vx,vy);
+%
+%   Example:
+%      dt=cfl_step(md,md.results.diagnostic.vx,md.results.diagnostic.vy);
+
+%Check length of velocities 
+if size(vx,1)~=md.mesh.numberofvertices & size(vy,1)~=md.mesh.numberofvertices,
+	error('timestpes error message: size of velocity components must be the same as md.mesh.numberofvertices');
+end
+
+index=md.mesh.elements;
+edgex=max(md.mesh.x(index),[],2)-min(md.mesh.x(index),[],2);
+edgey=max(md.mesh.y(index),[],2)-min(md.mesh.y(index),[],2);
+vx=max(abs(vx(index)),[],2);
+vy=max(abs(vy(index)),[],2);
+
+maxtime=1/2*min(1./(vx./edgex+vy./edgey));
Index: /issm/trunk-jpl-damage/src/m/utils/OS/issmbbftpin.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/OS/issmbbftpin.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/OS/issmbbftpin.m	(revision 11330)
@@ -0,0 +1,48 @@
+function issmbbftpin(host, login,port,numstreams,path, packages)
+%BBFTPIN get packages from host, using bbftp. assuming unix system here.
+%
+%   usage: scpin(host,packages,path)
+%
+%
+
+%first get hostname
+hostname=oshostname();
+
+%first be sure packages are not in the current directory, this could conflict with pscp on windows. 
+%get initial warning mode
+state=warning('query', 'all');
+%remove warnings in case the files do not exist
+warning off
+for i=1:numel(packages),
+	delete(packages{i});
+end
+%back to initial warning state
+warning(state);
+
+%if hostname and host are the same, do a simple copy
+if strcmpi(hostname,host),
+
+    for i=1:numel(packages),
+		success=copyfile([path '/' packages{i}]); %keep going, even if success=0
+	end
+
+else
+
+	%build a string of the type: bbftp -s -u elarour -e 'setnbstream 8; cd /nobackupp10/elarour/Testing/Interactive3/; get Antarctica.outbin' pfe1.nas.nasa.gov
+	command=['!bbftp -s -V -u ' login ' -e ''setnbstream 8; cd ' path '; '];
+	for i=1:length(packages),
+		command=[command 'get ' packages{i} ';'];
+	end
+	command=[command '''  pfe1.nas.nasa.gov'];
+	
+	eval(command);
+
+	%check bbftp worked
+	for i=1:numel(packages),
+		if ~exist(['./' packages{i}]),
+			error('scpin error message: could not call scp on *nix system');
+		end
+	end
+
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/OS/issmbbftpout.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/OS/issmbbftpout.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/OS/issmbbftpout.m	(revision 11330)
@@ -0,0 +1,30 @@
+function issmbbftpout(host,path,login,port,numstreams,packages)
+%BBFTPOUT put packages onto host, using bbftp. assuming unix system here.
+%
+%   usage: bbftpout(host,path,login,port,numstream,packages)
+%
+%
+
+%get hostname
+hostname=oshostname();
+
+%if hostname and host are the same, do a simple copy
+if strcmpi(host,hostname),
+	for i=1:numel(packages),
+		here=pwd;
+		eval(['cd ' path])
+		system(['rm -rf ' packages{i} ]);
+		system(['ln -s ' here '/' packages{i} ' .']);
+		eval(['cd ' here]);
+	end
+else 
+	
+	%build a string of the type: bbftp -s -u elarour -e 'setnbstream 8; cd /nobackupp10/elarour/Testing/Interactive3/; put Antarctica.tar.gz' pfe1.nas.nasa.gov
+	command=['!bbftp -s -V -u ' login ' -e ''setnbstream 8; cd ' path '; ']
+	for i=1:length(packages),
+		command=[command 'put ' packages{i} ';'];
+	end
+	command=[command '''  pfe1.nas.nasa.gov'];
+	
+	eval(command);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/OS/issmscpin.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/OS/issmscpin.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/OS/issmscpin.m	(revision 11330)
@@ -0,0 +1,74 @@
+function scpin(host, login,port,path, packages)
+%SCPIN get packages from host, using scp on unix, and pscp on windows
+%
+%   usage: scpin(host,packages,path)
+%
+%
+
+%first get hostname
+hostname=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_TIER variable
+		[status,ISSM_TIER]=system('echo [%ISSM_TIER_WIN%]');
+		if status, 
+			error('scpin error message: could not find ISSM_TIER_WIN envirnoment variable');
+		end
+		ISSM_TIER=ISSM_TIER(2:end-2);
+
+		username=input('Username: (quoted string) ');
+		key=input('Key: (quoted string) ');
+
+		for i=1:numel(packages),
+			[status,result]=system([ISSM_TIER '/externalpackages/ssh/pscp.exe -l "' username '" -pw "' key '" ' host ':' path '/' packages{i} ' ./']);
+			if status, 
+				error('scpin error message: could not call putty pscp');
+			end
+		end
+
+	else
+		%just use standard unix scp
+		%string to copy multiple files using scp: 
+		string='\{';
+		for i=1:numel(packages)-1,
+			string=[string packages{i} ','];
+		end
+		string=[string packages{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('scpin error message: could not call scp on *nix system');
+			end
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/OS/issmscpout.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/OS/issmscpout.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/OS/issmscpout.m	(revision 11330)
@@ -0,0 +1,57 @@
+function issmscpout(host,path,login,port,packages)
+%SCPOUT send packages to a host, using scp on unix, and pscp on windows
+%
+%   usage: scpout(host,path,packages)
+%
+%
+
+%get hostname
+hostname=oshostname();
+
+%if hostname and host are the same, do a simple copy
+
+if strcmpi(host,hostname),
+	for i=1:numel(packages),
+		here=pwd;
+		eval(['cd ' path])
+		system(['rm -rf ' packages{i} ]);
+		system(['ln -s ' here '/' packages{i} ' .']);
+		eval(['cd ' here]);
+	end
+else 
+	if ispc,
+		%use the putty project pscp.exe: it should be in the path.
+		
+		%get ISSM_TIER variable
+		[status,ISSM_TIER]=system('echo [%ISSM_TIER_WIN%]');
+		if status, 
+			error('scpout error message: could not find ISSM_TIER_WIN envirnoment variable');
+		end
+		ISSM_TIER=ISSM_TIER(2:end-2);
+
+		username=input('Username: (quoted string) ');
+		key=input('Key: (quoted string) ');
+
+		for i=1:numel(packages),
+			[status,result]=system([ISSM_TIER '/externalpackages/ssh/pscp.exe -l "' username '" -pw "' key '" ' packages{i} ' ' host ':' path]);
+			if status, 
+				error('scpout error message: could not call putty pscp');
+			end
+		end
+
+	else
+		%just use standard unix scp
+		%create string of packages being sent
+		string='';
+		for i=1:numel(packages),
+			string=[string ' ' packages{i}];
+		end
+		string=[string ' '];
+		
+		if port,
+			eval(['!scp -P ' num2str(port) ' ' string ' ' login '@localhost:' path]);
+		else
+			eval(['!scp ' string ' ' login '@' host ':' path]);
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/OS/issmssh.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/OS/issmssh.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/OS/issmssh.m	(revision 11330)
@@ -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_TIER variable
+		[status,ISSM_TIER]=system('echo [%ISSM_TIER_WIN%]');
+		if status, 
+			error('issmssh error message: could not find ISSM_TIER_WIN envirnoment variable');
+		end
+		ISSM_TIER=ISSM_TIER(2:end-2);
+
+		username=input('Username: (quoted string) ');
+		key=input('Key: (quoted string) ');
+
+		system([ISSM_TIER '/externalpackages/ssh/plink.exe -ssh -l "' username '" -pw "' key '" ' host ' "' command '"']);
+
+	else
+		%just use standard unix ssh
+		if port,
+			eval(['!ssh -l ' login ' -p ' num2str(port) ' localhost "' command '"']);
+		else
+			eval(['!ssh -l ' login ' ' host ' "' command '"']);
+		end
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/OS/listfiles.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/OS/listfiles.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/OS/listfiles.m	(revision 11330)
@@ -0,0 +1,22 @@
+function list=listfiles()
+%LISTFILES list files inside a directory
+%        this is very OS dependent.
+%
+%   usage: list=listfiles;
+%
+%
+%   see also LS DIR
+
+%use dir, as it seems to act OS independent
+
+first_list=dir;
+list={};
+
+for i=1:numel(first_list),
+	if (  ~strcmpi(first_list(i).name,'.') &...
+			~strcmpi(first_list(i).name,'..') &...
+			~strcmpi(first_list(i).name,'NightlyRun') &...
+			~strcmpi(first_list(i).name,'.svn')),
+		list{end+1}=first_list(i).name;
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/OS/listfilesparallel.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/OS/listfilesparallel.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/OS/listfilesparallel.m	(revision 11330)
@@ -0,0 +1,15 @@
+function list=listfilesparallel(rank,numprocs)
+%LISTFILESPARALLEL list files inside a directory, depending on rank  and number of processors running this routine.
+%        this is very OS dependent.
+%
+%   usage: list=listfilesparallel(rank,numprocs);
+%
+%
+%   see also LS DIR LISTFILES
+
+list=listfiles';
+numfiles=numel(list);
+
+%we now have a list, split it between all the processors.
+[i1,i2]=parallelrange(rank,numprocs,numfiles);
+list=list(i1:i2);
Index: /issm/trunk-jpl-damage/src/m/utils/OS/oshostname.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/OS/oshostname.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/OS/oshostname.m	(revision 11330)
@@ -0,0 +1,22 @@
+function hostname=oshostname()
+%OSHOSTNAME figure out hostname, irrespective of os type
+%
+%   usage: hostname=oshostname();
+%
+%
+
+if ispc,
+	[status,hostname]=system('hostname');hostname=hostname(1:end-1);
+
+	if status, 
+		error('oshostname error message: could not run hostname command on windows os');
+	end
+
+else
+	[status,hostname]=system(['hostname -s | sed ''s/-//g''']);
+	if status, 
+		error('oshostname error message: could not run hostname command on *nix os');
+	end
+	hostname=hostname(1:end-1);
+	hostname=ddewhite(hostname);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Plot/plot2patch.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Plot/plot2patch.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Plot/plot2patch.m	(revision 11330)
@@ -0,0 +1,16 @@
+function [px py]=plot2patch(x,y,miny)
+%PLOT2PATCH: build patch out of x,y plot.
+%
+% Usage: [px,py]=plot2patch(x,y,miny)
+%
+%        where px and py are a list of point defining a closed polygon.
+%              x,y are the values of the plot
+%              miny is the y-value used to close the plot into a closed polygon.
+% 
+%      See also patch, plot
+
+px=x;
+py=y;
+
+px=[px; flipud(x)];
+py=[py; ; miny*ones(length(x),1)];
Index: /issm/trunk-jpl-damage/src/m/utils/Plot/squarezoom.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Plot/squarezoom.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Plot/squarezoom.m	(revision 11330)
@@ -0,0 +1,20 @@
+function squarezoom()
+%SQUAREZOOM - zoom on a part of a figure
+%
+%   Usage:
+%      squarezoom()
+
+disp('Click twice to define a square where you want to zoom. First click for upper left corner, second for lower right corner');
+[x,y]=ginput(2);
+dx=x(2)-x(1);
+dy=y(1)-y(2);
+
+if dx>dy,
+	delta=dx-dy;
+	xlim([x(1) x(2)]);
+	ylim([y(2)-delta/2 y(1)+delta/2]);
+else
+	delta=dy-dx;
+	xlim([x(1)-delta/2 x(2)+delta/2]);
+	ylim([y(2) y(1)]);
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Shell/flaimdir.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Shell/flaimdir.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Shell/flaimdir.m	(revision 11330)
@@ -0,0 +1,7 @@
+function FLAIM_DIR=flaimdir()
+%ISSMDIR - Get FLAIM installation directory
+%
+%   Usage:
+%      FLAIM_DIR=flaimdir()
+
+FLAIM_DIR=[issmtier '/externalpackages/flaim/install'];
Index: /issm/trunk-jpl-damage/src/m/utils/Shell/issmdir.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Shell/issmdir.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Shell/issmdir.m	(revision 11330)
@@ -0,0 +1,11 @@
+function ISSM_DIR=issmdir()
+%ISSMDIR - Get ISSM_DIR environment variable contents.
+%
+%   Usage:
+%      ISSM_DIR=issmdir()
+
+ISSM_DIR =getenv('ISSM_DIR');
+
+if (isempty(ISSM_DIR)),
+	error('issmdir error message: ''ISSM_DIR'' environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!');
+end
Index: /issm/trunk-jpl-damage/src/m/utils/Shell/issmtier.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/Shell/issmtier.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/Shell/issmtier.m	(revision 11330)
@@ -0,0 +1,11 @@
+function ISSM_TIER=issmtier()
+%ISSMTIER - Get ISSM_TIER environment variable contents.
+%
+%   Usage:
+%      ISSM_TIER=issmtier()
+
+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
Index: /issm/trunk-jpl-damage/src/m/utils/String/ddeblank.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/String/ddeblank.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/String/ddeblank.m	(revision 11330)
@@ -0,0 +1,29 @@
+function sout = ddeblank(s)
+%DDEBLANK Double deblank. Strip both leading and trailing blanks.
+%
+%   DDEBLANK(S) removes leading and trailing blanks and null characters from
+%   the string S.  A null character is one that has a value of 0.
+%
+%   See also DEBLANK, DEWHITE, DDEWHITE.
+
+%   Author:      Peter J. Acklam
+%   Time-stamp:  2003-10-13 11:13:07 +0200
+%   E-mail:      pjacklam@online.no
+%   URL:         http://home.online.no/~pjacklam
+
+   error(nargchk(1, 1, nargin));
+   if ~ischar(s)
+      warning('Input must be a string (char array).');
+   end
+
+   if isempty(s)
+      sout = s;
+      return;
+   end
+
+   [r, c] = find( (s ~= ' ') & (s ~= 0) );
+   if size(s, 1) == 1
+      sout = s(min(c) : max(c));
+   else
+      sout = s(:, min(c) : max(c));
+   end
Index: /issm/trunk-jpl-damage/src/m/utils/String/ddewhite.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/String/ddewhite.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/String/ddewhite.m	(revision 11330)
@@ -0,0 +1,30 @@
+function sout = ddewhite(s)
+%DDEWHITE Double dewhite. Strip both leading and trailing whitespace.
+%
+%   DDEWHITE(S) removes leading and trailing white space and any null
+%   characters from the string S.  A null character is one that has an absolute
+%   value of 0.
+%
+%   See also DEWHITE, DEBLANK, DDEBLANK.
+
+%   Author:      Peter J. Acklam
+%   Time-stamp:  2003-10-13 11:12:57 +0200
+%   E-mail:      pjacklam@online.no
+%   URL:         http://home.online.no/~pjacklam
+
+   error(nargchk(1, 1, nargin));
+   if ~ischar(s)
+      error('Input must be a string (char array).');
+   end
+
+   if isempty(s)
+      sout = s;
+      return;
+   end
+
+   [r, c] = find(~isspace(s));
+   if size(s, 1) == 1
+      sout = s(min(c) : max(c));
+   else
+      sout = s(:, min(c) : max(c));
+   end
Index: /issm/trunk-jpl-damage/src/m/utils/String/dewhite.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/String/dewhite.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/String/dewhite.m	(revision 11330)
@@ -0,0 +1,30 @@
+function sout = dewhite(s)
+%DEWHITE Dewhite. Strip trailing whitespace.
+%
+%   DEWHITE(S) removes leading and trailing white space and any null characters
+%   from the string S.  A null character is one that has an absolute value of
+%   0.
+%
+%   See also DDEWHITE, DEBLANK, DDEBLANK.
+
+%   Author:      Peter J. Acklam
+%   Time-stamp:  2003-10-13 11:12:52 +0200
+%   E-mail:      pjacklam@online.no
+%   URL:         http://home.online.no/~pjacklam
+
+   error(nargchk(1, 1, nargin));
+   if ~ischar(s)
+      error( 'Input must be a string (char array).' );
+   end
+
+   if isempty(s)
+      sout = s;
+      return;
+   end
+
+   [r, c] = find(~isspace(s));
+   if size(s, 1) == 1
+      sout = s(1:max(c));
+   else
+      sout = s(:,1:max(c));
+   end
Index: /issm/trunk-jpl-damage/src/m/utils/String/discardnum.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/String/discardnum.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/String/discardnum.m	(revision 11330)
@@ -0,0 +1,14 @@
+function string2=discardnum(string)
+%DISCARDNUM -  ??????
+%
+%   Usage:
+%      string2=discardnum(string)
+
+string2=string;
+
+for i=1:length(string),
+	if (((string(i)-0) <=57) & ((string(i)-0) >=48)),
+		string2=string(1:i-1);
+		break;
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/String/ismemberi.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/String/ismemberi.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/String/ismemberi.m	(revision 11330)
@@ -0,0 +1,26 @@
+function flag=ismemberi(string,list),
+%ISMEMBERI - return 1 if a string belongs to a list (case insensitive)
+%
+%   same function as Matlab's ismember except that it
+%   is case insensitive
+%
+%   Usage:
+%      flag=ismemberi(string,list);
+%
+%   Example:
+%      flag=ismemberi('test','{'test1','test2','test3'});
+
+if ~iscell(list)
+	error('ismemberi error message: the list of string must be a cell!')
+end
+
+%initialize output
+flag=0;
+
+%go through the list
+for i=1:length(list),
+	if strcmpi(string,list{i}),
+		flag=i;
+		return
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/String/issmprintf.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/String/issmprintf.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/String/issmprintf.m	(revision 11330)
@@ -0,0 +1,13 @@
+function issmprintf(flag,format,varargin)
+%ISSMPRINTF -  display string in solution sequences. wrapper to disp and sprintf.  
+%
+%   Usage:
+%      issmprintf(flag,format,string)
+%      flag can be used to switch display on and off
+%
+%   Example:
+%      issmprintf(1,'%s\n','string to display');
+	
+if flag,
+	disp(sprintf(format,varargin{:}));
+end
Index: /issm/trunk-jpl-damage/src/m/utils/String/logoutput.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/String/logoutput.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/String/logoutput.m	(revision 11330)
@@ -0,0 +1,7 @@
+function logoutput(logstring,message)
+%LOGOUTPUT - embed a log string into an error message, used in the nightly runs.
+%
+%   Usage:
+%      logoutput(logstring,message)
+
+disp(sprintf('%s%s',logstring,message));
Index: /issm/trunk-jpl-damage/src/m/utils/String/strsplit.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/String/strsplit.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/String/strsplit.m	(revision 11330)
@@ -0,0 +1,91 @@
+function splittedstring = strsplit(inpstr,delimiter)
+%STRSPLIT - split a tring of delimiter separated values
+%
+%   This function should be used to split a string of delimiter separated
+%   values.  If all values are numerical values the returned matrix is a
+%   double array but if there is one non numerical value a cell array is
+%   returned.  You can check this with the iscell() function.
+%   inpstr: string containing delimiter separatede numerical values, eg
+%           3498,48869,23908,34.67
+%   Output: An x by 1 matrix containing the splitted values
+%   Delimiter: optional, if omitted the delimiter is , (comma)
+%
+%   Usage:
+%      output = strsplit(inpstr[,delimiter])
+%
+
+%   mailto:    gie.spaepen@ua.ac.be
+
+
+
+%Check input arguments
+if(nargin < 1)
+    error('There is no argument defined');
+else
+    if(nargin == 1)
+        strdelim = ',';
+        %Verbose off!! disp 'Delimiter set to ,';
+    else
+        strdelim = delimiter;
+    end
+end
+
+%deblank string
+deblank(inpstr);
+
+%Get number of substrings
+idx  = findstr(inpstr,strdelim);
+if size(idx) == 0
+    disp 'No delimiter in string, inputString is returned';
+    splittedstring = inpstr;
+else
+    %Define size of the indices
+    sz = size(idx,2);
+    %Define splittedstring
+    tempsplit = {};
+    %Loop through string and itinerate from delimiter to delimiter
+    for i = 1:sz
+        %Define standard start and stop positions for the start position,
+        %choose 1 as startup position because otherwise you get an array
+        %overflow, for the endposition you can detemine it from the
+        %delimiter position
+        strtpos = 1;
+        endpos = idx(i)-1;
+        %If i is not the beginning of the string get it from the delimiter
+        %position
+        if i ~= 1
+            strtpos = idx(i-1)+1;
+        end
+        %If i is equal to the number of delimiters get the last element
+        %first by determining the lengt of the string and then replace the
+        %endpos back to a standard position
+        if i == sz
+            endpos = size(inpstr,2); 
+            tempsplit(i+1) = {inpstr(idx(i)+1 : endpos)};
+            endpos = idx(i)-1;
+        end
+        %Add substring to output: splittedstring a cell array
+        tempsplit(i) = {inpstr(strtpos : endpos)};   
+    end
+    %Flag 
+    isallnums = 1;
+    %Check is there are NaN values if matrix elements are converted to
+    %doubles
+    for i = 1:size(tempsplit,2)
+        tempdouble = str2double(tempsplit(i));
+        if(isnan(tempdouble))
+            isallnums = 0;
+        end
+    end
+    %If isallnums = 1 then return a double array otherwise return a cell
+    %array
+    if(isallnums == 1)
+        for i = 1:size(tempsplit,2)
+            splittedstring(i) = str2double(tempsplit(i));
+        end
+    else
+        splittedstring = tempsplit;
+    end
+    
+        
+end
Index: /issm/trunk-jpl-damage/src/m/utils/String/strsplit_strict.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/String/strsplit_strict.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/String/strsplit_strict.m	(revision 11330)
@@ -0,0 +1,37 @@
+function splittedstring = strsplit(inpstr,delimiter)
+%STRSPLIT - split a tring of delimiter separated values
+%
+%   Usage:
+%      output = strsplit_strict(inpstr,delimiter)
+
+
+%Check input arguments
+if(nargin ~= 2)
+    error('There is no argument defined');
+end
+
+%deblank string
+deblank(inpstr);
+
+%Get number of substrings
+idx  = findstr(inpstr,delimiter);
+if size(idx) == 0
+    splittedstring = {inpstr};
+else
+    sz = size(idx,2);
+    splittedstring = {};
+    %Loop through string and itinerate from delimiter to delimiter
+    for i = 1:sz
+        strtpos = 1;
+        endpos = idx(i)-1;
+        if i ~= 1
+            strtpos = idx(i-1)+1;
+        end
+        if i == sz
+            endpos = size(inpstr,2); 
+            splittedstring(i+1) = {inpstr(idx(i)+1 : endpos)};
+            endpos = idx(i)-1;
+        end
+        splittedstring(i) = {inpstr(strtpos : endpos)};   
+    end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/consistency/checkfield.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/consistency/checkfield.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/consistency/checkfield.m	(revision 11330)
@@ -0,0 +1,195 @@
+function checkfield(md,fieldname,varargin)
+%CHECKFIELD - check field consistency
+%
+%   Used to check model consistency.
+%   Available options:
+%      - NaN: 1 if check that there is no NaN
+%      - size: [lines cols], NaN for non checked dimensions
+%      - >:  greater than provided value
+%      - >=: greater or equal to provided value
+%      - <:  smallerthan provided value
+%      - <=: smaller or equal to provided value
+%      - < vec:  smallerthan provided values on each vertex
+%      - forcing: 1 if check forcing consistency (size and time)
+%      - values: cell of strings or vector of acceptable values
+%      - numel: list of acceptable number of elements
+%      - cell: 1 if check that is cell
+%      - empty: 1 if check that non empty
+%      - message: overloaded error message
+%
+%   Usage:
+%      checkfield(md,fieldname,options);
+%
+%   Example:
+%      checkfield(md,'mesh.elementonbed','size',[md.mesh.numberofelements 1],'values',[0 1]);
+%      checkfield(md,'diagnostic.icefront','size',[NaN 4],'NaN',1);
+%      checkfield(md,'diagnostic.icefront(:,end)','values',[0 1 2]);
+
+%get options
+options=pairoptions(varargin{:});
+
+%get field from model
+eval(['field=md.' fieldname ';']);
+
+%check empty
+if exist(options,'empty')
+	if isempty(field),
+		checkmessage(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)),
+			checkmessage(getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should have ' num2str(fieldsize(2)) ' columns']));
+		end
+	elseif isnan(fieldsize(2)),
+		if (size(field,1)~=fieldsize(1)),
+			checkmessage(getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should have ' num2str(fieldsize(1)) ' lines']));
+		end
+	else
+		if ((size(field)~=fieldsize(1)) |  (size(field,2)~=fieldsize(2)))
+			checkmessage(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
+			checkmessage(getfieldvalue(options,'message',...
+				['field ''' fieldname ''' size should be ' sprintf('%g ',fieldnumel) ]));
+		elseif length(fieldnumel)==2
+			checkmessage(getfieldvalue(options,'message',...
+				['field ''' fieldname ''' size should be ' num2str(fieldnumel(1)) ' or ' num2str(fieldnumel(2)) ]));
+		else
+			checkmessage(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)),
+		checkmessage(getfieldvalue(options,'message',...
+			['NaN values found in field ''' fieldname '''']));
+	end
+end
+
+%check NaN
+if getfieldvalue(options,'cell',0);
+	if ~iscell(field),
+		checkmessage(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
+				checkmessage(getfieldvalue(options,'message',...
+					['field ''' fieldname ''' value should be ' fieldvalues{1} ]));
+			elseif length(fieldvalues)==2
+				checkmessage(getfieldvalue(options,'message',...
+					['field ''' fieldname ''' values should be ' fieldvalues{1} ' or ' fieldvalues{2} ]));
+			else
+				checkmessage(getfieldvalue(options,'message',...
+					['field ''' fieldname ''' should have values in ' sprintf('''%s'', ',fieldvalues{1:end-1}) 'or ''' fieldvalues{end} '''']));
+			end
+		end
+	else
+		checkmessage(getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should be one of the following strings: ' sprintf('''%s'', ',fieldvalues{1:end-1}) 'or ''' fieldvalues{end} '''']));
+	end
+else
+	field2=reshape(field,prod(size(field)),1);
+	if isnumeric(field),
+		if any(~ismember(field2,fieldvalues)),
+			checkmessage(getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should have values in [' num2str(fieldvalues) ']']));
+		end
+	else
+		checkmessage(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),
+		checkmessage(getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values above ' num2str(lowerbound)]));
+	end
+end
+if exist(options,'>')
+	lowerbound=getfieldvalue(options,'>');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2<=lowerbound),
+		checkmessage(getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values above ' num2str(lowerbound)]));
+	end
+end
+
+%check smaller
+if exist(options,'<=')
+	upperbound=getfieldvalue(options,'<=');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2>upperbound),
+		checkmessage(getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values below ' num2str(upperbound)]));
+	end
+end
+if exist(options,'<')
+	upperbound=getfieldvalue(options,'<');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2>=upperbound),
+		checkmessage(getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values below ' num2str(upperbound(1))]));
+	end
+end
+
+%check file
+if getfieldvalue(options,'file',0),
+	if ~exist(field,'file')
+		checkmessage(['file profided 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,
+			checkmessage(getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should have only one column as there are md.mesh.numberofvertices lines']));
+		end
+	elseif size(field,1)==md.mesh.numberofvertices+1
+		if any(field(end,:)~=sort(field(end,:))),
+			checkmessage(getfieldvalue(options,'message',...
+				['field ''' fieldname ''' columns should be chronological']));
+		end
+		if any(field(end,1:end-1)==field(end,2:end)),
+			checkmessage(getfieldvalue(options,'message',...
+				['field ''' fieldname ''' columns must not contain duplicate timesteps']));
+		end
+	else
+		checkmessage(getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have md.mesh.numberofvertices or md.mesh.numberofvertices+1 lines']));
+	end
+end
Index: /issm/trunk-jpl-damage/src/m/utils/consistency/checkmessage.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/consistency/checkmessage.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/consistency/checkmessage.m	(revision 11330)
@@ -0,0 +1,10 @@
+function checkmessage(string)
+%CHECKMESSAGE - checkmessage
+%
+%   Used to check model consistency
+%
+%   Usage:
+%      checkmessage(string);
+
+disp(['model not consistent: ' string]);
+modelconsistency(false);
Index: /issm/trunk-jpl-damage/src/m/utils/consistency/modelconsistency.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/consistency/modelconsistency.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/consistency/modelconsistency.m	(revision 11330)
@@ -0,0 +1,23 @@
+function flag=modelconsistency(flag_in)
+%MODELCONSISTENCY - return flag for model consistency
+%
+%   Used to check model consistency
+%
+%   Usage:
+%      flag=modelconsistency(flag_in)
+
+persistent consistency;
+
+if nargin==1 & nargout==0,
+	%OK model is inconsistent, set flag as false
+	consistency=flag_in;
+elseif nargin==0 & nargout==1,
+	if isempty(consistency),
+		%modelinconsistent has never been called, model is consistent
+		consistency=true;
+	end
+else
+	message('Bad usage');
+end
+
+flag=consistency;
Index: /issm/trunk-jpl-damage/src/m/utils/qmu/lclist_write.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/qmu/lclist_write.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/qmu/lclist_write.m	(revision 11330)
@@ -0,0 +1,62 @@
+%
+%  function to write linear constraint list
+%
+function []=lclist_write(fidi,cstring,cstring2,dvar)
+
+if isempty(dvar)
+    return;
+end
+
+%  put linear constraints into lists for writing
+
+nvar=0;
+pmatrix=[];
+plower =[];
+pupper =[];
+ptarget=[];
+pstype =[];
+pscale =[];
+
+fnames=fieldnames(dvar);
+for i=1:numel(fnames)
+    nvar=nvar+numel(dvar.(fnames{i}));
+    pmatrix=[pmatrix prop_matrix(dvar.(fnames{i}))];
+    plower =[plower  prop_lower(dvar.(fnames{i})) ];
+    pupper =[pupper  prop_upper(dvar.(fnames{i})) ];
+    ptarget=[ptarget prop_target(dvar.(fnames{i}))];
+    pstype =[pstype  prop_stype(dvar.(fnames{i})) ];
+    pscale =[pscale  prop_scale(dvar.(fnames{i})) ];
+end
+
+%  write linear constraints
+
+disp(sprintf('  Writing %d %s linear constraints.',...
+    nvar,cstring));
+
+if ~isempty(pmatrix)
+    fprintf(fidi,'\t  %s_matrix =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pmatrix,6,76);
+end
+if ~isempty(plower)
+    fprintf(fidi,'\t  %s_lower_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),plower ,6,76);
+end
+if ~isempty(pupper)
+    fprintf(fidi,'\t  %s_upper_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pupper ,6,76);
+end
+if ~isempty(ptarget)
+    fprintf(fidi,'\t  %s_targets =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),ptarget,6,76);
+end
+if ~isempty(pstype)
+    fprintf(fidi,'\t  %s_scale_types =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstype ,6,76);
+end
+if ~isempty(pscale)
+    fprintf(fidi,'\t  %s_scales =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pscale ,6,76);
+end
+
+end
+
Index: /issm/trunk-jpl-damage/src/m/utils/qmu/param_write.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/qmu/param_write.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/qmu/param_write.m	(revision 11330)
@@ -0,0 +1,24 @@
+%
+%  function to write a parameter
+%
+function []=param_write(fidi,sbeg,pname,smid,send,params)
+
+if ~isfield(params,pname)
+    warning('param_write:param_not_found',...
+        'Parameter ''%s'' not found in structure.',pname);
+    return
+end
+
+if islogical(params.(pname)) && ~params.(pname)
+    return
+end
+
+if     islogical(params.(pname))
+    fprintf(fidi,[sbeg '%s' send],pname);
+elseif ischar   (params.(pname))
+    fprintf(fidi,[sbeg '%s' smid '%s' send],pname,params.(pname));
+elseif isnumeric(params.(pname))
+    fprintf(fidi,[sbeg '%s' smid '%g' send],pname,params.(pname));
+end
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/qmu/rlev_write.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/qmu/rlev_write.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/qmu/rlev_write.m	(revision 11330)
@@ -0,0 +1,66 @@
+%
+%  function to write response levels
+%
+function []=rlev_write(fidi,dresp,params)
+
+if isempty(dresp)
+    return;
+end
+
+%  put responses into lists for writing
+
+nresp=0;
+respl={};
+probl={};
+rell ={};
+grell={};
+
+fnames=fieldnames(dresp);
+for i=1:numel(fnames)
+    nresp=nresp+numel(dresp.(fnames{i}));
+    [respli,probli,relli,grelli]=prop_levels(dresp.(fnames{i}));
+    respl=[respl respli];
+    probl=[probl probli];
+    rell =[rell  relli ];
+    grell=[grell grelli];
+end
+
+%  write response levels
+
+param_write(fidi,'\t  ','distribution',' ','\n',params);
+if ~isempty(respl)
+    rlevi_write(fidi,'response_levels',respl);
+    param_write(fidi,'\t  ','compute',' ','\n',params);
+end 
+if ~isempty(probl)
+    rlevi_write(fidi,'probability_levels',probl);
+end
+if ~isempty(rell)
+    rlevi_write(fidi,'reliability_levels',rell);
+end
+if ~isempty(grell)
+    rlevi_write(fidi,'gen_reliability_levels',grell);
+end
+
+end
+
+%
+%  function to each type of response level
+%
+function []=rlevi_write(fidi,ltype,levels)
+
+fprintf(fidi,'\t  num_%s =',ltype);
+for i=1:numel(levels)
+    fprintf(fidi,' %d',length(levels{i}));
+end
+fprintf(fidi,'\n');
+
+fprintf(fidi,'\t  %s =\n',ltype);
+
+for i=1:numel(levels)
+    if ~isempty(levels{i})
+        vector_write(fidi,sprintf('\t    '),levels{i},8,76);
+    end
+end
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/qmu/rlist_write.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/qmu/rlist_write.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/qmu/rlist_write.m	(revision 11330)
@@ -0,0 +1,70 @@
+%
+%  function to write response list
+%
+function [rdesc]=rlist_write(fidi,cstring,cstring2,dresp,rdesc)
+
+if isempty(dresp)
+    return;
+end
+
+%  put responses into lists for writing
+%  (and accumulate descriptors into list for subsequent writing)
+
+nresp=0;
+pstype =[];
+pscale =[];
+pweight=[];
+plower =[];
+pupper =[];
+ptarget=[];
+
+fnames=fieldnames(dresp);
+for i=1:numel(fnames)
+    nresp=nresp+numel(dresp.(fnames{i}));
+    pstype =[pstype  prop_stype(dresp.(fnames{i})) ];
+    pscale =[pscale  prop_scale(dresp.(fnames{i})) ];
+    pweight=[pweight prop_weight(dresp.(fnames{i}))];
+    plower =[plower  prop_lower(dresp.(fnames{i})) ];
+    pupper =[pupper  prop_upper(dresp.(fnames{i})) ];
+    ptarget=[ptarget prop_target(dresp.(fnames{i}))];
+    rdesc  =[rdesc   prop_desc(dresp.(fnames{i}),fnames{i})];
+end
+
+%  write responses
+
+disp(sprintf('  Writing %d %s responses.',nresp,cstring));
+
+fprintf(fidi,'\tnum_%s = %d\n',cstring,nresp);
+if ~isempty(pstype)
+    fprintf(fidi,'\t  %s_scale_types =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstype ,6,76);
+end
+if ~isempty(pscale)
+    fprintf(fidi,'\t  %s_scales =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pscale ,6,76);
+end
+if ~isempty(pweight)
+    switch cstring2
+        case 'objective_function'
+            fprintf(fidi,'\t  %s_weights =\n','multi_objective');
+            vector_write(fidi,sprintf('\t    '),pweight,6,76);
+        case 'least_squares_term'
+            fprintf(fidi,'\t  %s_weights =\n','least_squares');
+            vector_write(fidi,sprintf('\t    '),pweight,6,76);
+    end
+end
+if ~isempty(plower)
+    fprintf(fidi,'\t  %s_lower_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),plower ,6,76);
+end
+if ~isempty(pupper)
+    fprintf(fidi,'\t  %s_upper_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pupper ,6,76);
+end
+if ~isempty(ptarget)
+    fprintf(fidi,'\t  %s_targets =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),ptarget,6,76);
+end
+
+end
+
Index: /issm/trunk-jpl-damage/src/m/utils/qmu/vector_write.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/qmu/vector_write.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/qmu/vector_write.m	(revision 11330)
@@ -0,0 +1,52 @@
+
+%%  function to write a vector on multiple lines
+
+function []=vector_write(fidi,sbeg,vec,nmax,cmax)
+
+if ~exist('nmax','var') || isempty(nmax)
+    nmax=Inf;
+end
+if ~exist('cmax','var') || isempty(cmax)
+    cmax=Inf;
+end
+
+%  set up first iteration
+
+svec =[];
+nitem=nmax;
+lsvec=cmax;
+
+%  transpose vector from column-wise to row-wise
+
+vec=vec';
+
+%  assemble each line, flushing when necessary
+
+for i=1:numel(vec)
+    if isnumeric(vec(i))
+        sitem=sprintf('%g'    ,vec(i));
+    else
+        sitem=sprintf('''%s''',char(vec(i)));
+    end
+    nitem=nitem+1;
+    lsvec=lsvec+1+length(sitem);
+    
+    if (nitem <= nmax) && (lsvec <= cmax)
+        svec=[svec ' ' sitem];
+    else
+        if ~isempty(svec)
+            fprintf(fidi,'%s\n',svec);
+        end
+        svec=[sbeg sitem];
+        nitem=1;
+        lsvec=length(svec);
+    end
+end
+
+%  flush buffer at end, if necessary
+
+if ~isempty(svec)
+    fprintf(fidi,'%s\n',svec);
+end
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/qmu/vlist_write.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/qmu/vlist_write.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/qmu/vlist_write.m	(revision 11330)
@@ -0,0 +1,80 @@
+%
+%  function to write variable list
+%
+function []=vlist_write(fidi,cstring,cstring2,dvar)
+
+if isempty(dvar)
+    return;
+end
+
+%  put variables into lists for writing
+
+nvar=0;
+pinitpt=[];
+plower =[];
+pupper =[];
+pmean  =[];
+pstddev=[];
+pinitst=[];
+pstype =[];
+pscale =[];
+pdesc  =[];
+
+fnames=fieldnames(dvar);
+for i=1:numel(fnames)
+    nvar=nvar+numel(dvar.(fnames{i}));
+    pinitpt=[pinitpt prop_initpt(dvar.(fnames{i}))];
+    plower =[plower  prop_lower(dvar.(fnames{i})) ];
+    pupper =[pupper  prop_upper(dvar.(fnames{i})) ];
+    pmean  =[pmean   prop_mean(dvar.(fnames{i}))  ];
+    pstddev=[pstddev prop_stddev(dvar.(fnames{i}))];
+    pinitst=[pinitst prop_initst(dvar.(fnames{i}))];
+    pstype =[pstype  prop_stype(dvar.(fnames{i})) ];
+    pscale =[pscale  prop_scale(dvar.(fnames{i})) ];
+    pdesc  =[pdesc   prop_desc(dvar.(fnames{i}),fnames{i})];
+end
+
+%  write variables
+%  (using Dakota 4.1 syntax for backward compatability)
+
+disp(sprintf('  Writing %d %s variables.',nvar,cstring));
+
+fprintf(fidi,'\t%s = %d\n',cstring,nvar);
+if ~isempty(pinitpt)
+    fprintf(fidi,'\t  %s_initial_point =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pinitpt,6,76);
+end
+if ~isempty(plower)
+    fprintf(fidi,'\t  %s_lower_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),plower ,6,76);
+end
+if ~isempty(pupper)
+    fprintf(fidi,'\t  %s_upper_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pupper ,6,76);
+end
+if ~isempty(pmean)
+    fprintf(fidi,'\t  %s_means =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pmean  ,6,76);
+end
+if ~isempty(pstddev)
+    fprintf(fidi,'\t  %s_std_deviations =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstddev,6,76);
+end
+if ~isempty(pinitst)
+    fprintf(fidi,'\t  %s_initial_state =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pinitst,6,76);
+end
+if ~isempty(pstype)
+    fprintf(fidi,'\t  %s_scale_types =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstype ,6,76);
+end
+if ~isempty(pscale)
+    fprintf(fidi,'\t  %s_scales =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pscale ,6,76);
+end
+if ~isempty(pdesc)
+    fprintf(fidi,'\t  %s_descriptors =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pdesc  ,6,76);
+end
+
+end
Index: /issm/trunk-jpl-damage/src/m/utils/recursivepath.m
===================================================================
--- /issm/trunk-jpl-damage/src/m/utils/recursivepath.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/m/utils/recursivepath.m	(revision 11330)
@@ -0,0 +1,38 @@
+function p = recursivepath(d)
+%RECURSIVEPATH - generate paths in a directory
+%
+%   this routine is equivalent to Matlab's genpath except that it skips CVS and .svn directories
+%
+%   Usage:
+%      p = recursivepath(d)
+
+%initialize path to be returned
+p = '';
+sep=pathsep;  %directory separator
+
+% Generate path based on given root directory
+files=dir(d);
+if isempty(files)
+	return
+end
+
+% Add d to the path even if it is empty.
+p = [p d sep];
+
+% set logical vector for subdirectory entries in d
+isdir = logical(cat(1,files.isdir));
+
+% Recursively goes through the subdirectories of d
+dirs=files(isdir); % select only directory entries from the current listing
+for i=1:length(dirs)
+	dirname=dirs(i).name;
+	if ~strcmp(dirname,'.')    & ...
+		~strcmp(dirname,'..')   & ...
+		~strcmp(dirname,'.svn') & ...
+		~strcmp(dirname,'CVS')  & ...
+		~strncmp(dirname,'@',1) & ... %Method directories not allowed in MATLAB path
+		~strcmp(dirname,'private')    %private directories not allowed in MATLAB path
+
+		p = [p recursivepath(fullfile(d,dirname))];
+	end
+end
Index: /issm/trunk-jpl-damage/src/mex/AddExternalResult/AddExternalResult.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/AddExternalResult/AddExternalResult.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/AddExternalResult/AddExternalResult.cpp	(revision 11330)
@@ -0,0 +1,54 @@
+/*\file AddExternalResult.c
+ *\brief: output results inside elements, and in femmodel
+ */
+
+#include "./AddExternalResult.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	DataSet* results=NULL;
+	int      type,ncols,nraws;
+	double*  value=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&AddExternalResultUsage);
+
+	/*Input datasets: */
+	FetchMatlabData(&results,RESULTS);
+	FetchMatlabData(&type,TYPE);
+	FetchMatlabData(&value,&nraws,&ncols,VALUE);
+
+	/*results might be NILL, allocate: */
+	if(!results)results=new Results();
+
+	/*Find class of the value and call the right AddExternalResultx*/
+	if(nraws==1 && ncols==1){  //scalar result
+		AddExternalResultx(results, type, value[0]);
+	}
+	else if(nraws>1 && ncols==1){  //vector result
+		AddExternalResultx(results, type, value, nraws);
+	}
+	else{
+		_error_("type of result not implemented yet in AddExternalResult");
+	}
+
+	/*write output datasets: */
+	WriteMatlabData(RESULTSOUT,results);
+	
+	/*Free ressources: */
+	delete results;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void AddExternalResultUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [results] = %s(results,type,value);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/AddExternalResult/AddExternalResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/AddExternalResult/AddExternalResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/AddExternalResult/AddExternalResult.h	(revision 11330)
@@ -0,0 +1,33 @@
+/*
+	AddExternalResult.h
+*/
+
+#ifndef _ADDEXTERNALRESULT_H
+#define _ADDEXTERNALRESULT_H
+
+/* local prototypes: */
+void AddExternalResultUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "AddExternalResult"
+
+/* serial input macros: */
+#define RESULTS (mxArray*)prhs[0]
+#define TYPE (mxArray*)prhs[1]
+#define VALUE (mxArray*)prhs[2]
+
+/* serial output macros: */
+#define RESULTSOUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  3
+
+#endif  /* _ADDEXTERNALRESULT_H */
Index: /issm/trunk-jpl-damage/src/mex/AverageFilter/AverageFilter.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/AverageFilter/AverageFilter.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/AverageFilter/AverageFilter.cpp	(revision 11330)
@@ -0,0 +1,62 @@
+/*!\file:  AverageFilter.cpp
+ * \brief fill holes in matlab velocity array
+	this matlab module is an adaptation of a routine written by Robber 
+	Crippen.  The original routine was designed for the SRTM mission at JPL, 
+	and can be found in the current directory, under the name 
+	AverageFilterCrippen.  It fills void holes in an image, using an interpolation 
+	algorithm, and optionnally a smoothing algorithm. 
+	This matlab module extends the Crippen routine to be used in Matlab, 
+	using double arrays found in the workspace, and loaded directly into memory.
+*/
+
+
+#include "./AverageFilter.h"
+
+void mexFunction( int nlhs, mxArray* plhs[],
+				  int nrhs, const mxArray* prhs[])
+{
+
+	int i,j;
+
+	/* required input: */
+	double* imagein=NULL;
+	int     imagein_rows,imagein_cols;
+	int     smooth;
+
+
+	/* output: */
+	mxArray* pfield=NULL;
+	double* imageout=NULL;
+	int     imageout_rows,imageout_cols;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&AverageFilterUsage);
+
+	/*Fetch data: */
+	FetchMatlabData(&imagein,&imagein_rows,&imagein_cols,IMAGEIN);
+	FetchMatlabData(&smooth,SMOOTH);
+	
+	/*Run core hole filler routine: */
+	AverageFilterx( &imageout,imagein,imagein_rows,imagein_cols,smooth);
+
+	/* output: */
+	WriteMatlabData(IMAGEOUT,imageout,imagein_rows,imagein_cols);
+
+	/*end module: */
+	MODULEEND();
+}
+
+
+void AverageFilterUsage(void)
+{
+	printf("   AverageFilter usage:\n");
+	printf("   [image_out]=AverageFilter(image_in,pixels);\n\n");
+	printf("   where:\n");
+	printf("      image_in in double format\n");
+	printf("      pixels: characteristic size of smoothing\n");
+	printf("      image_out in double format\n");
+	printf("\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/AverageFilter/AverageFilter.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/AverageFilter/AverageFilter.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/AverageFilter/AverageFilter.h	(revision 11330)
@@ -0,0 +1,34 @@
+
+/*
+	AverageFilter.h
+*/
+
+
+#ifndef _AVERAGEFILTER_H
+#define _AVERAGEFILTER_H
+
+/* local prototypes: */
+void AverageFilterUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "AverageFilter"
+
+
+/* serial input macros: */
+#define IMAGEIN prhs[0]
+#define SMOOTH prhs[1]
+
+/* serial output macros: */
+#define IMAGEOUT &plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+#endif  /* _AVERAGEFILTER_H */
Index: /issm/trunk-jpl-damage/src/mex/BamgConvertMesh/BamgConvertMesh.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/BamgConvertMesh/BamgConvertMesh.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/BamgConvertMesh/BamgConvertMesh.cpp	(revision 11330)
@@ -0,0 +1,86 @@
+/*\file BamgConvertMesh.c
+ *\brief: bamg module.
+ */
+#include "./BamgConvertMesh.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input: */
+	double* index=NULL;
+	int     index_rows;
+	double* x=NULL;
+	int     x_cols;
+	double* y=NULL;
+	int     y_rows;
+	int     y_cols;
+
+	/*Output*/
+	BamgMesh* bamgmesh=NULL;
+	BamgGeom* bamggeom=NULL;
+	mxArray* bamgmesh_mat=NULL;
+	mxArray* bamggeom_mat=NULL;
+
+	/*Intermediary*/
+	int nods;
+	int nels;
+	int verbose=0;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&BamgConvertMeshUsage);
+
+	/*Initialize Bamg outputs*/
+	bamggeom=new BamgGeom();
+	bamgmesh=new BamgMesh();
+
+	/*Input datasets: */
+	if (verbose) printf("Fetching inputs\n");
+	FetchMatlabData(&index,&nels,&index_rows,INDEXHANDLE);
+	FetchMatlabData(&x,&nods,&x_cols,XHANDLE);
+	FetchMatlabData(&y,&y_rows,&y_cols,YHANDLE);
+
+	/*Check inputs*/
+	if (nels<0){
+		_error_("Number of elements must be positive, check index number of lines");
+	}
+	if (nods<0){
+		_error_("Number of nods must be positive, check x and y sizes");
+	}
+	if (index_rows!=3){
+		_error_("index should have 3 columns");
+	}
+	if (y_rows!=nods){
+		_error_("x and y do not have the same length");
+	}
+	if (x_cols>1 || y_cols>1){
+		_error_("x and y should have only one column");
+	}
+
+	/* Run core computations: */
+	if (verbose) printf("Call core\n");
+	BamgConvertMeshx(bamgmesh,bamggeom,index,x,y,nods,nels);
+
+	/*Generate output Matlab Structures*/
+	bamggeom->SetMatlabStructureFields(BAMGGEOMOUT);
+	bamgmesh->SetMatlabStructureFields(BAMGMESHOUT);
+
+	/*Clean up*/
+	delete bamggeom;
+	delete bamgmesh;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void BamgConvertMeshUsage(void)
+{
+	_printf_(true,"BAMGCONVERTMESH - convert [x y index] to a bamg geom and mesh geom");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"      [bamggeom bamgmesh]=BamgConvertMesh(index,x,y);\n");
+	_printf_(true,"      index: index of the mesh\n");
+	_printf_(true,"      x,y: coordinates of the nodes\n");
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/BamgConvertMesh/BamgConvertMesh.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/BamgConvertMesh/BamgConvertMesh.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/BamgConvertMesh/BamgConvertMesh.h	(revision 11330)
@@ -0,0 +1,34 @@
+/*!\file BamgConvertMesh.h
+ * \brief: prototype for Data Interpolation mex module.
+ */
+
+#ifndef _BAMGCONVERTMESH_H
+#define _BAMGCONVERTMESH_H
+
+/* local prototypes: */
+void BamgConvertMeshUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "BamgConvertMesh"
+
+
+/* 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]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  2
+#undef NRHS
+#define NRHS  3
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/BamgMesher/BamgMesher.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/BamgMesher/BamgMesher.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/BamgMesher/BamgMesher.cpp	(revision 11330)
@@ -0,0 +1,56 @@
+/*\file BamgMesher.c
+ *\brief: mesher that uses the bamg library
+ */
+#include "./BamgMesher.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*Outputs*/
+	mxArray* bamgmesh_mat=NULL;
+	mxArray* bamggeom_mat=NULL;
+
+	/*diverse: */
+	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: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&BamgMesherUsage);
+
+	/*Initialize variables*/
+	bamgopts   = new BamgOpts(BAMGOPTIONS);
+	bamggeom_in= new BamgGeom(BAMGGEOMIN);
+	bamgmesh_in= new BamgMesh(BAMGMESHIN);
+
+	/*Initialize outputs*/
+	bamggeom_out=new BamgGeom();
+	bamgmesh_out=new BamgMesh();
+
+	/*!Generate internal degree of freedom numbers: */
+	Bamgx(bamgmesh_out,bamggeom_out,bamgmesh_in,bamggeom_in,bamgopts);
+
+	/*Generate output Matlab Structures*/
+	bamggeom_out->SetMatlabStructureFields(BAMGGEOMOUT);
+	bamgmesh_out->SetMatlabStructureFields(BAMGMESHOUT);
+
+	/*Free ressources: */
+	delete bamgopts;
+	delete bamggeom_in;
+	delete bamggeom_out;
+	delete bamgmesh_in;
+	delete bamgmesh_out;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void BamgMesherUsage(void){
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [bamgmesh,bamggeom]=%s(bamgmesh,bamggeom,bamgoptions);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/BamgMesher/BamgMesher.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/BamgMesher/BamgMesher.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/BamgMesher/BamgMesher.h	(revision 11330)
@@ -0,0 +1,34 @@
+/*
+	BamgMesherUsage.h
+*/
+
+#ifndef _BAMG_MESHER_H_
+#define _BAMG_MESHER_H_
+
+/* local prototypes: */
+void BamgMesherUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "BamgMesher"
+    
+/* serial input macros: */
+#define BAMGMESHIN  (mxArray*)prhs[0]
+#define BAMGGEOMIN  (mxArray*)prhs[1]
+#define BAMGOPTIONS (mxArray*)prhs[2]
+
+/* serial output macros: */
+#define BAMGMESHOUT    (mxArray**)&plhs[0]
+#define BAMGGEOMOUT    (mxArray**)&plhs[1]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  2
+#undef NRHS
+#define NRHS  3
+
+#endif  /* _BAMG_MESHER_H_ */
+
Index: /issm/trunk-jpl-damage/src/mex/BamgTriangulate/BamgTriangulate.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/BamgTriangulate/BamgTriangulate.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/BamgTriangulate/BamgTriangulate.cpp	(revision 11330)
@@ -0,0 +1,58 @@
+/*\file BamgTriangulate.c
+ *\brief: bamg module.
+ */
+#include "./BamgTriangulate.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*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");
+	FetchMatlabData(&x,&nods,&x_cols,XHANDLE);
+	FetchMatlabData(&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*/
+	WriteMatlabData(INDEX,index,nels,3);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void BamgTriangulateUsage(void)
+{
+	_printf_(true,"BAMGTRIANGULATE - Delaunay Triangulation of a list of points");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"      index=BamgTriangulate(x,y);\n");
+	_printf_(true,"      index: index of the triangulation\n");
+	_printf_(true,"      x,y: coordinates of the nodes\n");
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/BamgTriangulate/BamgTriangulate.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/BamgTriangulate/BamgTriangulate.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/BamgTriangulate/BamgTriangulate.h	(revision 11330)
@@ -0,0 +1,32 @@
+/*!\file BamgTriangulate.h
+ * \brief: prototype for Data Interpolation mex module.
+ */
+
+#ifndef _BAMGTRIANGULATE_H
+#define _BAMGTRIANGULATE_H
+
+/* local prototypes: */
+void BamgTriangulateUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "BamgTriangulate"
+
+
+/* serial input macros: */
+#define XHANDLE prhs[0]
+#define YHANDLE prhs[1]
+
+/* serial output macros: */
+#define INDEX (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/Chaco/Chaco.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Chaco/Chaco.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Chaco/Chaco.cpp	(revision 11330)
@@ -0,0 +1,146 @@
+/*\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 mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+   
+	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=(int*)xmalloc(nvtxs*sizeof(int));
+	for (i=0; i<nvtxs+1;i++)start[i]=(int)mwstart[i];
+
+	mwadjacency = mxGetIr(A_IN);
+	adjacency = (int*)xmalloc(mxGetNzmax(A_IN)*sizeof(int));
+	for (i=0; i<mxGetNzmax(A_IN); i++) adjacency[i]= (int)mwadjacency[i];
+
+	nedges = start[nvtxs];
+	if(!mxIsEmpty(EWGTS_IN)){
+		ewgts = (float *) xcalloc(nedges, sizeof(float));
+		doublepointer=mxGetPr(A_IN);
+		for (i = 0; i < nedges; i++)ewgts[i] = (float)doublepointer[i];
+	}
+	else ewgts=NULL;
+
+	/*Fetch rest of data: */
+	FetchMatlabData(&vwgts,&nterms,VWGTS_IN); 
+
+	FetchMatlabData(&x,&nterms,X_IN); 
+	FetchMatlabData(&y,&nterms,Y_IN); 
+	FetchMatlabData(&z,&nterms,Z_IN); 
+	
+	FetchMatlabData(&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
+	
+	FetchMatlabData(&npart,NPARTS_IN); 
+	nparts=(int*)xmalloc(sizeof(int)); nparts[0]=npart; //weird Chacox interface ain't it?
+
+	FetchMatlabData(&goal,&nterms,GOAL_IN); 
+	
+	/*Some debugging print: {{{*/
+	#ifdef _DEBUG_
+	printf("nvtxs: %i\n",nvtxs);
+	printf("options: [");
+	for(i=0;i<10;i++)printf("%g|",options[i]);
+	printf("]\n");
+	printf("start: \n");
+	for (i=0; i<nvtxs+1;i++)printf("%i ",start[i]);
+	printf("\n");
+	printf("adjacency: \n");
+	for (i=0; i<mxGetNzmax(A_IN);i++)printf("%i ",adjacency[i]);
+	printf("\n");
+	printf("nedges: %i %p\n",nedges,ewgts);
+	if(ewgts) for (i = 0; i < nedges; i++)printf("%g ",ewgts[i]);
+	printf("\n");
+	printf("vwgts:\n");
+	for (i = 0; i < nvtxs; i++)printf("%g ",vwgts[i]);
+	printf("\n");
+	printf("nparts: %i\n",nparts[0]);
+	printf("goal: %p\n",goal);
+	#endif
+	/*}}}*/
+	
+	/*Allocate output: */
+	assignment = (short *) xcalloc(nvtxs, sizeof(short));
+	
+    /*Call core: */
+	Chacox(nvtxs, start, adjacency, vwgts, ewgts, x, y, z, assignment, options, nparts, goal);
+
+    /*Output data: */
+	doubleassignment=(double*)xmalloc(nvtxs*sizeof(double));
+	for (i=0;i<nvtxs;i++) doubleassignment[i]=(double)assignment[i];
+	WriteMatlabData(ASSGN_OUT,doubleassignment,nvtxs);
+
+	/*Free ressources:*/
+	xfree((void**)&assignment); 
+	xfree((void**)&goal);
+	xfree((void**)&nparts);
+	xfree((void**)&z);
+	xfree((void**)&y);
+	xfree((void**)&x);
+	xfree((void**)&ewgts);
+	xfree((void**)&vwgts);
+	xfree((void**)&adjacency);
+	xfree((void**)&start);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ChacoUsage( void )
+{
+	_printf_(true,"\n");
+	_printf_(true,"Usage: [assgn] = Chaco(A,vwgts,ewgts,x,y,z,options,nparts,goal);\n");
+	_printf_(true,"\n");
+}
+
Index: /issm/trunk-jpl-damage/src/mex/Chaco/Chaco.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Chaco/Chaco.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Chaco/Chaco.h	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file:  Chaco.h
+ * \brief header file for Chaco module.
+ */ 
+
+#ifndef _CHACO_H
+#define _CHACO_H
+
+/* local prototypes: */
+void ChacoUsage(void);
+
+#include <stdio.h>
+#include <string.h>    /*  strcasecmp  */
+#include <time.h>      /*  clock,time,difftime  */
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+    
+/* serial input macros: */
+#define A_IN (mxArray*)prhs[0]
+#define VWGTS_IN (mxArray*)prhs[1]
+#define EWGTS_IN (mxArray*)prhs[2]
+#define X_IN (mxArray*)prhs[3]
+#define Y_IN (mxArray*)prhs[4]
+#define Z_IN (mxArray*)prhs[5]
+#define OPTNS_IN (mxArray*)prhs[6]
+#define NPARTS_IN (mxArray*)prhs[7]
+#define GOAL_IN (mxArray*)prhs[8]
+
+/* serial output macros: */
+#define ASSGN_OUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  9
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Chaco"
+
+#endif  /* _CHACO_H */
Index: /issm/trunk-jpl-damage/src/mex/ComputeBasalStress/ComputeBasalStress.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ComputeBasalStress/ComputeBasalStress.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ComputeBasalStress/ComputeBasalStress.cpp	(revision 11330)
@@ -0,0 +1,63 @@
+/*\file ComputeBasalStress.c
+ *\brief: recover pressure from elements
+ */
+
+#include "./ComputeBasalStress.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL; 
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+	int      numberofnodes;
+
+	/* output datasets: */
+	Vec sigma_g=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ComputeBasalStressUsage);
+        
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Generate internal degree of freedom numbers: */
+	ComputeBasalStressx(&sigma_g, elements,nodes,vertices,loads,materials,parameters);
+
+	/*write output datasets: */
+	WriteMatlabData(SIGMA,sigma_g);
+
+	/*Free ressources: */
+	delete nodes;
+	delete vertices;
+	delete elements;
+	delete materials;
+	delete loads;
+	delete parameters;
+	VecFree(&sigma_g);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ComputeBasalStressUsage(void) {
+	printf("\n");
+	printf("   usage: [p_g] = %s(elements, nodes, vertices, loads, materials, params);\n",__FUNCT__);
+	printf("\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ComputeBasalStress/ComputeBasalStress.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ComputeBasalStress/ComputeBasalStress.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ComputeBasalStress/ComputeBasalStress.h	(revision 11330)
@@ -0,0 +1,36 @@
+/*
+	ComputeBasalStress.h
+*/
+
+#ifndef _COMPUTEBASALSTRESS_H
+#define _COMPUTEBASALSTRESS_H
+
+/* local prototypes: */
+void ComputeBasalStressUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ComputeBasalStress"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADS (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+
+/* serial output macros: */
+#define SIGMA (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  6
+
+#endif  /* _COMPUTEPRESSURE_H */
+
Index: /issm/trunk-jpl-damage/src/mex/ConfigureObjects/ConfigureObjects.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ConfigureObjects/ConfigureObjects.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ConfigureObjects/ConfigureObjects.cpp	(revision 11330)
@@ -0,0 +1,59 @@
+/*\file ConfigureObjects.c
+ *\brief: configure objects (elements, loads for example), that need linking with nodes
+ */
+
+#include "./ConfigureObjects.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Loads* loads=NULL;
+	Nodes* nodes=NULL;
+	Vertices* vertices=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+
+	/* output datasets: elements and loads*/
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ConfigureObjectsUsage);
+	
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+	FetchMatlabData((DataSet**)&loads,LOADSIN);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*!Configure objects:*/
+	ConfigureObjectsx(elements, loads, nodes, vertices,materials,parameters);
+
+	/*write output datasets: */
+	WriteMatlabData(ELEMENTS,elements);
+	WriteMatlabData(LOADS,loads);
+	WriteMatlabData(NODESOUT,nodes);
+	WriteMatlabData(PARAMETERSOUT,parameters);
+
+	/*Free ressources: */
+	delete elements;
+	delete loads;
+	delete nodes;
+	delete vertices;
+	delete materials;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ConfigureObjectsUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements,loads, nodes,parameters] = %s(elements,loads,nodes, materials,parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ConfigureObjects/ConfigureObjects.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ConfigureObjects/ConfigureObjects.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ConfigureObjects/ConfigureObjects.h	(revision 11330)
@@ -0,0 +1,42 @@
+
+/*
+	ConfigureObjects.h
+*/
+
+
+#ifndef _CONFIGUREOBJECTS_H
+#define _CONFIGUREOBJECTS_H
+
+/* local prototypes: */
+void ConfigureObjectsUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ConfigureObjects"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define LOADSIN (mxArray*)prhs[1]
+#define NODES (mxArray*)prhs[2]
+#define VERTICES (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+
+/* serial output macros: */
+#define ELEMENTS (mxArray**)&plhs[0]
+#define LOADS (mxArray**)&plhs[1]
+#define NODESOUT (mxArray**)&plhs[2]
+#define PARAMETERSOUT (mxArray**)&plhs[3]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  4
+#undef NRHS
+#define NRHS  6
+
+
+#endif  /* _CONFIGUREOBJECTS_H */
+
Index: /issm/trunk-jpl-damage/src/mex/ConstraintsState/ConstraintsState.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ConstraintsState/ConstraintsState.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ConstraintsState/ConstraintsState.cpp	(revision 11330)
@@ -0,0 +1,65 @@
+/*\file ConstraintsState.c
+ *\brief: set up penalty constraints
+ */
+
+#include "./ConstraintsState.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL;
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+
+	/*output: */
+	int converged;
+	int num_unstable_constraints;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ConstraintsStateUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADSIN);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Generate internal degree of freedom numbers: */
+	ConstraintsStatex(&converged, &num_unstable_constraints, elements,nodes,vertices, loads,materials,parameters);
+
+	/*write output datasets: */
+	WriteMatlabData(LOADS,loads);
+	WriteMatlabData(CONVERGED,converged);
+	WriteMatlabData(NUMUNSTABLECONSTRAINTS,num_unstable_constraints);
+	
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ConstraintsStateUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [loads, constraints_converged, num_unstable_constraints] = %s(elements,nodes,vertices,loads,materials,params);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ConstraintsState/ConstraintsState.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ConstraintsState/ConstraintsState.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ConstraintsState/ConstraintsState.h	(revision 11330)
@@ -0,0 +1,37 @@
+/*
+	ConstraintsState.h
+*/
+
+#ifndef _CONSTRAINTSSTATE_H
+#define _CONSTRAINTSSTATE_H
+
+/* local prototypes: */
+void ConstraintsStateUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ConstraintsState"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+
+/* serial output macros: */
+#define LOADS (mxArray**)&plhs[0]
+#define CONVERGED (mxArray**)&plhs[1]
+#define NUMUNSTABLECONSTRAINTS (mxArray**)&plhs[2]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  3
+#undef NRHS
+#define NRHS  6
+
+#endif  /* _CONSTRAINTSSTATE_H */
Index: /issm/trunk-jpl-damage/src/mex/ContourToMesh/ContourToMesh.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ContourToMesh/ContourToMesh.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ContourToMesh/ContourToMesh.cpp	(revision 11330)
@@ -0,0 +1,135 @@
+/*! \file  ContourtoMesh
+    \brief: takes an  contour file, and figures out which nodes or elements from the mesh  
+    are inside this contour. 
+	usage:
+	[in_nod,in_elem]=ContourToMesh(index,x,y,contours,interptype,edgevalue);
+	
+	input:
+
+		index,x,y: delaunay triangulation.
+		contours: structure holding sets of vertices making open contours. 
+		interptype: string definining type of interpolation ('element', or 'node', or 'element and node');
+		edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons
+
+	output:
+		in_nod: vector of flags (0 or 1), of size nods if interptype is set to 'node' or 'element and node', 
+				or of size 0 otherwise.
+		in_elem: vector of flags (0 or 1), of size nel if interptype is set to 'element' or 'element and node', 
+				or of size 0 otherwise.
+*/
+	
+#include "./ContourToMesh.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+
+	int i,j;
+
+	/* required input: */
+	double* index=NULL;
+	double* x=NULL;
+	double* y=NULL;
+	int     edgevalue;
+	char*   interptype=NULL;
+
+	/* output: */
+	Vec  in_nod=NULL;
+	int  nods;
+	Vec  in_elem=NULL;
+	int  nel;
+
+	//contours
+	mxArray*  matlabstructure=NULL;
+	int numcontours;
+	Contour** contours=NULL;
+	Contour*  contouri=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	//CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ContourToMeshUsage); Cant' use it here, as we have variable  outputs.
+	if((nlhs!=1 && nlhs!=2) || (nrhs!=NRHS)){
+		ContourToMeshUsage();
+		_error_(" usage. See above");
+	}
+
+	/*First, call expread on filename to build a contour array in the matlab workspace: */
+	mexCallMATLAB( 1, &matlabstructure, 1, (mxArray**)&FILENAME, "expread");
+
+	/*Fetch inputs: */
+	FetchMatlabData(&index,&nel,NULL,INDEXHANDLE);
+	FetchMatlabData(&x,&nods,NULL,XHANDLE);
+	FetchMatlabData(&y,NULL,NULL,YHANDLE);
+	FetchMatlabData(&edgevalue,EDGEVALUEHANDLE);
+
+	//Fetch contours
+	numcontours=mxGetNumberOfElements(matlabstructure);
+	contours=(Contour**)xmalloc(numcontours*sizeof(Contour*));
+	for(i=0;i<numcontours;i++){
+		//allocate
+		contouri=(Contour*)xmalloc(sizeof(Contour));
+		//retrieve dimension of this contour.
+		contouri->nods=(int)mxGetScalar(mxGetField(matlabstructure,i,"nods"));
+		//set pointers.
+		contouri->x=mxGetPr(mxGetField(matlabstructure,i,"x"));
+		contouri->y=mxGetPr(mxGetField(matlabstructure,i,"y"));
+		*(contours+i)=contouri;
+	}
+
+	/*Fetch  interptype: */
+	FetchMatlabData(&interptype,INTERPTYPEHANDLE);
+
+	/* Debugging of contours :{{{1*/
+	/*for(i=0;i<numcontours;i++){
+		printf("\nContour echo: contour number  %i / %i\n",i+1,numcontours);
+		contouri=*(contours+i);
+		printf("   Number of vertices %i\n",contouri->nods);
+		for (j=0;j<contouri->nods;j++){
+			printf("   %lf %lf\n",*(contouri->x+j),*(contouri->y+j));
+		}
+	}*/
+	/*}}}*/
+
+	/*Run interpolation routine: */
+	ContourToMeshx( &in_nod,&in_elem,index,x,y,contours,numcontours,interptype,nel,nods,edgevalue);
+
+	/* output: */
+	if (strcmp(interptype,"node")==0){
+		WriteMatlabData(PLHS0,in_nod);
+	}
+	else if (strcmp(interptype,"element")==0){
+		WriteMatlabData(PLHS0,in_elem);
+	}
+	else if (strcmp(interptype,"element and node")==0){
+		WriteMatlabData(PLHS0,in_nod);
+		WriteMatlabData(PLHS1,in_elem);
+	}
+	else _error_(" wrong interpolation type");
+
+	/*end module: */
+	MODULEEND();
+	
+}
+
+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\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");
+}
Index: /issm/trunk-jpl-damage/src/mex/ContourToMesh/ContourToMesh.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ContourToMesh/ContourToMesh.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ContourToMesh/ContourToMesh.h	(revision 11330)
@@ -0,0 +1,45 @@
+
+/*
+	ContourToMesh.h
+*/
+
+
+#ifndef _CONTOURTOMESH_H
+#define _CONTOURTOMESH_H
+
+/* local prototypes: */
+void ContourToMeshUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__
+#define __FUNCT__ "ContourToMesh"
+
+
+#ifndef ALL
+#define ALL 0
+#endif
+
+/* input macros: */
+#define INDEXHANDLE prhs[0]
+#define XHANDLE prhs[1]
+#define YHANDLE prhs[2]
+#define FILENAME prhs[3]
+#define INTERPTYPEHANDLE prhs[4]
+#define EDGEVALUEHANDLE prhs[5]
+
+/* serial output macros: */
+#define PLHS0 (mxArray**)&plhs[0]
+#define PLHS1 (mxArray**)&plhs[1]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  2
+#undef NRHS
+#define NRHS 6
+
+
+#endif  /* _CONTOURTOMESH_H */
+
Index: /issm/trunk-jpl-damage/src/mex/ContourToNodes/ContourToNodes.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ContourToNodes/ContourToNodes.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ContourToNodes/ContourToNodes.cpp	(revision 11330)
@@ -0,0 +1,114 @@
+/*! \file  ContourtoNodes
+    \brief: takes a  contour file, and figures out which nodes  (x,y list)
+    are inside this contour. 
+
+	usage:
+	[flags]=ContourToNodes(x,y,contours,interptype,edgevalue);
+	
+	where:
+
+	input:
+
+		x,y: node cooredinates
+		
+		contours: structure holding sets of vertices making open contours. 
+		
+		interptype: string definining type of interpolation ('element', or 'node', or 'element and node');
+
+		edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons
+
+	output:
+		flags: vector of flags (0 or 1), of size nods 
+*/
+	
+#include "./ContourToNodes.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+
+	int i,j;
+
+	/* required input: */
+	double* x=NULL;
+	double* y=NULL;
+	int     edgevalue;
+	char*   interptype=NULL;
+
+	/* output: */
+	Vec  flags=NULL;
+	int  nods;
+
+	//contours
+	mxArray*  matlabstructure=NULL;
+	int numcontours;
+	Contour** contours=NULL;
+	Contour*  contouri=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ContourToNodesUsage);
+
+	
+	/*Fetch inputs: */
+	FetchMatlabData(&x,&nods,NULL,XHANDLE);
+	FetchMatlabData(&y,NULL,NULL,YHANDLE);
+	FetchMatlabData(&edgevalue,EDGEVALUEHANDLE);
+
+	//Fetch contours
+
+	if(mxIsChar(FILENAME)){
+		/*Call expread on filename to build a contour array in the matlab workspace: */
+		mexCallMATLAB( 1, &matlabstructure, 1, (mxArray**)&FILENAME, "expread");
+	}
+	else{
+		/*FILENAME is actually a structure, coming directly from expread: */
+		matlabstructure=(mxArray*)FILENAME;
+	}
+
+	numcontours=mxGetNumberOfElements(matlabstructure);
+	contours=(Contour**)xmalloc(numcontours*sizeof(Contour*));
+	for(i=0;i<numcontours;i++){
+		//allocate
+		contouri=(Contour*)xmalloc(sizeof(Contour));
+		//retrieve dimension of this contour.
+		contouri->nods=(int)mxGetScalar(mxGetField(matlabstructure,i,"nods"));
+		//set pointers.
+		contouri->x=mxGetPr(mxGetField(matlabstructure,i,"x"));
+		contouri->y=mxGetPr(mxGetField(matlabstructure,i,"y"));
+		*(contours+i)=contouri;
+	}
+
+	/* Debugging of contours :{{{1*/
+	/*for(i=0;i<numcontours;i++){
+		printf("\nContour echo: contour number  %i / %i\n",i+1,numcontours);
+		contouri=*(contours+i);
+		printf("   Number of nodes %i\n",contouri->nods);
+		for (j=0;j<contouri->nods;j++){
+			printf("   %lf %lf\n",*(contouri->x+j),*(contouri->y+j));
+		}
+	}*/
+	/*}}}*/
+
+	/*Run interpolation routine: */
+	ContourToNodesx(&flags,x,y,nods,contours,numcontours,edgevalue);
+
+	/* output: */
+	WriteMatlabData(FLAGS,flags);
+
+	/*end module: */
+	MODULEEND();
+
+}
+
+void ContourToNodesUsage(void){
+	printf("   usage:\n");
+	printf("   [flags]=ContourToNodes(x,y,contourname,edgevalue);\n\n");
+	printf("   where:\n");
+	printf("      x,y: list of nodes.\n");
+	printf("      contourname: name of .exp file containing the contours, or resulting structure from call to expread.\n");
+	printf("      interptype: string definining type of interpolation ('element', or 'node').\n");
+	printf("      edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons.\n");
+	printf("      flags: vector of flags (0 or 1), of size nods.\n");
+	printf("\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ContourToNodes/ContourToNodes.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ContourToNodes/ContourToNodes.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ContourToNodes/ContourToNodes.h	(revision 11330)
@@ -0,0 +1,42 @@
+
+/*
+	ContourToNodes.h
+*/
+
+
+#ifndef _CONTOURTONODES_H
+#define _CONTOURTONODES_H
+
+/* local prototypes: */
+void ContourToNodesUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__
+#define __FUNCT__ "ContourToNodes"
+
+
+#ifndef ALL
+#define ALL 0
+#endif
+
+/* input macros: */
+#define XHANDLE prhs[0]
+#define YHANDLE prhs[1]
+#define FILENAME prhs[2]
+#define EDGEVALUEHANDLE prhs[3]
+
+/* serial output macros: */
+#define FLAGS (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS 1
+#undef NRHS
+#define NRHS 4
+
+
+#endif  /* _CONTOURTONODES_H */
+
Index: /issm/trunk-jpl-damage/src/mex/ControlInputGetGradient/ControlInputGetGradient.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ControlInputGetGradient/ControlInputGetGradient.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ControlInputGetGradient/ControlInputGetGradient.cpp	(revision 11330)
@@ -0,0 +1,65 @@
+/*\file ControlInputGetGradient.c
+ *\brief: recover velocity ug from inputs
+ */
+
+#include "./ControlInputGetGradient.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements   *elements   = NULL;
+	Nodes      *nodes      = NULL;
+	Vertices   *vertices   = NULL;
+	Loads      *loads      = NULL;
+	Materials  *materials  = NULL;
+	Parameters *parameters = NULL;
+	int         control_type;
+	Vec         gradient   = NULL;
+
+	/* output datasets: elements and loads*/
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ControlInputGetGradientUsage);
+	
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADSIN);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+	FetchMatlabData(&control_type,CONTROLTYPE);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+	materials-> Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!core code:*/
+	ControlInputGetGradientx(&gradient,elements, nodes,vertices,loads, materials,parameters,control_type);
+
+	/*write output datasets: */
+	WriteMatlabData(GRADIENT,gradient);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ControlInputGetGradientUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [gradient] = %s(elements,nodes,vertices,loads, materials,parameters,control_type);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ControlInputGetGradient/ControlInputGetGradient.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ControlInputGetGradient/ControlInputGetGradient.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ControlInputGetGradient/ControlInputGetGradient.h	(revision 11330)
@@ -0,0 +1,36 @@
+/*
+	ControlInputGetGradient.h
+*/
+
+#ifndef _CONTROLINPUTGETGRADIENT_H
+#define _CONTROLINPUTGETGRADIENT_H
+
+/* local prototypes: */
+void ControlInputGetGradientUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ControlInputGetGradient"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+#define CONTROLTYPE (mxArray*)prhs[6]
+
+/* serial output macros: */
+#define GRADIENT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  7
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/ControlInputScaleGradient/ControlInputScaleGradient.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ControlInputScaleGradient/ControlInputScaleGradient.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ControlInputScaleGradient/ControlInputScaleGradient.cpp	(revision 11330)
@@ -0,0 +1,68 @@
+/*\file ControlInputScaleGradient.c
+*\brief: update elements properties using an input  vector
+*/
+
+#include "./ControlInputScaleGradient.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+/*input datasets: */
+Elements   *elements   = NULL;
+Nodes      *nodes      = NULL;
+Vertices   *vertices   = NULL;
+Loads      *loads      = NULL;
+Materials  *materials  = NULL;
+Parameters *parameters = NULL;
+int         control_type;
+double      scaling_factor;
+
+/*Boot module: */
+MODULEBOOT();
+
+/*checks on arguments on the matlab side: */
+CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ControlInputScaleGradientUsage);
+
+/*Input datasets: */
+FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+FetchMatlabData((DataSet**)&nodes,NODESIN);
+FetchMatlabData((DataSet**)&vertices,VERTICESIN);
+FetchMatlabData((DataSet**)&loads,LOADSIN);
+FetchMatlabData((DataSet**)&materials,MATERIALSIN);
+FetchMatlabData(&parameters,PARAMETERSIN);
+FetchMatlabData(&control_type,CONTROLTYPE);
+FetchMatlabData(&scaling_factor,SCALE);
+
+/*configure: */
+elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+/*call "x" code layer*/
+ControlInputScaleGradientx(elements,nodes,vertices,loads, materials,parameters,control_type,scaling_factor);
+
+/*write output datasets: */
+WriteMatlabData(ELEMENTS,elements);
+WriteMatlabData(NODES,nodes);
+WriteMatlabData(VERTICES,vertices);
+WriteMatlabData(LOADS,loads);
+WriteMatlabData(MATERIALS,materials);
+WriteMatlabData(PARAMETERS,parameters);
+
+/*Free ressources: */
+delete elements;
+delete nodes;
+delete vertices;
+delete loads;
+delete materials;
+delete parameters;
+
+/*end module: */
+MODULEEND();
+}
+
+void ControlInputScaleGradientUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements,nodes,vertices,loads,materials,parameters] = %s(elements,nodes,vertices,loads,materials,control_type,scaling_factor);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ControlInputScaleGradient/ControlInputScaleGradient.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ControlInputScaleGradient/ControlInputScaleGradient.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ControlInputScaleGradient/ControlInputScaleGradient.h	(revision 11330)
@@ -0,0 +1,43 @@
+/*
+	ControlInputScaleGradient.h
+*/
+
+#ifndef _CONTROLINPUTSCALEGRADIENT_H
+#define _CONTROLINPUTSCALEGRADIENT_H
+
+/* local prototypes: */
+void ControlInputScaleGradientUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ControlInputScaleGradient"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODESIN (mxArray*)prhs[1]
+#define VERTICESIN (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALSIN (mxArray*)prhs[4]
+#define PARAMETERSIN (mxArray*)prhs[5]
+#define CONTROLTYPE (mxArray*)prhs[6]
+#define SCALE (mxArray*)prhs[7]
+
+/* serial output macros: */
+#define ELEMENTS (mxArray**)&plhs[0]
+#define NODES (mxArray**)&plhs[1]
+#define VERTICES (mxArray**)&plhs[2]
+#define LOADS (mxArray**)&plhs[3]
+#define MATERIALS (mxArray**)&plhs[4]
+#define PARAMETERS (mxArray**)&plhs[5]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  6
+#undef NRHS
+#define NRHS  8
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/ControlInputSetGradient/ControlInputSetGradient.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ControlInputSetGradient/ControlInputSetGradient.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ControlInputSetGradient/ControlInputSetGradient.cpp	(revision 11330)
@@ -0,0 +1,68 @@
+/*\file ControlInputSetGradient.c
+*\brief: update elements properties using an input  vector
+*/
+
+#include "./ControlInputSetGradient.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+/*input datasets: */
+Elements   *elements   = NULL;
+Nodes      *nodes      = NULL;
+Vertices   *vertices   = NULL;
+Loads      *loads      = NULL;
+Materials  *materials  = NULL;
+Parameters *parameters = NULL;
+int         control_type;
+double     *gradient   = NULL;
+
+/*Boot module: */
+MODULEBOOT();
+
+/*checks on arguments on the matlab side: */
+CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ControlInputSetGradientUsage);
+
+/*Input datasets: */
+FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+FetchMatlabData((DataSet**)&nodes,NODESIN);
+FetchMatlabData((DataSet**)&vertices,VERTICESIN);
+FetchMatlabData((DataSet**)&loads,LOADSIN);
+FetchMatlabData((DataSet**)&materials,MATERIALSIN);
+FetchMatlabData(&parameters,PARAMETERSIN);
+FetchMatlabData(&control_type,CONTROLTYPE);
+FetchMatlabData(&gradient,NULL,GRADIENT);
+
+/*configure: */
+elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+/*call "x" code layer*/
+ControlInputSetGradientx(elements,nodes,vertices,loads, materials,parameters,control_type,gradient);
+
+/*write output datasets: */
+WriteMatlabData(ELEMENTS,elements);
+WriteMatlabData(NODES,nodes);
+WriteMatlabData(VERTICES,vertices);
+WriteMatlabData(LOADS,loads);
+WriteMatlabData(MATERIALS,materials);
+WriteMatlabData(PARAMETERS,parameters);
+
+/*Free ressources: */
+delete elements;
+delete nodes;
+delete vertices;
+delete loads;
+delete materials;
+delete parameters;
+
+/*end module: */
+MODULEEND();
+}
+
+void ControlInputSetGradientUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements,nodes,vertices,loads,materials,parameters] = %s(elements,nodes,vertices,loads,materials,control_type,gradient);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ControlInputSetGradient/ControlInputSetGradient.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ControlInputSetGradient/ControlInputSetGradient.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ControlInputSetGradient/ControlInputSetGradient.h	(revision 11330)
@@ -0,0 +1,43 @@
+/*
+	ControlInputSetGradient.h
+*/
+
+#ifndef _CONTROLINPUTSETGRADIENT_H
+#define _CONTROLINPUTSETGRADIENT_H
+
+/* local prototypes: */
+void ControlInputSetGradientUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ControlInputSetGradient"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODESIN (mxArray*)prhs[1]
+#define VERTICESIN (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALSIN (mxArray*)prhs[4]
+#define PARAMETERSIN (mxArray*)prhs[5]
+#define CONTROLTYPE (mxArray*)prhs[6]
+#define GRADIENT (mxArray*)prhs[7]
+
+/* serial output macros: */
+#define ELEMENTS (mxArray**)&plhs[0]
+#define NODES (mxArray**)&plhs[1]
+#define VERTICES (mxArray**)&plhs[2]
+#define LOADS (mxArray**)&plhs[3]
+#define MATERIALS (mxArray**)&plhs[4]
+#define PARAMETERS (mxArray**)&plhs[5]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  6
+#undef NRHS
+#define NRHS  8
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/ControlOptimization/ControlOptimization.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ControlOptimization/ControlOptimization.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ControlOptimization/ControlOptimization.cpp	(revision 11330)
@@ -0,0 +1,68 @@
+/*\file ControlOptimization.c
+ *\brief: control optimization (replaces fmincon from matlab)
+ */
+
+#include "./ControlOptimization.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	char* function_name=NULL;
+	double xmin,xmax;
+	double* maxiter;
+	OptArgs optargs;
+	OptPars optpars;
+
+	/*output: */
+	double search_scalar;
+	double J;
+
+	/*arguments to objectivefunctionC: */
+	int      n_value;
+	double*  threshold=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ControlOptimizationUsage);
+
+	/*Input datasets: */
+	FetchMatlabData(&function_name,FUNCTIONNAME);
+	FetchMatlabData(&xmin,XMIN);
+	FetchMatlabData(&xmax,XMAX);
+
+	/*Parameters: */
+	FetchMatlabData(&maxiter,NULL,NULL,mxGetField(OPTIONS,0,"MaxIter"));
+	FetchMatlabData(&threshold,NULL,NULL,mxGetField(PARAMETERS,0,"InversionStepThreshold"));
+	FetchMatlabData(&n_value,STEP);
+
+	optargs.function_name=function_name;
+	optargs.femmodel=FEMMODEL;
+
+	optpars.xmin=xmin;
+	optpars.xmax=xmax;
+	optpars.maxiter=(int)maxiter[n_value-1];
+	optpars.cm_jump=threshold[n_value-1];
+
+	BrentSearch(&search_scalar,&J,&optpars,&OptFunc,&optargs);
+
+	/*write output : */
+	WriteMatlabData(SEARCHSCALAR,search_scalar);
+	WriteMatlabData(MISFIT,J);
+
+	/*Free ressources: */
+	xfree((void**)&function_name);
+	xfree((void**)&threshold);
+	xfree((void**)&maxiter);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ControlOptimizationUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [search_scalar J] = %s(function_name,xmin,xmax,options,femmodel,step,parameters)\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ControlOptimization/ControlOptimization.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ControlOptimization/ControlOptimization.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ControlOptimization/ControlOptimization.h	(revision 11330)
@@ -0,0 +1,37 @@
+/*
+	ControlOptimization.h
+*/
+
+#ifndef _CONTROLOPTIMIZATION_H
+#define _CONTROLOPTIMIZATION_H
+
+/* local prototypes: */
+void ControlOptimizationUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ControlOptimization"
+
+/* serial input macros: */
+#define FUNCTIONNAME (mxArray*)prhs[0]
+#define XMIN (mxArray*)prhs[1]
+#define XMAX (mxArray*)prhs[2]
+#define OPTIONS (mxArray*)prhs[3]
+#define FEMMODEL (mxArray*)prhs[4]
+#define STEP (mxArray*)prhs[5]
+#define PARAMETERS (mxArray*)prhs[6]
+
+/* serial output macros: */
+#define SEARCHSCALAR (mxArray**)&plhs[0]
+#define MISFIT (mxArray**)&plhs[1]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  2
+#undef NRHS
+#define NRHS  7 
+
+#endif  /* _CONTROLOPTIMIZATION_H */
Index: /issm/trunk-jpl-damage/src/mex/CostFunction/CostFunction.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/CostFunction/CostFunction.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/CostFunction/CostFunction.cpp	(revision 11330)
@@ -0,0 +1,62 @@
+/*\file CostFunction.c
+ *\brief: compute misfit between modeled velocity and observed velocity
+ */
+
+#include "./CostFunction.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements   *elements   = NULL;
+	Loads      *loads      = NULL;
+	Nodes      *nodes      = NULL;
+	Vertices   *vertices   = NULL;
+	Materials  *materials  = NULL;
+	Parameters *parameters = NULL;
+
+	/* output datasets: */
+	double J;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&CostFunctionUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Call core code: */
+	CostFunctionx(&J, elements,nodes,vertices, loads,materials,parameters);
+
+	/*write output : */
+	WriteMatlabData(COST,J);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void CostFunctionUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [J] = %s(elements,nodes,vertices,loads, materials, parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/CostFunction/CostFunction.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/CostFunction/CostFunction.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/CostFunction/CostFunction.h	(revision 11330)
@@ -0,0 +1,38 @@
+/*
+	CostFunction.h
+*/
+
+#ifndef _COSTFUNCTION_H
+#define _COSTFUNCTION_H
+
+/* local prototypes: */
+void CostFunctionUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "CostFunction"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADS (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+
+/* serial output macros: */
+#define COST (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  6
+
+#endif  /* _COSTFUNCTION_H */
+
+
+
Index: /issm/trunk-jpl-damage/src/mex/CreateNodalConstraints/CreateNodalConstraints.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/CreateNodalConstraints/CreateNodalConstraints.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/CreateNodalConstraints/CreateNodalConstraints.cpp	(revision 11330)
@@ -0,0 +1,45 @@
+/*\file CreateNodalConstraints.c
+ *\brief: reduce g set vector to s set vector (set of single point constraints)
+ */
+
+#include "./CreateNodalConstraints.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Nodes *nodes         = NULL;
+	int    analysis_type;
+
+	/* output datasets: */
+	Vec ys=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&CreateNodalConstraintsUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData(&analysis_type,ANALYSISTYPE);
+
+	/*!Reduce vector: */
+	CreateNodalConstraintsx(&ys,nodes,analysis_type);
+
+	/*write output datasets: */
+	WriteMatlabData(YS,ys);
+
+	/*Free ressources: */
+	delete nodes;
+	VecFree(&ys);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void CreateNodalConstraintsUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: ys = %s(nodes,analysis_type);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/CreateNodalConstraints/CreateNodalConstraints.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/CreateNodalConstraints/CreateNodalConstraints.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/CreateNodalConstraints/CreateNodalConstraints.h	(revision 11330)
@@ -0,0 +1,31 @@
+/*
+	CreateNodalConstraints.h
+*/
+
+#ifndef _CREATENODALCONSTRAINTS_H
+#define _CREATENODALCONSTRAINTS_H
+
+/* local prototypes: */
+void CreateNodalConstraintsUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "CreateNodalConstraints"
+
+/* serial input macros: */
+#define NODES (mxArray*)prhs[0]
+#define ANALYSISTYPE (mxArray*)prhs[1]
+
+/* serial output macros: */
+#define YS (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+#endif  /* _REDUCEVECTORGTOF_H */
Index: /issm/trunk-jpl-damage/src/mex/Dakota/Dakota.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Dakota/Dakota.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Dakota/Dakota.cpp	(revision 11330)
@@ -0,0 +1,46 @@
+/*\file Dakota.c
+ *\brief: launch solution core using Dakota engine.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Dakota.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	mxArray    *femmodel   = NULL;
+
+	/* output datasets: none*/
+
+	#ifndef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+	_error_(" Dakota not available! Cannot carry out qmu analysis!");
+	#endif
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&DakotaUsage);
+
+	/*Input datasets: */
+	femmodel=FEMMODEL;
+
+	/*!Generate internal degree of freedom numbers: */
+	Dakotax(femmodel);
+
+	/*end module: */
+	MODULEEND();
+
+
+}
+
+void DakotaUsage(void){
+	_printf_(true,"\n");
+	_printf_(true,"   usage: %s(femmodel);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/Dakota/Dakota.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Dakota/Dakota.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Dakota/Dakota.h	(revision 11330)
@@ -0,0 +1,33 @@
+
+/*
+	Dakota.h
+*/
+
+
+#ifndef _DAKOTA_H
+#define _DAKOTA_H
+
+/* local prototypes: */
+void DakotaUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Dakota"
+
+/* serial input macros: */
+#define FEMMODEL (mxArray*)prhs[0]
+
+/* serial output macros: */
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  0
+#undef NRHS
+#define NRHS  1
+
+
+#endif  /* _DAKOTA_H */
+
Index: /issm/trunk-jpl-damage/src/mex/DakotaResponses/DakotaResponses.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/DakotaResponses/DakotaResponses.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/DakotaResponses/DakotaResponses.cpp	(revision 11330)
@@ -0,0 +1,92 @@
+/*\file DakotaResponses.c
+*\brief: compute dakota responses after a run
+*/
+
+#include "./DakotaResponses.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	int i;
+
+	/*input datasets: */
+	Elements*   elements=NULL;
+	Nodes*      nodes=NULL;
+	Vertices*   vertices=NULL;
+	Loads*      loads=NULL;
+	Materials*  materials=NULL;
+	Parameters* parameters=NULL;
+	double*     responses=NULL;
+	char**      responses_descriptors=NULL;
+	char*       string=NULL;
+	int         numresponses;
+	int         numresponsedescriptors;
+	mxArray*    pfield=NULL;
+	int         stringlength;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&DakotaResponsesUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+	FetchMatlabData((DataSet**)&nodes,NODESIN);
+	FetchMatlabData((DataSet**)&vertices,VERTICESIN);
+	FetchMatlabData((DataSet**)&loads,LOADSIN);
+	FetchMatlabData((DataSet**)&materials,MATERIALSIN);
+	FetchMatlabData(&parameters,PARAMETERSIN);
+
+	/*number of responses: */
+	parameters->FindParam(&numresponses,QmuNumberofresponsesEnum);
+	
+	/*dakota input: */
+	numresponsedescriptors=mxGetM(RESPONSESDESCRIPTORS);
+	responses_descriptors=(char**)xmalloc(numresponsedescriptors*sizeof(char*));
+	for(i=0;i<numresponsedescriptors;i++){
+		pfield=mxGetCell(RESPONSESDESCRIPTORS,i);
+		stringlength = (mxGetM(pfield) * mxGetN(pfield) * sizeof(mxChar)) + 1 ;
+		string=(char*)xmalloc(stringlength);
+		mxGetString(pfield,string,stringlength);
+		responses_descriptors[i]=string;
+	}
+
+	/*Allocate responses: */
+	responses=(double*)xmalloc(numresponses*sizeof(double));
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+	
+	/*!Generate internal degree of freedom numbers: */
+	DakotaResponsesx(responses,elements,nodes, vertices,loads,materials, parameters, responses_descriptors,numresponsedescriptors,numresponses);
+
+	/*write output datasets: */
+	WriteMatlabData(RESPONSES,responses,numresponses);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+	
+	for(i=0;i<numresponsedescriptors;i++){
+		char* string=responses_descriptors[i]; xfree((void**)&string);
+	}
+	xfree((void**)&responses_descriptors);
+	
+	//xfree((void**)&responses); do not free responses!
+
+	/*end module: */
+	MODULEEND();
+}
+
+void DakotaResponsesUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [responses] = %s(elements,nodes,vertices,loads,materials,parameters,responses_descritpors);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/DakotaResponses/DakotaResponses.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/DakotaResponses/DakotaResponses.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/DakotaResponses/DakotaResponses.h	(revision 11330)
@@ -0,0 +1,38 @@
+/*
+	DakotaResponses.h
+*/
+
+#ifndef _DAKOTARESPONSES_H
+#define _DAKOTARESPONSES_H
+
+/* local prototypes: */
+void DakotaResponsesUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "DakotaResponses"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODESIN (mxArray*)prhs[1]
+#define VERTICESIN (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALSIN (mxArray*)prhs[4]
+#define PARAMETERSIN (mxArray*)prhs[5]
+#define RESPONSESDESCRIPTORS (mxArray*)prhs[6]
+
+/* serial output macros: */
+#define RESPONSES (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  7
+
+#endif  /* _DAKOTARESPONSES_H */
+
Index: /issm/trunk-jpl-damage/src/mex/Echo/Echo.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Echo/Echo.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Echo/Echo.cpp	(revision 11330)
@@ -0,0 +1,33 @@
+/*\file Echo.c
+ *\brief:  echo a dataset from a matlab workspace handle.
+ */
+
+#include "./Echo.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	DataSet* dataset=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&EchoUsage);
+
+	/*Input datasets: */
+	FetchMatlabData(&dataset,DATASET);
+
+	/*Echo dataset: */
+	dataset->Echo();
+	
+	/*end module: */
+	MODULEEND();
+}
+
+void EchoUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: %s(m.dataset);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/Echo/Echo.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Echo/Echo.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Echo/Echo.h	(revision 11330)
@@ -0,0 +1,27 @@
+/*!\file:  Echo.h
+ * \brief header file for Echo module.
+ */ 
+
+#ifndef _ECHO_H
+#define _ECHO_H
+
+/* local prototypes: */
+void EchoUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+    
+/* serial input macros: */
+#define DATASET (mxArray*)prhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  0
+#undef NRHS
+#define NRHS  1
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Echo"
+
+#endif  /* _ECHO_H */
Index: /issm/trunk-jpl-damage/src/mex/ElementConnectivity/ElementConnectivity.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ElementConnectivity/ElementConnectivity.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ElementConnectivity/ElementConnectivity.cpp	(revision 11330)
@@ -0,0 +1,46 @@
+/*\file ElementConnectivity.c
+ *\brief: build element connectivity using node connectivity and elements. 
+ */
+
+#include "./ElementConnectivity.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*inputs: */
+	double* elements=NULL;
+	double* nodeconnectivity=NULL;
+	int     nel,nods;
+	int     width;
+
+	/*outputs: */
+	double* elementconnectivity=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ElementConnectivityUsage);
+        
+	/*Input datasets: */
+	FetchMatlabData(&elements,&nel,NULL,ELEMENTS);
+	FetchMatlabData(&nodeconnectivity,&nods,&width,NODECONNECTIVITY);
+
+	/*!Generate internal degree of freedom numbers: */
+	ElementConnectivityx(&elementconnectivity, elements,nel, nodeconnectivity, nods, width);
+
+	/*write output datasets: */
+	WriteMatlabData(ELEMENTCONNECTIVITY,elementconnectivity,nel,3);
+
+	/*Free ressources: */
+	xfree((void**)&elements);
+	xfree((void**)&nodeconnectivity);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ElementConnectivityUsage(void) {
+	_printf_(true,"\n");
+	_printf_(true,"   usage: elementconnectivity = %s(elements, nodeconnectivity);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ElementConnectivity/ElementConnectivity.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ElementConnectivity/ElementConnectivity.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ElementConnectivity/ElementConnectivity.h	(revision 11330)
@@ -0,0 +1,35 @@
+
+/*
+	ElementConnectivity.h
+*/
+
+
+#ifndef _ELEMENTCONNECTIVITY_H
+#define _ELEMENTCONNECTIVITY_H
+
+/* local prototypes: */
+void ElementConnectivityUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ElementConnectivity"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODECONNECTIVITY (mxArray*)prhs[1]
+
+/* serial output macros: */
+#define ELEMENTCONNECTIVITY (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+
+#endif  /* _ELEMENTCONNECTIVITY_H */
+
Index: /issm/trunk-jpl-damage/src/mex/EnumToString/EnumToString.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/EnumToString/EnumToString.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/EnumToString/EnumToString.cpp	(revision 11330)
@@ -0,0 +1,32 @@
+/*\file EnumToString.c
+ *\brief:convert enum (int) to string
+ */
+
+#include "./EnumToString.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	char    *name    = NULL;
+	int      enum_in;
+
+	/*checks on arguments on the matlab side: */
+	if(nrhs!=NRHS){
+		EnumToStringUsage(); _error_(" usage. See above");
+	}
+
+	/*Fetch inputs: */
+	FetchMatlabData(&enum_in,ENUMIN);
+
+	/*Run core function: */
+	EnumToStringx(&name,enum_in);
+
+	/* output: */
+	WriteMatlabData(NAME,name);
+}
+
+void EnumToStringUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: %sstring = EnumToString(enum);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/EnumToString/EnumToString.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/EnumToString/EnumToString.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/EnumToString/EnumToString.h	(revision 11330)
@@ -0,0 +1,30 @@
+/*!\file:  EnumToString.h
+ * \brief header file for EnumToString module.
+ */ 
+
+#ifndef _ENUMTOSTRING_H
+#define _ENUMTOSTRING_H
+
+/* local prototypes: */
+void EnumToStringUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+    
+/* serial input macros: */
+#define ENUMIN (mxArray*)prhs[0]
+
+/* serial output macros: */
+#define NAME (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  1
+
+#undef __FUNCT__ 
+#define __FUNCT__  "EnumToString"
+
+#endif  /* _TEST_H */
Index: /issm/trunk-jpl-damage/src/mex/Exp2Kml/Exp2Kml.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Exp2Kml/Exp2Kml.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Exp2Kml/Exp2Kml.cpp	(revision 11330)
@@ -0,0 +1,115 @@
+/*\file Exp2Kml.c
+ *\brief: exp to kml file conversion mex module.
+ */
+#include "./Exp2Kml.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	int i,verbose=1;
+
+	/*input: */
+	char    *filexp=NULL,*filkml=NULL;
+	int     sgn;
+
+	Options* options=NULL;
+	char     *choles=NULL;
+	bool     holes=false;
+	double   cm=0.,sp=0.;
+
+	/* output: */
+	int     iret=0;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if (nlhs > NLHS) {
+		Exp2KmlUsage();
+		_error_("Exp2Kml usage error");
+	}
+	if (nrhs < NRHS) {
+		Exp2KmlUsage();
+		_error_("Exp2Kml usage error");
+	}
+
+	/*Input datasets: */
+	if (verbose) printf("Fetching inputs:\n");
+	FetchMatlabData(&filexp,EXP_IN);
+	if (verbose) printf("  filexp=\"%s\"\n",filexp);
+	FetchMatlabData(&filkml,KML_IN);
+	if (verbose) printf("  filkml=\"%s\"\n",filkml);
+	FetchMatlabData(&sgn,SGN_IN);
+	if (verbose) printf("  sgn=%d\n",sgn);
+
+	if (verbose) printf("Parsing options:\n");
+	options=new Options(NRHS,nrhs,prhs);
+	if (options->Size()) for(i=0;i<options->Size();i++) ((Option*)options->GetObjectByOffset(i))->DeepEcho();
+	options->Get(&choles,"holes","no");
+	if (!strncmp(choles,"y",1) || !strncmp(choles,"on",2))
+		holes=true;
+	/*  defaults are in Xy2lldef, so don't duplicate them here, and only use user values if both have been specified  */
+	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
+		options->Get(&cm,"central_meridian");
+		if (verbose) printf("  cm=%g\n",cm);
+		options->Get(&sp,"standard_parallel");
+		if (verbose) printf("  sp=%g\n",sp);
+	}
+
+	/*some checks*/
+	if (verbose) printf("Checking inputs:\n");
+
+	if (sgn != +1 && sgn != -1) _error_("Hemisphere sgn=%d must be +1 (north) or -1 (south).",sgn);
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=%g must be between -180 (west) and +180 (east) degrees.",cm);
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=%g must be between 0 and 90 degrees (in specified hemisphere).",sp);
+
+	/* Run core computations: */
+	if (verbose) printf("Calling core:\n");
+	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
+		iret=Exp2Kmlx(filexp,filkml,
+					  sgn,cm,sp,
+					  holes);
+	else
+		iret=Exp2Kmlx(filexp,filkml,
+					  sgn,
+					  holes);
+	if (verbose) printf("  iret=%d\n",iret);
+
+	/*Write data: */
+	WriteMatlabData(RET_OUT,iret);
+
+	/*Clean-up*/
+	xfree((void**)&choles);
+	delete options;
+	xfree((void**)&filkml);
+	xfree((void**)&filexp);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void Exp2KmlUsage(void)
+{
+	_printf_(true,"Exp2Kml - exp to kml file conversion module:\n");
+	_printf_(true,"\n");
+	_printf_(true,"   This module converts a file from exp to kml format.\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"      [ret]=Exp2Kml(filexp,filkml,sgn,'param name',param,...);\n");
+	_printf_(true,"\n");
+	_printf_(true,"      filexp      file name of exp file to be read (char)\n");
+	_printf_(true,"      filkml      file name of kml file to be written (char)\n");
+	_printf_(true,"      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
+	_printf_(true,"\n");
+	_printf_(true,"      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf_(true,"      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf_(true,"      holes       flag for treatment of multiple profiles (char, optional, 'yes' for holes))\n");
+	_printf_(true,"\n");
+	_printf_(true,"      ret         return code (non-zero for warning)\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Examples:\n");
+	_printf_(true,"      [ret]=Exp2Kml('file.exp','file.kml', 1);\n");
+	_printf_(true,"      [ret]=Exp2Kml('file.exp','file.kml', 1,'central_meridian',45,'standard_parallel',70,'holes','yes');\n");
+	_printf_(true,"      [ret]=Exp2Kml('file.exp','file.kml',-1,'central_meridian', 0,'standard_parallel',71,'holes','yes');\n");
+	_printf_(true,"\n");
+}
+
Index: /issm/trunk-jpl-damage/src/mex/Exp2Kml/Exp2Kml.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Exp2Kml/Exp2Kml.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Exp2Kml/Exp2Kml.h	(revision 11330)
@@ -0,0 +1,34 @@
+/*!\file Exp2Kml.h
+ * \brief: prototype for exp to kml file conversion mex module.
+ */
+
+#ifndef _EXP2KML_H
+#define _EXP2KML_H
+
+/* local prototypes: */
+void Exp2KmlUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Exp2Kml"
+
+
+/* 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]
+
+/* serial arg counts: */
+#undef NRHS
+#define NRHS  3
+#undef NLHS
+#define NLHS  1
+
+#endif
+
Index: /issm/trunk-jpl-damage/src/mex/GetSolutionFromInputs/GetSolutionFromInputs.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/GetSolutionFromInputs/GetSolutionFromInputs.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/GetSolutionFromInputs/GetSolutionFromInputs.cpp	(revision 11330)
@@ -0,0 +1,62 @@
+/*\file GetSolutionFromInputs.c
+ *\brief: recover velocity ug from inputs
+ */
+
+#include "./GetSolutionFromInputs.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL;
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+	Vec      ug=NULL;
+
+	/* output datasets: elements and loads*/
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&GetSolutionFromInputsUsage);
+	
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADSIN);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Configure objects:*/
+	GetSolutionFromInputsx(&ug,elements, nodes,vertices,loads, materials,parameters);
+
+	/*write output datasets: */
+	WriteMatlabData(UG,ug);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void GetSolutionFromInputsUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [ug] = %s(elements,nodes,vertices,loads, materials,parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/GetSolutionFromInputs/GetSolutionFromInputs.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/GetSolutionFromInputs/GetSolutionFromInputs.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/GetSolutionFromInputs/GetSolutionFromInputs.h	(revision 11330)
@@ -0,0 +1,37 @@
+/*
+	GetSolutionFromInputs.h
+*/
+
+#ifndef _GETSOLUTIONFROMINPUTS_H
+#define _GETSOLUTIONFROMINPUTS_H
+
+/* local prototypes: */
+void GetSolutionFromInputsUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "GetSolutionFromInputs"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+
+/* serial output macros: */
+#define UG (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  6
+
+
+#endif  /* _GETSOLUTIONFROMINPUTS_H */
+
Index: /issm/trunk-jpl-damage/src/mex/GetVectorFromInputs/GetVectorFromInputs.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/GetVectorFromInputs/GetVectorFromInputs.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/GetVectorFromInputs/GetVectorFromInputs.cpp	(revision 11330)
@@ -0,0 +1,66 @@
+/*\file GetVectorFromInputs.c
+ *\brief: recover velocity ug from inputs
+ */
+
+#include "./GetVectorFromInputs.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL;
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+	int name_enum;
+	int type_enum;
+	Vec      ug=NULL;
+
+	/* output datasets: elements and loads*/
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&GetVectorFromInputsUsage);
+	
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADSIN);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+	FetchMatlabData(&name_enum,NAMEENUM);
+	FetchMatlabData(&type_enum,TYPEENUM);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!core code:*/
+	GetVectorFromInputsx(&ug,elements, nodes,vertices,loads, materials,parameters,name_enum,type_enum);
+
+	/*write output datasets: */
+	WriteMatlabData(UG,ug);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void GetVectorFromInputsUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [ug] = %s(elements,nodes,vertices,loads, materials,parameters,name_enum,type_enum);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/GetVectorFromInputs/GetVectorFromInputs.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/GetVectorFromInputs/GetVectorFromInputs.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/GetVectorFromInputs/GetVectorFromInputs.h	(revision 11330)
@@ -0,0 +1,37 @@
+/*
+	GetVectorFromInputs.h
+*/
+
+#ifndef _GETVECTORFROMINPUTS_H
+#define _GETVECTORFROMINPUTS_H
+
+/* local prototypes: */
+void GetVectorFromInputsUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "GetVectorFromInputs"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+#define NAMEENUM (mxArray*)prhs[6]
+#define TYPEENUM (mxArray*)prhs[7]
+
+/* serial output macros: */
+#define UG (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  8
+
+#endif  /* _GETVECTORFROMINPUTS_H */
Index: /issm/trunk-jpl-damage/src/mex/Gradj/Gradj.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Gradj/Gradj.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Gradj/Gradj.cpp	(revision 11330)
@@ -0,0 +1,65 @@
+/*\file Gradj.c
+ *\brief: compute gradients for inverse control method
+ */
+
+#include "./Gradj.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	int         control_type;
+	Elements   *elements     = NULL;
+	Nodes      *nodes        = NULL;
+	Vertices   *vertices     = NULL;
+	Loads      *loads        = NULL;
+	Materials  *materials    = NULL;
+	Parameters *parameters   = NULL;
+
+	/* output datasets: */
+	Vec         gradient       = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&GradjUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+	FetchMatlabData(&control_type,CONTROLTYPE);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Call core code: */
+	Gradjx(&gradient, elements,nodes, vertices,loads, materials,parameters, control_type);
+
+	/*write output : */
+	WriteMatlabData(GRADG,gradient);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+	VecFree(&gradient);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void GradjUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [gradient] = %s(elements,nodes,vertices,loads, materials, parameters,control_type);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/Gradj/Gradj.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Gradj/Gradj.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Gradj/Gradj.h	(revision 11330)
@@ -0,0 +1,37 @@
+/*
+	Gradj.h
+*/
+
+#ifndef _GRADJ_H
+#define _GRADJ_H
+
+/* local prototypes: */
+void GradjUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Gradj"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADS (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+#define CONTROLTYPE (mxArray*)prhs[6]
+
+/* serial output macros: */
+#define GRADG (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  7
+
+#endif  /* _GRADJ_H */
Index: /issm/trunk-jpl-damage/src/mex/GroundinglineMigration/GroundinglineMigration.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/GroundinglineMigration/GroundinglineMigration.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/GroundinglineMigration/GroundinglineMigration.cpp	(revision 11330)
@@ -0,0 +1,64 @@
+/*\file GroundinglineMigration.c
+*\brief: update elements properties using an input  vector
+*/
+
+#include "./GroundinglineMigration.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements*   elements          = NULL;
+	Nodes      *nodes             = NULL;
+	Vertices    *vertices          = NULL;
+	Loads     *loads             = NULL;
+	Materials   *materials         = NULL;
+	Parameters *parameters        = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&GroundinglineMigrationUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+	FetchMatlabData((DataSet**)&nodes,NODESIN);
+	FetchMatlabData((DataSet**)&vertices,VERTICESIN);
+	FetchMatlabData((DataSet**)&loads,LOADSIN);
+	FetchMatlabData((DataSet**)&materials,MATERIALSIN);
+	FetchMatlabData(&parameters,PARAMETERSIN);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*call "x" code layer*/
+	GroundinglineMigrationx(elements,nodes,vertices,loads, materials,parameters);
+
+	/*write output datasets: */
+	WriteMatlabData(ELEMENTS,elements);
+	WriteMatlabData(NODES,nodes);
+	WriteMatlabData(VERTICES,vertices);
+	WriteMatlabData(LOADS,loads);
+	WriteMatlabData(MATERIALS,materials);
+	WriteMatlabData(PARAMETERS,parameters);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void GroundinglineMigrationUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements,nodes,vertices,loads,materials,parameters] = %s(elements,nodes,vertices,loads,materials,parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/GroundinglineMigration/GroundinglineMigration.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/GroundinglineMigration/GroundinglineMigration.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/GroundinglineMigration/GroundinglineMigration.h	(revision 11330)
@@ -0,0 +1,42 @@
+/*
+	GroundinglineMigration.h
+*/
+
+#ifndef _GROUNDINGLINEMIGRATION_H
+#define _GROUNDINGLINEMIGRATION_H
+
+/* local prototypes: */
+void GroundinglineMigrationUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "GroundinglineMigration"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODESIN (mxArray*)prhs[1]
+#define VERTICESIN (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALSIN (mxArray*)prhs[4]
+#define PARAMETERSIN (mxArray*)prhs[5]
+
+/* serial output macros: */
+#define ELEMENTS (mxArray**)&plhs[0]
+#define NODES (mxArray**)&plhs[1]
+#define VERTICES (mxArray**)&plhs[2]
+#define LOADS (mxArray**)&plhs[3]
+#define MATERIALS (mxArray**)&plhs[4]
+#define PARAMETERS (mxArray**)&plhs[5]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  6
+#undef NRHS
+#define NRHS  6
+
+#endif  /* _GROUNDINGLINEMIGRATION_H */
+
Index: /issm/trunk-jpl-damage/src/mex/HoleFiller/HoleFiller.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/HoleFiller/HoleFiller.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/HoleFiller/HoleFiller.cpp	(revision 11330)
@@ -0,0 +1,69 @@
+/*!\file:  HoleFiller.cpp
+ * \brief fill holes in matlab velocity array
+	this matlab module is an adaptation of a routine written by Robber 
+	Crippen.  The original routine was designed for the SRTM mission at JPL, 
+	and can be found in the current directory, under the name 
+	HoleFillerCrippen.  It fills void holes in an image, using an interpolation 
+	algorithm, and optionnally a smoothing algorithm. 
+	This matlab module extends the Crippen routine to be used in Matlab, 
+	using double arrays found in the workspace, and loaded directly into memory.
+*/
+
+
+#include "./HoleFiller.h"
+
+void mexFunction( int nlhs, mxArray* plhs[],
+				  int nrhs, const mxArray* prhs[])
+{
+
+	int i,j;
+
+	/* required input: */
+	double* imagein=NULL;
+	int     imagein_rows,imagein_cols;
+	int     smooth_flag;
+	int     smooth;
+
+
+	/* output: */
+	mxArray* pfield=NULL;
+	double* imageout=NULL;
+	int     imageout_rows,imageout_cols;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&HoleFillerUsage);
+
+	/*Fetch data: */
+	FetchMatlabData(&imagein,&imagein_rows,&imagein_cols,IMAGEIN);
+	FetchMatlabData(&smooth_flag,SMOOTH);
+	
+	/*Get smooth flag setup: */
+	if (smooth_flag==0)
+		smooth=1;
+	else
+		smooth=0;
+
+	/*Run core hole filler routine: */
+	HoleFillerx( &imageout,imagein,imagein_rows,imagein_cols,smooth);
+
+	/* output: */
+	WriteMatlabData(IMAGEOUT,imageout,imagein_rows,imagein_cols);
+
+	/*end module: */
+	MODULEEND();
+}
+
+
+void HoleFillerUsage(void)
+{
+	printf("   HoleFiller usage:\n");
+	printf("   [image_out]=HoleFiller(image_in,smooth);\n\n");
+	printf("   where:\n");
+	printf("      image_in in double format\n");
+	printf("      smooth: 1 to smooth with a box filer, 0 to leave data raw\n");
+	printf("      image_out in double format\n");
+	printf("\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/HoleFiller/HoleFiller.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/HoleFiller/HoleFiller.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/HoleFiller/HoleFiller.h	(revision 11330)
@@ -0,0 +1,34 @@
+
+/*
+	HoleFiller.h
+*/
+
+
+#ifndef _HOLEFILLER_H
+#define _HOLEFILLER_H
+
+/* local prototypes: */
+void HoleFillerUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "HoleFiller"
+
+
+/* serial input macros: */
+#define IMAGEIN prhs[0]
+#define SMOOTH prhs[1]
+
+/* serial output macros: */
+#define IMAGEOUT &plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+#endif  /* _HOLEFILLER_H */
Index: /issm/trunk-jpl-damage/src/mex/InputControlUpdate/InputControlUpdate.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputControlUpdate/InputControlUpdate.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputControlUpdate/InputControlUpdate.cpp	(revision 11330)
@@ -0,0 +1,68 @@
+/*\file InputControlUpdate.c
+*\brief: update elements properties using an input  vector
+*/
+
+#include "./InputControlUpdate.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+/*input datasets: */
+Elements   *elements   = NULL;
+Nodes      *nodes      = NULL;
+Vertices   *vertices   = NULL;
+Loads      *loads      = NULL;
+Materials  *materials  = NULL;
+Parameters *parameters = NULL;
+double      scalar;
+double      update;
+
+/*Boot module: */
+MODULEBOOT();
+
+/*checks on arguments on the matlab side: */
+CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InputControlUpdateUsage);
+
+/*Input datasets: */
+FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+FetchMatlabData((DataSet**)&nodes,NODESIN);
+FetchMatlabData((DataSet**)&vertices,VERTICESIN);
+FetchMatlabData((DataSet**)&loads,LOADSIN);
+FetchMatlabData((DataSet**)&materials,MATERIALSIN);
+FetchMatlabData(&parameters,PARAMETERSIN);
+FetchMatlabData(&scalar,SCALAR);
+FetchMatlabData(&update,UPDATE);
+
+/*configure: */
+elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+/*call "x" code layer*/
+InputControlUpdatex(elements,nodes,vertices,loads, materials,parameters,scalar,(bool)update);
+
+/*write output datasets: */
+WriteMatlabData(ELEMENTS,elements);
+WriteMatlabData(NODES,nodes);
+WriteMatlabData(VERTICES,vertices);
+WriteMatlabData(LOADS,loads);
+WriteMatlabData(MATERIALS,materials);
+WriteMatlabData(PARAMETERS,parameters);
+
+/*Free ressources: */
+delete elements;
+delete nodes;
+delete vertices;
+delete loads;
+delete materials;
+delete parameters;
+
+/*end module: */
+MODULEEND();
+}
+
+void InputControlUpdateUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements,nodes,vertices,loads,materials,parameters] = %s(elements,nodes,vertices,loads,materials,parameters,scalar);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InputControlUpdate/InputControlUpdate.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputControlUpdate/InputControlUpdate.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputControlUpdate/InputControlUpdate.h	(revision 11330)
@@ -0,0 +1,44 @@
+/*
+	InputControlUpdate.h
+*/
+
+#ifndef _INPUTCONTROLUPDATE_H
+#define _INPUTCONTROLUPDATE_H
+
+/* local prototypes: */
+void InputControlUpdateUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InputControlUpdate"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODESIN (mxArray*)prhs[1]
+#define VERTICESIN (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALSIN (mxArray*)prhs[4]
+#define PARAMETERSIN (mxArray*)prhs[5]
+#define SCALAR (mxArray*)prhs[6]
+#define UPDATE (mxArray*)prhs[7]
+
+/* serial output macros: */
+#define ELEMENTS (mxArray**)&plhs[0]
+#define NODES (mxArray**)&plhs[1]
+#define VERTICES (mxArray**)&plhs[2]
+#define LOADS (mxArray**)&plhs[3]
+#define MATERIALS (mxArray**)&plhs[4]
+#define PARAMETERS (mxArray**)&plhs[5]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  6
+#undef NRHS
+#define NRHS  8
+
+#endif  /* _INPUTCONTROLCONSTRAIN_H */
+
Index: /issm/trunk-jpl-damage/src/mex/InputConvergence/InputConvergence.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputConvergence/InputConvergence.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputConvergence/InputConvergence.cpp	(revision 11330)
@@ -0,0 +1,85 @@
+/*\file InputConvergence.c
+ *\brief: processes model inputs from the matlab workspace, and transforms them into datasets or vectors 
+ *        that will be used throughout the matlab solution sequences.
+ */
+
+#include "./InputConvergence.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){ 
+
+	int i;
+
+	/*inputs: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL;
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+
+	int* field_enums=NULL;
+	double* double_fields=NULL;
+	int numfields;
+	int* criterion_enums=NULL;
+	double* double_criterion=NULL;
+	double* criterion_values=NULL;
+	int numcriterions;
+
+	/* output datasets: */
+	bool converged;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InputConvergenceUsage);
+
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	FetchMatlabData(&double_fields,&numfields,FIELDENUMS);
+	field_enums=(int*)xmalloc(numfields*sizeof(int));
+	for(i=0;i<numfields;i++)field_enums[i]=(int)double_fields[i];
+
+	FetchMatlabData(&double_criterion,&numcriterions,CRITERIONENUMS);
+	FetchMatlabData(&criterion_values,&numcriterions,CRITERIONVALUES);
+	criterion_enums=(int*)xmalloc(numcriterions*sizeof(int));
+	for(i=0;i<numcriterions;i++)criterion_enums[i]=(int)double_criterion[i];
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+	
+	/*call x code InputConvergencex: */
+	converged=InputConvergencex(elements,nodes,vertices,loads,materials,parameters, field_enums,numfields,criterion_enums,criterion_values,numcriterions);
+
+	/*Write output data: */
+	WriteMatlabData(CONVERGED,converged);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+	xfree((void**)&field_enums);
+	xfree((void**)&double_fields);
+	xfree((void**)&criterion_enums);
+	xfree((void**)&double_criterion);
+	xfree((void**)&criterion_values);
+	
+	/*end module: */
+	MODULEEND();
+}
+	
+void InputConvergenceUsage(void) {
+	_printf_(true,"\n");
+	_printf_(true,"   usage: convergence=InputConvergence(elements,nodes,vertices,loads,materials,parameters,fieldenums,criterionenums,criterionvalue)\n");
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InputConvergence/InputConvergence.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputConvergence/InputConvergence.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputConvergence/InputConvergence.h	(revision 11330)
@@ -0,0 +1,41 @@
+/*\file InputConvergence.h
+ * \brief: InputConvergence module include
+ */
+
+#ifndef _MEXINPUTCONVERGENCE_H_
+#define _MEXINPUTCONVERGENCE_H_
+
+/* local prototypes: */
+void InputConvergenceUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InputConvergence"
+
+#undef ALL
+#define ALL 0
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADS (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+#define FIELDENUMS (mxArray*)prhs[6]
+#define CRITERIONENUMS (mxArray*)prhs[7]
+#define CRITERIONVALUES (mxArray*)prhs[8]
+
+/* serial output macros: */
+#define CONVERGED (mxArray**)&plhs[0]
+		
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  9 
+
+#endif  /* _MEXINPUTCONVERGENCE_H */
Index: /issm/trunk-jpl-damage/src/mex/InputDuplicate/InputDuplicate.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputDuplicate/InputDuplicate.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputDuplicate/InputDuplicate.cpp	(revision 11330)
@@ -0,0 +1,59 @@
+/*\file InputDuplicate.c
+ *\brief: duplicate input
+ */
+
+#include "./InputDuplicate.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL;
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+	int      original_enum,new_enum; 
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InputDuplicateUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+	
+	FetchMatlabData(&original_enum,ORIGINALENUM);
+	FetchMatlabData(&new_enum,NEWENUM);
+
+	/*!Call core code: */
+	InputDuplicatex( elements, nodes, vertices, loads, materials,parameters,original_enum, new_enum);
+
+	/*write output : */
+	WriteMatlabData(ELEMENTSOUT,elements);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+	
+	/*end module: */
+	MODULEEND();
+
+}
+
+void InputDuplicateUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements] = %s(elements, nodes, vertices, loads, materials, parameters, original_enum,new_enum);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InputDuplicate/InputDuplicate.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputDuplicate/InputDuplicate.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputDuplicate/InputDuplicate.h	(revision 11330)
@@ -0,0 +1,37 @@
+/*
+	InputDuplicate.h
+*/
+
+#ifndef _INPUTDUPLICATE_H
+#define _INPUTDUPLICATE_H
+
+/* local prototypes: */
+void InputDuplicateUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InputDuplicate"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADS (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+#define ORIGINALENUM (mxArray*)prhs[6]
+#define NEWENUM (mxArray*)prhs[7]
+
+/* serial output macros: */
+#define ELEMENTSOUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  8
+
+#endif  /* _INPUTDUPLICATE_H */
Index: /issm/trunk-jpl-damage/src/mex/InputScale/InputScale.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputScale/InputScale.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputScale/InputScale.cpp	(revision 11330)
@@ -0,0 +1,65 @@
+/*\file InputScale.c
+ *\brief: duplicate input
+ */
+
+#include "./InputScale.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL;
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+	int      enum_type;
+	double   scale_factor;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InputScaleUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+	
+	FetchMatlabData(&enum_type,ENUMTYPE);
+	FetchMatlabData(&scale_factor,SCALEFACTOR);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Call core code: */
+	InputScalex( elements, nodes, vertices, loads, materials,parameters,enum_type, scale_factor);
+
+	/*write output : */
+	WriteMatlabData(ELEMENTSOUT,elements);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+	
+	/*end module: */
+	MODULEEND();
+
+}
+
+void InputScaleUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements] = %s(elements, nodes, vertices, loads, materials, parameters, enum_type,scale_factor);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InputScale/InputScale.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputScale/InputScale.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputScale/InputScale.h	(revision 11330)
@@ -0,0 +1,37 @@
+/*
+	InputScale.h
+*/
+
+#ifndef _INPUTSCALE_H
+#define _INPUTSCALE_H
+
+/* local prototypes: */
+void InputScaleUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InputScale"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADS (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+#define ENUMTYPE (mxArray*)prhs[6]
+#define SCALEFACTOR (mxArray*)prhs[7]
+
+/* serial output macros: */
+#define ELEMENTSOUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  8
+
+#endif  /* _INPUTSCALE_H */
Index: /issm/trunk-jpl-damage/src/mex/InputToResult/InputToResult.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputToResult/InputToResult.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputToResult/InputToResult.cpp	(revision 11330)
@@ -0,0 +1,79 @@
+/*\file InputToResult.c
+ *\brief: duplicate input
+ */
+
+#include "./InputToResult.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL;
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+	int      enum_type,step; 
+	double   time;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	//CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InputToResultUsage); Cant' use it here, as we have variable inputs.
+	if((nlhs!=NLHS) || (nrhs!=7 && nrhs!=9)){
+		InputToResultUsage();
+		_error_(" usage. See above");
+	}
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+	
+	FetchMatlabData(&enum_type,ENUMTYPE);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	if(nrhs==9){
+		FetchMatlabData(&step,STEP);
+		FetchMatlabData(&time,TIME);
+
+		/*!Call core code: */
+		InputToResultx( elements, nodes, vertices, loads, materials,parameters,enum_type, step,time);
+	}
+	else{
+
+		/*!Call core code: */
+		InputToResultx( elements, nodes, vertices, loads, materials,parameters,enum_type);
+	}
+
+	/*write output : */
+	WriteMatlabData(ELEMENTSOUT,elements);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+	
+	/*end module: */
+	MODULEEND();
+
+}
+
+void InputToResultUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements] = %s(elements, nodes, vertices, loads, materials, parameters, enum_type,step,time);\n",__FUNCT__);
+	_printf_(true,"   usage: [elements] = %s(elements, nodes, vertices, loads, materials, parameters, enum_type);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InputToResult/InputToResult.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputToResult/InputToResult.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputToResult/InputToResult.h	(revision 11330)
@@ -0,0 +1,36 @@
+/*
+	InputToResult.h
+*/
+
+#ifndef _INPUTTORESULT_H
+#define _INPUTTORESULT_H
+
+/* local prototypes: */
+void InputToResultUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InputToResult"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADS (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+#define ENUMTYPE (mxArray*)prhs[6]
+#define STEP (mxArray*)prhs[7]
+#define TIME (mxArray*)prhs[8]
+
+/* serial output macros: */
+#define ELEMENTSOUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+
+#endif  /* _INPUTTORESULT_H */
Index: /issm/trunk-jpl-damage/src/mex/InputUpdateFromConstant/InputUpdateFromConstant.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputUpdateFromConstant/InputUpdateFromConstant.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputUpdateFromConstant/InputUpdateFromConstant.cpp	(revision 11330)
@@ -0,0 +1,64 @@
+/*\file InputUpdateFromConstant.c
+*\brief: update elements properties using a constant value
+*/
+
+#include "./InputUpdateFromConstant.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL;
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+	double   constant;
+	int      name;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InputUpdateFromConstantUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+	FetchMatlabData((DataSet**)&nodes,NODESIN);
+	FetchMatlabData((DataSet**)&vertices,VERTICESIN);
+	FetchMatlabData((DataSet**)&loads,LOADSIN);
+	FetchMatlabData((DataSet**)&materials,MATERIALSIN);
+	FetchMatlabData(&parameters,PARAMETERSIN);
+	FetchMatlabData(&constant,CONSTANT);
+	FetchMatlabData(&name,NAME);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Generate internal degree of freedom numbers: */
+	InputUpdateFromConstantx(elements,nodes,vertices,loads, materials,parameters,constant,name);
+
+	/*write output datasets: */
+	WriteMatlabData(ELEMENTS,elements);
+	WriteMatlabData(LOADS,loads);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void InputUpdateFromConstantUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements loads] = %s(elements,nodes,vertices,loads,materials,parameters,constant,name);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InputUpdateFromConstant/InputUpdateFromConstant.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputUpdateFromConstant/InputUpdateFromConstant.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputUpdateFromConstant/InputUpdateFromConstant.h	(revision 11330)
@@ -0,0 +1,40 @@
+/*
+	InputUpdateFromConstant.h
+*/
+
+#ifndef _UPDATEINPUTSFROMCONSTANT_H
+#define _UPDATEINPUTSFROMCONSTANT_H
+
+/* local prototypes: */
+void InputUpdateFromConstantUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InputUpdateFromConstant"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODESIN (mxArray*)prhs[1]
+#define VERTICESIN (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALSIN (mxArray*)prhs[4]
+#define PARAMETERSIN (mxArray*)prhs[5]
+#define CONSTANT (mxArray*)prhs[6]
+#define NAME (mxArray*)prhs[7]
+
+/* serial output macros: */
+#define ELEMENTS (mxArray**)&plhs[0]
+#define LOADS (mxArray**)&plhs[1]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  2
+#undef NRHS
+#define NRHS  8
+
+#endif  /* _UPDATEINPUTSFROMCONSTANT_H */
+
Index: /issm/trunk-jpl-damage/src/mex/InputUpdateFromDakota/InputUpdateFromDakota.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputUpdateFromDakota/InputUpdateFromDakota.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputUpdateFromDakota/InputUpdateFromDakota.cpp	(revision 11330)
@@ -0,0 +1,89 @@
+/*\file InputUpdateFromDakota.c
+*\brief: update inputs using dakota input variables
+*/
+
+#include "./InputUpdateFromDakota.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	int i;
+
+	/*input datasets: */
+	Elements*   elements=NULL;
+	Nodes*      nodes=NULL;
+	Vertices*   vertices=NULL;
+	Loads*      loads=NULL;
+	Materials*  materials=NULL;
+	Parameters* parameters=NULL;
+	double*     variables=NULL;
+	char**      variables_descriptors=NULL;
+	char*       string=NULL;
+	int         stringlength;
+	int         numvariables;
+	mxArray*    pfield=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InputUpdateFromDakotaUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+	FetchMatlabData((DataSet**)&nodes,NODESIN);
+	FetchMatlabData((DataSet**)&vertices,VERTICESIN);
+	FetchMatlabData((DataSet**)&loads,LOADSIN);
+	FetchMatlabData((DataSet**)&materials,MATERIALSIN);
+	FetchMatlabData(&parameters,PARAMETERSIN);
+	/*dakota input: */
+	FetchMatlabData(&variables,&numvariables,VARIABLES);
+
+	variables_descriptors=(char**)xmalloc(numvariables*sizeof(char*));
+	for(i=0;i<numvariables;i++){
+
+		pfield=mxGetCell(VARIABLESDESCRIPTORS,i);
+		stringlength = (mxGetM(pfield) * mxGetN(pfield) * sizeof(mxChar)) + 1 ;
+		string=(char*)xmalloc(stringlength);
+		mxGetString(pfield,string,stringlength);
+
+		variables_descriptors[i]=string;
+	}
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+	materials-> Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Generate internal degree of freedom numbers: */
+	InputUpdateFromDakotax(elements,nodes,vertices,loads, materials,parameters,variables,variables_descriptors,numvariables);
+
+	/*write output datasets: */
+	WriteMatlabData(ELEMENTS,elements);
+	WriteMatlabData(LOADS,loads);
+	WriteMatlabData(MATERIALS,materials);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+
+	xfree((void**)&variables);
+	for(i=0;i<numvariables;i++){
+		char* string=variables_descriptors[i]; xfree((void**)&string);
+	}
+	xfree((void**)&variables_descriptors);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void InputUpdateFromDakotaUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements loads] = %s(elements,nodes,vertices,loads,materials,parameters,variables,variables_descriptors);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InputUpdateFromDakota/InputUpdateFromDakota.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputUpdateFromDakota/InputUpdateFromDakota.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputUpdateFromDakota/InputUpdateFromDakota.h	(revision 11330)
@@ -0,0 +1,40 @@
+/*
+	InputUpdateFromDakota.h
+*/
+
+#ifndef _UPDATEINPUTSFROMDAKOTA_H
+#define _UPDATEINPUTSFROMDAKOTA_H
+
+/* local prototypes: */
+void InputUpdateFromDakotaUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InputUpdateFromDakota"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODESIN (mxArray*)prhs[1]
+#define VERTICESIN (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALSIN (mxArray*)prhs[4]
+#define PARAMETERSIN (mxArray*)prhs[5]
+#define VARIABLES (mxArray*)prhs[6]
+#define VARIABLESDESCRIPTORS (mxArray*)prhs[7]
+
+/* serial output macros: */
+#define ELEMENTS (mxArray**)&plhs[0]
+#define LOADS (mxArray**)&plhs[1]
+#define MATERIALS (mxArray**)&plhs[2]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  3
+#undef NRHS
+#define NRHS  8
+
+#endif  /* _UPDATEINPUTSFROMDAKOTA_H */
Index: /issm/trunk-jpl-damage/src/mex/InputUpdateFromSolution/InputUpdateFromSolution.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputUpdateFromSolution/InputUpdateFromSolution.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputUpdateFromSolution/InputUpdateFromSolution.cpp	(revision 11330)
@@ -0,0 +1,63 @@
+/*\file InputUpdateFromSolution.c
+*\brief: update elements properties using a solution vector
+*/
+
+#include "./InputUpdateFromSolution.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL;
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+	Vec      solution=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InputUpdateFromSolutionUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+	FetchMatlabData((DataSet**)&nodes,NODESIN);
+	FetchMatlabData((DataSet**)&vertices,VERTICESIN);
+	FetchMatlabData((DataSet**)&loads,LOADSIN);
+	FetchMatlabData((DataSet**)&materials,MATERIALSIN);
+	FetchMatlabData(&parameters,PARAMETERSIN);
+	FetchMatlabData(&solution,SOLUTION);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Generate internal degree of freedom numbers: */
+	InputUpdateFromSolutionx(elements,nodes,vertices,loads, materials,parameters,solution);
+
+	/*write output datasets: */
+	WriteMatlabData(ELEMENTS,elements);
+	WriteMatlabData(MATERIALS,materials);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+	VecFree(&solution);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void InputUpdateFromSolutionUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements,materials] = %s(elements,nodes,vertices,loads,materials,parameters,solution);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InputUpdateFromSolution/InputUpdateFromSolution.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputUpdateFromSolution/InputUpdateFromSolution.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputUpdateFromSolution/InputUpdateFromSolution.h	(revision 11330)
@@ -0,0 +1,38 @@
+/*
+	InputUpdateFromSolution.h
+*/
+
+#ifndef _UPDATEINPUTSFROMSOLUTION_H
+#define _UPDATEINPUTSFROMSOLUTION_H
+
+/* local prototypes: */
+void InputUpdateFromSolutionUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InputUpdateFromSolution"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODESIN (mxArray*)prhs[1]
+#define VERTICESIN (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALSIN (mxArray*)prhs[4]
+#define PARAMETERSIN (mxArray*)prhs[5]
+#define SOLUTION (mxArray*)prhs[6]
+
+/* serial output macros: */
+#define ELEMENTS (mxArray**)&plhs[0]
+#define MATERIALS (mxArray**)&plhs[1]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  2
+#undef NRHS
+#define NRHS  7
+
+#endif  /* _UPDATEINPUTSFROMSOLUTION_H */
+
Index: /issm/trunk-jpl-damage/src/mex/InputUpdateFromVector/InputUpdateFromVector.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputUpdateFromVector/InputUpdateFromVector.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputUpdateFromVector/InputUpdateFromVector.cpp	(revision 11330)
@@ -0,0 +1,77 @@
+/*\file InputUpdateFromVector.c
+*\brief: update elements properties using an input  vector
+*/
+
+#include "./InputUpdateFromVector.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL;
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+	double*  vector=NULL;
+	int      dummy;
+	int      name;
+	int      type;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InputUpdateFromVectorUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+	FetchMatlabData((DataSet**)&nodes,NODESIN);
+	FetchMatlabData((DataSet**)&vertices,VERTICESIN);
+	FetchMatlabData((DataSet**)&loads,LOADSIN);
+	FetchMatlabData((DataSet**)&materials,MATERIALSIN);
+	FetchMatlabData(&parameters,PARAMETERSIN);
+	FetchMatlabData(&vector,&dummy,VECTOR);
+	FetchMatlabData(&name,NAME);
+	FetchMatlabData(&type,TYPE);
+
+	/*Check that type is one of Constant, Vertex or Element: */
+	if ((type!=ConstantEnum) && (type!=VertexEnum) && (type!=ElementEnum)){
+		_error_("%s%s%s\n","Type of input can only be a constant, a vertex or an element vector.  Right now, you input a ",EnumToStringx(type)," type data for input update");
+	}
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Generate internal degree of freedom numbers: */
+	InputUpdateFromVectorx(elements,nodes,vertices,loads, materials,parameters,vector,name,type);
+
+	/*write output datasets: */
+	WriteMatlabData(ELEMENTS,elements);
+	WriteMatlabData(NODES,nodes);
+	WriteMatlabData(VERTICES,vertices);
+	WriteMatlabData(LOADS,loads);
+	WriteMatlabData(MATERIALS,materials);
+	WriteMatlabData(PARAMETERS,parameters);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+	xfree((void**)&vector);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void InputUpdateFromVectorUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements,nodes,vertices,loads,materials,parameters] = %s(elements,nodes,vertices,loads,materials,parameters,vector,name_enum,type_enum);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InputUpdateFromVector/InputUpdateFromVector.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InputUpdateFromVector/InputUpdateFromVector.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InputUpdateFromVector/InputUpdateFromVector.h	(revision 11330)
@@ -0,0 +1,48 @@
+
+/*
+	InputUpdateFromVector.h
+*/
+
+
+#ifndef _UPDATEINPUTSFROMVECTOR_H
+#define _UPDATEINPUTSFROMVECTOR_H
+
+/* local prototypes: */
+void InputUpdateFromVectorUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InputUpdateFromVector"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODESIN (mxArray*)prhs[1]
+#define VERTICESIN (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALSIN (mxArray*)prhs[4]
+#define PARAMETERSIN (mxArray*)prhs[5]
+#define VECTOR (mxArray*)prhs[6]
+#define NAME (mxArray*)prhs[7]
+#define TYPE (mxArray*)prhs[8]
+
+/* serial output macros: */
+#define ELEMENTS (mxArray**)&plhs[0]
+#define NODES (mxArray**)&plhs[1]
+#define VERTICES (mxArray**)&plhs[2]
+#define LOADS (mxArray**)&plhs[3]
+#define MATERIALS (mxArray**)&plhs[4]
+#define PARAMETERS (mxArray**)&plhs[5]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  6
+#undef NRHS
+#define NRHS  9
+
+
+#endif  /* _UPDATEINPUTSFROMVECTOR_H */
+
Index: /issm/trunk-jpl-damage/src/mex/InternalFront/InternalFront.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InternalFront/InternalFront.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InternalFront/InternalFront.cpp	(revision 11330)
@@ -0,0 +1,99 @@
+/*\file InternalFront.c
+ *\brief: build pressureload
+ */
+
+#include "./InternalFront.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	bool*   elementonwater=NULL;
+	int*    elements=NULL;
+	int*    connectivity=NULL;
+	int*    elementconnectivity=NULL;
+	int*    front=NULL;
+	double* front2=NULL;
+	bool    found;
+	int     numberofelements,numberofsegments;
+	int     N,M;
+	int     i,j,ii,jj,id;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InternalFrontUsage);
+
+	/*Fetch required fields*/
+	FetchMatlabData(&numberofelements,mxGetAssignedField(MODEL,0,"numberofelements"));
+	if(numberofelements<=0) _error_("No elements found in the model");
+	FetchMatlabData(&elements,&M,&N,mxGetAssignedField(MODEL,0,"elements"));
+	if(M!=numberofelements || N!=3) _error_("Field 'elements' should be of size [md.numberofelements 3]");
+	FetchMatlabData(&elementonwater,&M,&N,mxGetAssignedField(MODEL,0,"elementonwater"));
+	if(M!=numberofelements || N!=1) _error_("Field 'elementonwater' should be of size [md.numberofelements 1]");
+	FetchMatlabData(&elementconnectivity,&M,&N,mxGetAssignedField(MODEL,0,"elementconnectivity"));
+	if(M!=numberofelements || N!=3) _error_("Field 'elementconnectivity' should be of size [md.numberofelements 3]");
+
+	/*Allocate and initialize all variables*/
+	numberofsegments=0;
+	front=(int*)xmalloc(3*numberofelements*4*sizeof(int));
+
+	/*Loop over all elements on water*/
+	for(i=0;i<numberofelements;i++){
+
+		/*Skip if on water*/
+		if(!elementonwater[i]) continue;
+
+		/*Loop over all three adjacent elements*/
+		for(j=0;j<3;j++){
+
+			/*Skip if adjacent element does not exist or is on water*/
+			id=elementconnectivity[i*3+j];
+			if(id==0) continue;
+			if(elementonwater[id-1]) continue;
+
+			/*We have an ice front to add here, let's go!*/
+			for(ii=0;ii<3;ii++){
+
+				found=false;
+				for(jj=0;jj<3;jj++){
+					if(elements[(id-1)*3+ii]==elements[i*3+jj]){
+						found=true;
+						break;
+					}
+				}
+
+				/*OK, we just found the node of id, which is not in i. We have the segment*/
+				if(!found){
+					front[numberofsegments*4+0]=elements[(id-1)*3+(ii+1)%3];
+					front[numberofsegments*4+1]=elements[(id-1)*3+(ii+2)%3];
+					front[numberofsegments*4+2]=id;
+					front[numberofsegments*4+3]=IceEnum;
+					numberofsegments+=1;
+					break;
+				}
+			}
+
+			/*In debugging mode, check that the segment has been found*/
+			_assert_(!found);
+		}
+	}
+
+	/*Now that we know how many segments there is we can allocate the final matrix*/
+	if(numberofsegments){
+		front2=(double*)xmalloc(4*numberofsegments*sizeof(double));
+		for(i=0;i<4*numberofsegments;i++) front2[i]=(double)front[i];
+	}
+	xfree((void**)&front);
+
+	/*write output datasets: */
+	WriteMatlabData(FRONT,front2,numberofsegments,4);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void InternalFrontUsage(void) {
+	_printf_(true,"\n");
+	_printf_(true,"   usage: icefront = %s(md);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InternalFront/InternalFront.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InternalFront/InternalFront.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InternalFront/InternalFront.h	(revision 11330)
@@ -0,0 +1,31 @@
+
+/*
+	InternalFront.h
+*/
+
+
+#ifndef _INTERNALFRONT_H
+#define _INTERNALFRONT_H
+
+/* local prototypes: */
+void InternalFrontUsage(void);
+
+#include "../../c/shared/shared.h"
+#include "../../c/io/io.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InternalFront"
+
+/* serial input macros: */
+#define MODEL (mxArray*)prhs[0]
+
+/* serial output macros: */
+#define FRONT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  1
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/InterpFromGridToMesh/InterpFromGridToMesh.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 11330)
@@ -0,0 +1,95 @@
+/*!\file InterpFromGridToMesh.c
+ * \brief: data interpolation from a list of (x,y,values) into mesh vertices
+ 
+	InterpFromGridToMesh.c
+
+	usage:
+	data_mesh=InterpFromGridToMesh(x,y,data,x_mesh,y_mesh);
+	
+	where:
+
+		input:
+		x,y: coordinates of matrix data
+		data - matrix holding the data to be interpolated onto the mesh.
+		x_mesh,y_mesh: coordinates of the mesh vertices onto which we interpolate.
+		
+		output: 
+		data_mesh:  vector of mesh interpolated data.
+*/
+	
+#include "./InterpFromGridToMesh.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+
+	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: */
+	Vec  data_mesh=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	//CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InterpFromGridToMeshUsage);
+	if((nlhs!=NLHS) || (nrhs!=6 && nrhs!=7)){
+		InterpFromGridToMeshUsage();
+		_error_(" usage. See above");
+	}
+
+	/*Input datasets: */
+	FetchMatlabData(&x,&x_rows,NULL,XHANDLE);
+	FetchMatlabData(&y,&y_rows,NULL,YHANDLE);
+	FetchMatlabData(&data,&data_rows,&data_cols,DATAHANDLE);
+	FetchMatlabData(&x_mesh,&x_mesh_rows,NULL,XMESHHANDLE);
+	FetchMatlabData(&y_mesh,&y_mesh_rows,NULL,YMESHHANDLE);
+	FetchMatlabData(&default_value,DEFAULTHANDLE);
+
+	/* Run core computations: */
+	if(nrhs==7){
+		FetchMatlabData(&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: */
+	WriteMatlabData(DATAMESH,data_mesh);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void InterpFromGridToMeshUsage(void)
+{
+	_printf_(true,"INTERPFROMGRIDTOMESH - interpolation from a grid onto a list of points\n");
+	_printf_(true,"\n");
+	_printf_(true,"   This function is a multi-threaded mex file that interpolates a field\n");
+	_printf_(true,"   defined on a grid onto a list of points\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"      data_mesh=InterpFromGridToMesh(x,y,data,x_mesh,y_mesh,default_value);\n");
+	_printf_(true,"\n");
+	_printf_(true,"      data: matrix holding the data to be interpolated onto the mesh.\n");
+	_printf_(true,"      x,y: coordinates of matrix data. (x and y must be in increasing order)\n");
+	_printf_(true,"      x_mesh,y_mesh: coordinates of the points onto which we interpolate.\n");
+	_printf_(true,"      default_value: default value if no data is found (holes).\n");
+	_printf_(true,"      data_mesh: vector of mesh interpolated data.\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Example:\n");
+	_printf_(true,"      load('velocities.mat');\n");
+	_printf_(true,"      md.inversion.vx_obs=InterpFromGridToMesh(x_n,y_m,vx,md.mesh.x,md.mesh.y,0);\n");
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InterpFromGridToMesh/InterpFromGridToMesh.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InterpFromGridToMesh/InterpFromGridToMesh.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InterpFromGridToMesh/InterpFromGridToMesh.h	(revision 11330)
@@ -0,0 +1,40 @@
+/*!\file InterpFromGridToMesh.h
+ * \brief: prototype for Data Interpolation mex module.
+ */
+
+#ifndef _InterpFromGridToMesh_H
+#define _InterpFromGridToMesh_H
+
+/* local prototypes: */
+void InterpFromGridToMeshUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InterpFromGridToMesh"
+
+#undef CLEANUP
+#define CLEANUP InterpFromGridToMeshLocalCleanup();
+
+
+/* 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]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  6
+
+#endif  /* _INTERPFROMGRIDTOMESH_H */
Index: /issm/trunk-jpl-damage/src/mex/InterpFromMesh2d/InterpFromMesh2d.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 11330)
@@ -0,0 +1,169 @@
+/*!\file InterpFromMesh2d.c
+ * \brief: data interpolation from a list of (x,y,values) into mesh vertices
+ 
+	InterpFromMesh2d.c
+
+	usage:
+	data_mesh=InterpFromMesh2d(index,x,y,data,x_mesh,y_mesh);
+	
+	where:
+
+		input:
+		x,y: coordinates of matrix data
+		data - matrix holding the data to be interpolated onto the mesh.
+		x_mesh,y_mesh: coordinates of the mesh vertices onto which we interpolate.
+		
+		output: 
+		data_mesh:  vector of mesh interpolated data.
+
+*/
+	
+#include "./InterpFromMesh2d.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+
+	/*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
+	mxArray*  matlabstructure=NULL;
+	Contour** contours=NULL;
+	int       numcontours;
+	Contour*  contouri=NULL;
+	int       i;
+
+	/*Intermediary*/
+	int nods_data;
+	int nels_data;
+	int nods_prime;
+
+	/* output: */
+	Vec  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: */
+	FetchMatlabData(&index_data,&index_data_rows,&dummy,INDEXHANDLE);
+	FetchMatlabData(&x_data,&x_data_rows,NULL,XHANDLE);
+	FetchMatlabData(&y_data,&y_data_rows,NULL,YHANDLE);
+	FetchMatlabData(&data,&data_rows,&data_cols,DATAHANDLE);
+	FetchMatlabData(&x_prime,&x_prime_rows,NULL,XPRIMEHANDLE);
+	FetchMatlabData(&y_prime,&y_prime_rows,NULL,YPRIMEHANDLE);
+
+	if(nrhs>=7){
+		/*default values: */
+		FetchMatlabData(&default_values,&num_default_values,DEFAULTHANDLE);
+	}
+	else{
+		default_values=NULL;
+		num_default_values=0;
+	}
+
+	if(nrhs>=8){
+		
+		/*Call expread on filename to build a contour array in the matlab workspace: */
+		mexCallMATLAB( 1, &matlabstructure, 1, (mxArray**)&FILENAME, "expread");
+
+		/*contours: */
+		numcontours=mxGetNumberOfElements(matlabstructure);
+		contours=(Contour**)xmalloc(numcontours*sizeof(Contour*));
+		for(i=0;i<numcontours;i++){
+			//allocate
+			contouri=(Contour*)xmalloc(sizeof(Contour));
+			//retrieve dimension of this contour.
+			contouri->nods=(int)mxGetScalar(mxGetField(matlabstructure,i,"nods"));
+			//set pointers.
+			contouri->x=mxGetPr(mxGetField(matlabstructure,i,"x"));
+			contouri->y=mxGetPr(mxGetField(matlabstructure,i,"y"));
+			*(contours+i)=contouri;
+		}
+
+		/* Debugging of contours :{{{1*/
+		/*for(i=0;i<numcontours;i++){
+		  printf("\nContour echo: contour number  %i / %i\n",i+1,numcontours);
+		  contouri=*(contours+i);
+		  printf("   Number of vertices %i\n",contouri->nods);
+		  for (j=0;j<contouri->nods;j++){
+		  printf("   %lf %lf\n",*(contouri->x+j),*(contouri->y+j));
+		  }
+		  }*/
+		/*}}}*/
+	}
+	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: */
+	WriteMatlabData(DATAPRIME,data_prime);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void InterpFromMesh2dUsage(void)
+{
+	_printf_(true,"   usage:\n");
+	_printf_(true,"         data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime);\n\n");
+	_printf_(true,"      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value);\n\n");
+	_printf_(true,"      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value,contourname);\n\n");
+	_printf_(true,"   where:\n");
+	_printf_(true,"      x,y: coordinates of the nodes where data is defined\n");
+	_printf_(true,"      index: index of the mesh where data is defined\n");
+	_printf_(true,"      data - vector holding the data to be interpolated onto the points.\n");
+	_printf_(true,"      x_prime,y_prime: coordinates of the mesh vertices onto which we interpolate.\n");
+	_printf_(true,"      default_value: a scalar or vector of size length(x_prime).\n");
+	_printf_(true,"      contourname: linear interpolation will happen on all x_interp,y_interp inside the contour, default value will be adopted on the rest of the mesh.\n");
+	_printf_(true,"      data_prime:  vector of prime interpolated data.\n");
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InterpFromMesh2d/InterpFromMesh2d.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InterpFromMesh2d/InterpFromMesh2d.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InterpFromMesh2d/InterpFromMesh2d.h	(revision 11330)
@@ -0,0 +1,38 @@
+/*!\file InterpFromMesh2d.h
+ * \brief: prototype for Data Interpolation mex module.
+ */
+
+#ifndef _INTERPFROMMESH2D_H
+#define _INTERPFROMMESH2D_H
+
+/* local prototypes: */
+void InterpFromMesh2dUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InterpFromMesh2d"
+
+#undef CLEANUP
+#define CLEANUP InterpFromMesh2dLocalCleanup();
+
+/* 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]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+
+#endif  /* _INTERPFROMMESH2D_H */
Index: /issm/trunk-jpl-damage/src/mex/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 11330)
@@ -0,0 +1,79 @@
+/*\file InterpFromMeshToGrid.c
+ *\brief: compute diff between observed and modeled velocity
+ */
+
+#include "./InterpFromMeshToGrid.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	double* index=NULL;
+	int     nel;
+	double* x=NULL;
+	int     nods;
+	double* y=NULL;
+	double* meshdata=NULL;
+	int     meshdata_length;
+	double  xmin;
+	double  ymax;
+	double  xposting;
+	double  yposting;
+	int     nlines,ncols;
+	double  default_value;
+
+	/* output datasets: */
+	double* griddata=NULL;
+	double* x_m=NULL;
+	double* y_m=NULL;
+
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InterpFromMeshToGridUsage);
+
+	/*Input datasets: */
+	FetchMatlabData(&index,&nel,NULL,INDEX);
+	FetchMatlabData(&x,&nods,NULL,X);
+	FetchMatlabData(&y,NULL,NULL,Y);
+	FetchMatlabData(&meshdata,&meshdata_length,NULL,MESHDATA);
+	FetchMatlabData(&xmin,XMIN);
+	FetchMatlabData(&ymax,YMAX);
+	FetchMatlabData(&xposting,XPOSTING);
+	FetchMatlabData(&yposting,YPOSTING);
+	FetchMatlabData(&nlines,NLINES);
+	FetchMatlabData(&ncols,NCOLS);
+	FetchMatlabData(&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: */
+	WriteMatlabData(XM,x_m,ncols);
+	WriteMatlabData(YM,y_m,nlines);
+	WriteMatlabData(GRIDDATA,griddata,nlines,ncols);
+
+	/*Free ressources: */
+	//let matlab do this.
+	
+	/*end module: */
+	MODULEEND();
+}
+
+void InterpFromMeshToGridUsage(void)
+{
+	_printf_(true,"INTERPFROMMESHTOGRID - interpolation of a data defined on a mesh onto a grid\n");
+	_printf_(true,"\n");
+	_printf_(true,"   This function is a multi-threaded mex file that interpolates a field\n");
+	_printf_(true,"   defined on a triangular mesh onto a regular grid\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"      [x_m,y_m,griddata]=InterpFromMeshToGrid(index,x,y,data,xmin,ymax,xposting,yposting,nlines,ncols,default_value)\n");
+	_printf_(true,"\n");
+	_printf_(true,"      index,x,y: delaunay triangulation defining the mesh.\n");
+	_printf_(true,"      meshdata: vertex values of data to be interpolated.\n");
+	_printf_(true,"      xmin,ymax,posting,nlines,ncols: parameters that define the grid\n");
+	_printf_(true,"      default_value: value of points located out of the mesh.\n");
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InterpFromMeshToGrid/InterpFromMeshToGrid.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InterpFromMeshToGrid/InterpFromMeshToGrid.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InterpFromMeshToGrid/InterpFromMeshToGrid.h	(revision 11330)
@@ -0,0 +1,44 @@
+
+/*
+	InterpFromMeshToGrid.h
+*/
+
+
+#ifndef _INTERPFROMMESHTOGRID_H
+#define _INTERPFROMMESHTOGRID_H
+
+/* local prototypes: */
+void InterpFromMeshToGridUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InterpFromMeshToGrid"
+
+/* serial input macros: */
+#define INDEX (mxArray*)prhs[0]
+#define X (mxArray*)prhs[1]
+#define Y (mxArray*)prhs[2]
+#define MESHDATA (mxArray*)prhs[3]
+#define XMIN (mxArray*)prhs[4]
+#define YMAX (mxArray*)prhs[5]
+#define XPOSTING (mxArray*)prhs[6]
+#define YPOSTING (mxArray*)prhs[7]
+#define NLINES (mxArray*)prhs[8]
+#define NCOLS (mxArray*)prhs[9]
+#define DEFAULTVALUE (mxArray*)prhs[10]
+
+/* serial output macros: */
+#define XM (mxArray**)&plhs[0]
+#define YM (mxArray**)&plhs[1]
+#define GRIDDATA (mxArray**)&plhs[2]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  3
+#undef NRHS
+#define NRHS  11
+
+#endif  /* _INTERPFROMMESHTOGRID_H*/
Index: /issm/trunk-jpl-damage/src/mex/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 11330)
@@ -0,0 +1,162 @@
+/*\file InterpFromMeshToMesh2d.c
+ *\brief: bamg module.
+ */
+#include "./InterpFromMeshToMesh2d.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	int i;
+
+	/*input: */
+	double* index=NULL;
+	int     index_cols;
+
+	double* x_data=NULL;
+	int     x_data_rows;
+
+	double* y_data=NULL;
+	int     y_data_rows;
+
+	double* data=NULL; 
+	int     data_rows;
+	int     data_cols;
+
+	double* x_interp=NULL;
+	double* y_interp=NULL;
+
+	int     x_interp_rows;
+	int     y_interp_rows;
+
+	double* default_values=NULL;
+	int     num_default_values=0;
+
+	//contours
+	mxArray*  matlabstructure=NULL;
+	Contour** contours=NULL;
+	int       numcontours;
+	Contour*  contouri=NULL;
+
+	/*Intermediary*/
+	int nods_data;
+	int nels_data;
+	int nods_interp;
+	int verbose=0;
+
+	/* output: */
+	double* data_interp=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if(nlhs!=NLHS){
+		InterpFromMeshToMesh2dUsage();
+		_error_("InterpFromMeshToMesh2dUsage usage error");
+	}
+	if((nrhs!=6) & (nrhs!=8)){
+		InterpFromMeshToMesh2dUsage();
+		_error_("InterpFromMeshToMesh2dUsage usage error");
+	}
+
+	/*Input datasets: */
+	if (verbose) printf("Fetching inputs\n");
+	FetchMatlabData(&index,&nels_data,&index_cols,INDEXHANDLE);
+	FetchMatlabData(&x_data,&x_data_rows,NULL,XHANDLE);
+	FetchMatlabData(&y_data,&y_data_rows,NULL,YHANDLE);
+	FetchMatlabData(&data,&data_rows,&data_cols,DATAHANDLE);
+	FetchMatlabData(&x_interp,&x_interp_rows,NULL,XINTERPHANDLE);
+	FetchMatlabData(&y_interp,&y_interp_rows,NULL,YINTERPHANDLE);
+
+	if(nrhs==8){
+		
+		/*Call expread on filename to build a contour array in the matlab workspace: */
+		mexCallMATLAB( 1, &matlabstructure, 1, (mxArray**)&FILENAME, "expread");
+
+		/*default values: */
+		FetchMatlabData(&default_values,&num_default_values,DEFAULTHANDLE);
+
+		/*contours: */
+		numcontours=mxGetNumberOfElements(matlabstructure);
+		contours=(Contour**)xmalloc(numcontours*sizeof(Contour*));
+		for(i=0;i<numcontours;i++){
+			//allocate
+			contouri=(Contour*)xmalloc(sizeof(Contour));
+			//retrieve dimension of this contour.
+			contouri->nods=(int)mxGetScalar(mxGetField(matlabstructure,i,"nods"));
+			//set pointers.
+			contouri->x=mxGetPr(mxGetField(matlabstructure,i,"x"));
+			contouri->y=mxGetPr(mxGetField(matlabstructure,i,"y"));
+			*(contours+i)=contouri;
+		}
+
+		/* Debugging of contours :{{{1*/
+		/*for(i=0;i<numcontours;i++){
+		  printf("\nContour echo: contour number  %i / %i\n",i+1,numcontours);
+		  contouri=*(contours+i);
+		  printf("   Number of vertices %i\n",contouri->nods);
+		  for (j=0;j<contouri->nods;j++){
+		  printf("   %lf %lf\n",*(contouri->x+j),*(contouri->y+j));
+		  }
+		  }*/
+		/*}}}*/
+	}
+	else{
+		num_default_values=0;
+		default_values=NULL;
+		numcontours=0;
+		contours=NULL;
+	}
+
+	/*some checks*/
+	if (verbose) printf("Checking inputs\n");
+	if (x_data_rows!=y_data_rows){
+		_error_("vectors x and y should have the same length!");
+	}
+	if (x_interp_rows!=y_interp_rows){
+		_error_("vectors x_interp and y_interp should have the same length!");
+	}
+	if (index_cols!=3){
+		_error_("index should have 3 columns (input provided has %i columns)",index_cols);
+	}
+
+	/*get number of elements and number of nodes in the data*/
+	nods_data=x_data_rows;
+	nods_interp=x_interp_rows;
+
+	/* Run core computations: */
+	if (verbose) printf("Call core\n");
+	InterpFromMeshToMesh2dx(&data_interp,index,x_data,y_data,nods_data,nels_data,data,data_rows,data_cols,x_interp,y_interp,nods_interp,default_values,num_default_values,contours,numcontours);
+
+	/*Write data: */
+	WriteMatlabData(DATAINTERP,data_interp,nods_interp,data_cols);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void InterpFromMeshToMesh2dUsage(void)
+{
+	_printf_(true,"INTERFROMMESHTOMESH2D - interpolation from a 2d triangular mesh onto a list of point\n");
+	_printf_(true,"\n");
+	_printf_(true,"   This function is a multi-threaded mex file that interpolates a field\n");
+	_printf_(true,"   defined on a triangular mesh onto a list of point\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"         data_interp=InterpFromMeshToMesh2d(index,x,y,data,x_interp,y_interp);\n");
+	_printf_(true,"      or data_interp=InterpFromMeshToMesh2d(index,x,y,data,x_interp,y_interp,default_value,contourname);\n");
+	_printf_(true,"\n");
+	_printf_(true,"      index: index of the mesh where data is defined\n");
+	_printf_(true,"      x,y: coordinates of the nodes where data is defined\n");
+	_printf_(true,"      data: matrix holding the data to be interpolated onto the mesh. (one column per field)\n");
+	_printf_(true,"      x_interp,y_interp: coordinates of the points onto which we interpolate.\n");
+	_printf_(true,"      if default_value and contourname not specified: linear interpolation will happen on all x_interp,y_interp.\n");
+	_printf_(true,"      if (default_value,contourname) specified: linear interpolation will happen on all x_interp,y_interp inside the contour, default value will be adopted on the rest of the mesh.\n");
+	_printf_(true,"      note that default_value is either a scalar, or a vector of size  length(x_interp)\n");
+	_printf_(true,"      data_interp: vector of mesh interpolated data.\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Example:\n");
+	_printf_(true,"      load('temperature.mat');\n");
+	_printf_(true,"      md.initialization.temperature=InterpFromMeshToMesh2d(index,x,y,temperature,md.mesh.x,md.mesh.y);\n");
+	_printf_(true,"      md.initialization.temperature=InterpFromMeshToMesh2d(index,x,y,temperature,md.mesh.x,md.mesh.y,253,'Contour.exp');\n");
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h	(revision 11330)
@@ -0,0 +1,36 @@
+/*!\file InterpFromMeshToMesh2d.h
+ * \brief: prototype for Data Interpolation mex module.
+ */
+
+#ifndef _INTERPFROMMESHTOMESH2d_H
+#define _INTERPFROMMESHTOMESH2d_H
+
+/* local prototypes: */
+void InterpFromMeshToMesh2dUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InterpFromMeshToMesh2d"
+
+
+/* serial input macros: */
+#define INDEXHANDLE prhs[0]
+#define XHANDLE prhs[1]
+#define YHANDLE prhs[2]
+#define DATAHANDLE prhs[3]
+#define XINTERPHANDLE prhs[4]
+#define YINTERPHANDLE prhs[5]
+#define DEFAULTHANDLE prhs[6]
+#define FILENAME prhs[7]
+
+/* serial output macros: */
+#define DATAINTERP (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 11330)
@@ -0,0 +1,119 @@
+/*!\file InterpFromMeshToMesh3d.c
+ * \brief: data interpolation from a list of (x,y,values) into mesh vertices
+ 
+	InterpFromMeshToMesh3d.c
+
+	usage:
+	data_mesh=InterpFromMeshToMesh3d(index,x,y,z,data,x_mesh,y_mesh,z_mesh);
+	
+	where:
+
+		input:
+		x,y,z: coordinates of matrix data
+		data - matrix holding the data to be interpolated onto the mesh.
+		x_mesh,y_mesh,z_mesh: coordinates of the mesh vertices onto which we interpolate.
+		
+		output: 
+		data_mesh:  vector of mesh interpolated data.
+
+*/
+	
+#include "./InterpFromMeshToMesh3d.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+
+	/*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: */
+	Vec  data_prime=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InterpFromMeshToMesh3dUsage);
+
+	/*Input datasets: */
+	FetchMatlabData(&index_data,&index_data_rows,NULL,INDEXHANDLE);
+	FetchMatlabData(&x_data,&x_data_rows,NULL,XHANDLE);
+	FetchMatlabData(&y_data,&y_data_rows,NULL,YHANDLE);
+	FetchMatlabData(&z_data,&z_data_rows,NULL,ZHANDLE);
+	FetchMatlabData(&data,&data_rows,&data_cols,DATAHANDLE);
+	FetchMatlabData(&x_prime,&x_prime_rows,NULL,XPRIMEHANDLE);
+	FetchMatlabData(&y_prime,&y_prime_rows,NULL,YPRIMEHANDLE);
+	FetchMatlabData(&z_prime,&z_prime_rows,NULL,ZPRIMEHANDLE);
+	FetchMatlabData(&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: */
+	WriteMatlabData(DATAPRIME,data_prime);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void InterpFromMeshToMesh3dUsage(void)
+{
+	_printf_(true,"INTERPFROMMESHTOMESH3D - interpolation from a 3d hexahedron mesh onto a list of point\n");
+	_printf_(true,"\n");
+	_printf_(true,"   This function is a multi-threaded mex file that interpolates a field\n");
+	_printf_(true,"   defined on a triangular mesh onto a list of point\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"      data_prime=InterpFromMeshToMesh3d(index,x,y,z,data,x_prime,y_prime,z_prime,default_value);\n");
+	_printf_(true,"\n");
+	_printf_(true,"      index: index of the mesh where data is defined\n");
+	_printf_(true,"      x,y,z: coordinates of the nodes where data is defined\n");
+	_printf_(true,"      data: matrix holding the data to be interpolated onto the mesh.\n");
+	_printf_(true,"      x_prime,y_prime,z_prime: coordinates of the points onto which we interpolate.\n");
+	_printf_(true,"      default_value: default value if no data is found (holes).\n");
+	_printf_(true,"      data_prime: vector of mesh interpolated data.\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Example:\n");
+	_printf_(true,"      load('temperature.mat');\n");
+	_printf_(true,"      md.initialization.temperature=InterpFromMeshToMesh3d(index,x,y,z,temperature,md.mesh.x,md.mesh.y,md.mesh.z,253);\n");
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h	(revision 11330)
@@ -0,0 +1,42 @@
+/*!\file InterpFromMeshToMesh3d.h
+ * \brief: prototype for Data Interpolation mex module.
+ */
+
+#ifndef _INTERPFROMMESH3D_H
+#define _INTERPFROMMESH3D_H
+
+/* local prototypes: */
+void InterpFromMeshToMesh3dUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InterpFromMeshToMesh3d"
+
+#undef CLEANUP
+#define CLEANUP InterpFromMeshToMesh3dLocalCleanup();
+
+
+/* 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]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  9
+
+#endif  /* _INTERPFROMMESHTOMESH3D_H */
Index: /issm/trunk-jpl-damage/src/mex/KMLFileRead/KMLFileRead.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/KMLFileRead/KMLFileRead.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/KMLFileRead/KMLFileRead.cpp	(revision 11330)
@@ -0,0 +1,151 @@
+/*\file KMLFileRead.c
+ *\brief: KML file reader module.
+ */
+#include "./KMLFileRead.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	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: */
+	if (verbose) printf("Fetching inputs:\n");
+	FetchMatlabData(&filnam,FILENAME);
+	if (verbose) printf("  filnam =\"%s\"\n",filnam);
+
+	if (verbose) printf("Parsing options:\n");
+	options=new Options(NRHS,nrhs,prhs);
+	if (options->Size()) for(i=0;i<options->Size();i++) ((Option*)options->GetObjectByOffset(i))->DeepEcho();
+	options->Get(&echo    ,"echo"    ,"off");
+	options->Get(&deepecho,"deepecho","off");
+	options->Get(&write   ,"write"   ,"off");
+
+	/*some checks*/
+	if (verbose) printf("Checking inputs:\n");
+
+	if (!strlen(filnam))
+		strcpy(filnam,"stdout");
+
+	if (verbose) printf("Opening file \"%s\".\n",filnam);
+	fidi=fopen(filnam,"r");
+
+	/* Run core computations: */
+	if (verbose) printf("Calling core:\n");
+	kobj=KMLFileReadx(fidi);
+
+	if (verbose) printf("Closing file \"%s\".\n",filnam);
+	fclose(fidi);
+
+	if (kobj) {
+		if (!strncmp(echo    ,"on",2) || !strncmp(echo    ,"y",1))
+			kobj->Echo();
+		if (!strncmp(deepecho,"on",2) || !strncmp(deepecho,"y",1))
+			kobj->DeepEcho();
+		if (strncmp(write,"off",3) && strncmp(write,"no",2)) {
+			if (!strncmp(write,"on",2) || !strncmp(write,"yes",3) || !strncmp(write,"stdout",6)) {
+				kobj->Write(stdout,"");
+			}
+			else {
+				if (verbose) printf("Opening file \"%s\".\n",write);
+				fido=fopen(write,"w");
+				kobj->Write(fido,"");
+				if (verbose) printf("Closing file \"%s\".\n",write);
+				ierror=fclose(fido);
+			}
+		}
+
+		delete kobj;
+	}
+
+	/*Write data: */
+	WriteMatlabData(ERRORFLAG,ierror);
+
+	/*Clean-up*/
+	xfree((void**)&write);
+	xfree((void**)&deepecho);
+	xfree((void**)&echo);
+	delete options;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void KMLFileReadUsage(void)
+{
+	_printf_(true,"KMLFileRead - KML file reader module:\n");
+	_printf_(true,"\n");
+	_printf_(true,"   This module reads a KML file.\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"      [ierror]=KMLFileRead(kmlfile,'param name',param,...);\n");
+	_printf_(true,"\n");
+	_printf_(true,"      kmlfile      file name of kml file to be read (char)\n");
+	_printf_(true,"\n");
+	_printf_(true,"      echo         echo command (char, optional, 'off'/'on')\n");
+	_printf_(true,"      deepecho     deep echo command (char, optional, 'off'/'on')\n");
+	_printf_(true,"      write        write command (char, optional, 'off'/'stdout'/kmlfile)\n");
+	_printf_(true,"\n");
+	_printf_(true,"      ierror       return code (non-zero for error)\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Examples:\n");
+	_printf_(true,"      [ierror]=KMLFileRead('file.kml','deepecho','on');\n");
+	_printf_(true,"      [ierror]=KMLFileRead('filin.kml','echo','on','write','filout.kml');\n");
+	_printf_(true,"\n");
+}
+
Index: /issm/trunk-jpl-damage/src/mex/KMLFileRead/KMLFileRead.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/KMLFileRead/KMLFileRead.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/KMLFileRead/KMLFileRead.h	(revision 11330)
@@ -0,0 +1,31 @@
+/*!\file KMLFileRead.h
+ * \brief: prototype for KML file reader mex module.
+ */
+
+#ifndef _KMLFILEREAD_H
+#define _KMLFILEREAD_H
+
+/* local prototypes: */
+void KMLFileReadUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "KMLFileRead"
+
+
+/* serial input macros: */
+#define FILENAME      prhs[0]
+
+/* serial output macros: */
+#define ERRORFLAG (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NRHS
+#define NRHS  1
+#undef NLHS
+#define NLHS  1
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/KMLMeshWrite/KMLMeshWrite.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/KMLMeshWrite/KMLMeshWrite.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/KMLMeshWrite/KMLMeshWrite.cpp	(revision 11330)
@@ -0,0 +1,198 @@
+/*\file KMLMeshWrite.c
+ *\brief: KML mesh writer module.
+ */
+#include "./KMLMeshWrite.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	int i,j,nnodes=0,verbose=1;
+
+	/*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*   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: */
+	if (verbose) printf("Fetching inputs:\n");
+	FetchMatlabData(&name,NAME);
+	if (verbose) printf("  name   =\"%s\"\n",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=(char *) xmalloc((mxGetNumberOfElements(notesi)+1)*sizeof(char));
+					mxGetString(notesi,notes,mxGetNumberOfElements(notesi)+1);
+				}
+				else {
+/*  note that strlen does not include trailing null  */
+					notes=(char *) xrealloc(notes,(strlen(notes)+1+mxGetNumberOfElements(notesi)+1)*sizeof(char));
+					strcat(notes,"\n");
+					mxGetString(notesi,&notes[strlen(notes)],mxGetNumberOfElements(notesi)+1);
+				}
+			}
+		}
+	}
+	else
+		FetchMatlabData(&notes,NOTES);
+	if (verbose) printf("  notes  =\"%s\"\n",notes);
+
+	FetchMatlabData(&elem,&melem,&nelem,ELEMHANDLE);
+	if (verbose) printf("  elem   =size [%d x %d]\n",melem,nelem);
+	FetchMatlabData(&nodecon,&mncon,&nncon,NODECONHANDLE);
+	if (verbose) printf("  nodecon=size [%d x %d]\n",mncon,nncon);
+	FetchMatlabData(&lat,&mlat,&nlat,LATHANDLE);
+	llat=mlat*nlat;
+	if (verbose) printf("  lat    =length [%d]\n",llat);
+	FetchMatlabData(&lng,&mlng,&nlng,LNGHANDLE);
+	llng=mlng*nlng;
+	if (verbose) printf("  lng    =length [%d]\n",llng);
+	FetchMatlabData(&part,&mprt,&nprt,PARTHANDLE);
+	lprt=mprt*nprt;
+	if (verbose) printf("  part   =length [%d]\n",lprt);
+	FetchMatlabData(&data,&mdata,&ndata,DATAHANDLE);
+	if (verbose) printf("  data   =size [%d x %d]\n",mdata,ndata);
+	FetchMatlabData(&cmap,&mcmap,&ncmap,CMAPHANDLE);
+	if (verbose) printf("  cmap   =size [%d x %d]\n",mcmap,ncmap);
+	FetchMatlabData(&filnam,FILENAME);
+	if (verbose) printf("  filnam =\"%s\"\n",filnam);
+
+	if (verbose) printf("Parsing options:\n");
+	options=new Options(NRHS,nrhs,prhs);
+//	if (options->Size()) for(i=0;i<options->Size();i++) ((Option*)options->GetObjectByOffset(i))->DeepEcho();
+
+	/*some checks*/
+	if (verbose) printf("Checking inputs:\n");
+
+	for (i=0; i<melem*nelem; i++)
+		if (elem[i] > nnodes)
+			nnodes=elem[i];
+	if (verbose) printf("  nnodes =%d\n",nnodes);
+	if (part)
+		for (i=0; i<lprt; i++)
+			if (part[i]+1 > nparts)
+				nparts=part[i]+1;
+	if (verbose) printf("  nparts =%d\n",nparts);
+
+	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");
+
+	if (verbose) printf("Opening file \"%s\".\n",filnam);
+	fid=fopen(filnam,"w");
+
+	/* Run core computations: */
+	if (verbose) printf("Calling core:\n");
+	KMLMeshWritex(&ierror,
+				  name,
+				  notes,
+				  elem,melem,nelem,
+				  nodecon,mncon,nncon,
+				  lat,lng,
+				  part,
+				  data,mdata,ndata,
+				  cmap,mcmap,ncmap,
+				  fid);
+
+	if (verbose) printf("Closing file \"%s\".\n",filnam);
+	fclose(fid);
+
+	/*Write data: */
+	WriteMatlabData(ERRORFLAG,ierror);
+
+	/*Clean-up*/
+	delete options;
+	if (mxIsCell(NOTES) && notes) xfree((void**)&notes);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void KMLMeshWriteUsage(void)
+{
+	_printf_(true,"KMLMeshWrite - KML mesh writer module:\n");
+	_printf_(true,"\n");
+	_printf_(true,"   This module writes the mesh of a model as KML polygons into the specified KML file.\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"      ierror=KMLMeshWrite(name,notes,elem,nodecon,lat,long,part,data,cmap,kmlfile);\n");
+	_printf_(true,"\n");
+	_printf_(true,"      name       model name (string, may be empty)\n");
+	_printf_(true,"      notes      model notes (string or cell array of strings, may be empty)\n");
+	_printf_(true,"      elem       elements (double array)\n");
+	_printf_(true,"      nodecon    nodal connectivity array (double array, may be empty)\n");
+	_printf_(true,"      lat        nodal latititudes (double vector)\n");
+	_printf_(true,"      long       nodal longitudes (double vector)\n");
+	_printf_(true,"      part       nodal partitions (double vector, may be empty)\n");
+	_printf_(true,"      data       nodal or element data (double vector, may be empty)\n");
+	_printf_(true,"      cmap       color map (double nx3 array, may be empty)\n");
+	_printf_(true,"      kmlfile    KML file name (string)\n");
+	_printf_(true,"\n");
+	_printf_(true,"      ierror     error flag (double, non-zero for error)\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Example:\n");
+	_printf_(true,"      KMLMeshWrite(md.name,md.notes,md.elements,md.nodeconnectivity,md.lat,md.long,md.part,md.fm_criterion,options.cmap,filekml);\n");
+	_printf_(true,"\n");
+}
+
Index: /issm/trunk-jpl-damage/src/mex/KMLMeshWrite/KMLMeshWrite.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/KMLMeshWrite/KMLMeshWrite.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/KMLMeshWrite/KMLMeshWrite.h	(revision 11330)
@@ -0,0 +1,40 @@
+/*!\file KMLMeshWrite.h
+ * \brief: prototype for KML mesh writer mex module.
+ */
+
+#ifndef _KMLMESHWRITE_H
+#define _KMLMESHWRITE_H
+
+/* local prototypes: */
+void KMLMeshWriteUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "KMLMeshWrite"
+
+
+/* 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]
+
+/* serial arg counts: */
+#undef NRHS
+#define NRHS 10
+#undef NLHS
+#define NLHS  1
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/KMLOverlay/KMLOverlay.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/KMLOverlay/KMLOverlay.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/KMLOverlay/KMLOverlay.cpp	(revision 11330)
@@ -0,0 +1,149 @@
+/*\file KMLOverlay.c
+ *\brief: KML file overlay mex module.
+ */
+#include "./KMLOverlay.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	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: */
+	if (verbose) printf("Fetching inputs:\n");
+	FetchMatlabData(&filkml,FILENAME);
+	if (verbose) printf("  filkml=\"%s\"\n",filkml);
+
+	if (verbose) printf("Parsing options:\n");
+	options=new Options(NRHS,nrhs,prhs);
+//	if (options->Size()) for(i=0;i<options->Size();i++) ((Option*)options->GetObjectByOffset(i))->DeepEcho();
+	options->Get(&lataxis ,&nlat ,"lataxis" );
+	if (verbose && lataxis) for (i=0; i<nlat; i++) printf("  lataxis [%d]=%g\n",i,lataxis[i]);
+	options->Get(&longaxis,&nlong,"longaxis");
+	if (verbose && longaxis) for (i=0; i<nlong; i++) printf("  longaxis[%d]=%g\n",i,longaxis[i]);
+//	((Option*)options->GetOption("images"))->DeepEcho();
+	options->Get(&pimages,&nimages,"images");
+	if (verbose && pimages) for (i=0; i<nimages; i++) printf("  pimages[%d]=\"%s\"\n",i,pimages[i]);
+	options->Get(&dzip,"zip",0.);
+	if (verbose) printf("  dzip=%g\n",dzip);
+
+	/*some checks*/
+	if (verbose) printf("Checking inputs:\n");
+
+	if (nlat  != 2) _error_("Latitudinal axes \"lataxis\" require two double values, not %d.",nlat);
+	if (nlong != 2) _error_("Longitudinal axes \"longaxis\" require two double values, not %d.",nlong);
+	if (!nimages) _error_("No image files provided.");
+
+	if ((int)dzip) {
+		filkmz=filkml;
+		filkml=(char *) xmalloc(8*sizeof(char));
+		strcpy(filkml,"doc.kml");
+	}
+
+	if (!strlen(filkml))
+		strcpy(filkml,"stdout");
+
+	if (verbose) printf("Opening kml overlay file \"%s\".\n",filkml);
+	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 \"%s\".\n",filkml);
+	fclose(fid);
+
+	/* Create kmz file, if specified: */
+	if ((int)dzip) {
+		czip=(char *) xmalloc((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 *) xrealloc(czip,(strlen(czip)+1+strlen(pimages[i])+1)*sizeof(char));
+				strcat(czip," ");
+				strcat(czip,pimages[i]);
+			}
+		if (verbose) printf("Zipping file \"%s\".\n",filkmz);
+		if (verbose) printf("%s\n",czip);
+
+		if (mexEvalString(czip)) _error_("Error zipping file \"%s\".",filkmz);
+		xfree((void**)&czip);
+		xfree((void**)&filkmz);
+	}
+
+	/*Write data: */
+	WriteMatlabData(ERRORFLAG,ierror);
+
+	/*Clean-up*/
+	if (pimages) {
+		for (i=nimages; i>0; i--) xfree((void**)&(pimages[i-1]));
+		xfree((void**)&pimages);
+	}
+	xfree((void**)&longaxis);
+	xfree((void**)&lataxis);
+	delete options;
+	xfree((void**)&filkml);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void KMLOverlayUsage(void)
+{
+	_printf_(true,"KMLOverlay - KML file overlay module:\n");
+	_printf_(true,"\n");
+	_printf_(true,"   This module reads a list of image files and writes a KML or KMZ overlay file.\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"      ierror=KMLOverlay(kmlfile,'param name',param,...);\n");
+	_printf_(true,"\n");
+	_printf_(true,"      kmlfile     KML or KMZ file name (string)\n");
+	_printf_(true,"\n");
+	_printf_(true,"      lataxis     latitude axis (double vector [south north], required)\n");
+	_printf_(true,"      longaxis    longitude axis (double vector [west east], required)\n");
+	_printf_(true,"      images      relative or http image file names (string or array of strings or cell array of strings, required)\n");
+	_printf_(true,"      zip         flag to zip the doc.kml and image files into kmzfile (double, non-zero for kmz)\n");
+	_printf_(true,"\n");
+	_printf_(true,"      ierror     error flag (double, non-zero for error)\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Example:\n");
+	_printf_(true,"      KMLOverlay(kmlfile,'lataxis',[south north],'longaxis',[west east],'images',{'file1.png','http://issm/file2.png'},'zip',1);\n");
+	_printf_(true,"\n");
+}
+
Index: /issm/trunk-jpl-damage/src/mex/KMLOverlay/KMLOverlay.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/KMLOverlay/KMLOverlay.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/KMLOverlay/KMLOverlay.h	(revision 11330)
@@ -0,0 +1,31 @@
+/*!\file KMLOverlay.h
+ * \brief: prototype for KML file overlay mex module.
+ */
+
+#ifndef _KMLOVERLAY_H
+#define _KMLOVERLAY_H
+
+/* local prototypes: */
+void KMLOverlayUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "KMLOverlay"
+
+
+/* serial input macros: */
+#define FILENAME      prhs[0]
+
+/* serial output macros: */
+#define ERRORFLAG (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NRHS
+#define NRHS  1
+#undef NLHS
+#define NLHS  1
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/Kml2Exp/Kml2Exp.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Kml2Exp/Kml2Exp.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Kml2Exp/Kml2Exp.cpp	(revision 11330)
@@ -0,0 +1,106 @@
+/*\file Kml2Exp.c
+ *\brief: kml to exp file conversion mex module.
+ */
+#include "./Kml2Exp.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	int i,verbose=1;
+
+	/*input: */
+	char    *filkml=NULL,*filexp=NULL;
+	int     sgn;
+
+	Options* options=NULL;
+	double   cm=0.,sp=0.;
+
+	/* output: */
+	int     iret=0;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if (nlhs > NLHS) {
+		Kml2ExpUsage();
+		_error_("Kml2Exp usage error");
+	}
+	if (nrhs < NRHS) {
+		Kml2ExpUsage();
+		_error_("Kml2Exp usage error");
+	}
+
+	/*Input datasets: */
+	if (verbose) printf("Fetching inputs:\n");
+	FetchMatlabData(&filkml,KML_IN);
+	if (verbose) printf("  filkml=\"%s\"\n",filkml);
+	FetchMatlabData(&filexp,EXP_IN);
+	if (verbose) printf("  filexp=\"%s\"\n",filexp);
+	FetchMatlabData(&sgn,SGN_IN);
+	if (verbose) printf("  sgn=%d\n",sgn);
+
+	if (verbose) printf("Parsing options:\n");
+	options=new Options(NRHS,nrhs,prhs);
+	if (options->Size()) for(i=0;i<options->Size();i++) ((Option*)options->GetObjectByOffset(i))->DeepEcho();
+	/*  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=%g\n",cm);
+		options->Get(&sp,"standard_parallel");
+		if (verbose) printf("  sp=%g\n",sp);
+	}
+
+	/*some checks*/
+	if (verbose) printf("Checking inputs:\n");
+
+	if (sgn != +1 && sgn != -1) _error_("Hemisphere sgn=%d must be +1 (north) or -1 (south).",sgn);
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=%g must be between -180 (west) and +180 (east) degrees.",cm);
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=%g must be between 0 and 90 degrees (in specified hemisphere).",sp);
+
+	/* Run core computations: */
+	if (verbose) printf("Calling core:\n");
+	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
+		iret=Kml2Expx(filkml,filexp,
+					  sgn,cm,sp);
+	else
+		iret=Kml2Expx(filkml,filexp,
+					  sgn);
+	if (verbose) printf("  iret=%d\n",iret);
+
+	/*Write data: */
+	WriteMatlabData(RET_OUT,iret);
+
+	/*Clean-up*/
+	delete options;
+	xfree((void**)&filexp);
+	xfree((void**)&filkml);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void Kml2ExpUsage(void)
+{
+	_printf_(true,"Kml2Exp - kml to exp file conversion module:\n");
+	_printf_(true,"\n");
+	_printf_(true,"   This module converts a file from kml to exp format.\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"      [ret]=Kml2Exp(filexp,filkml,sgn,'param name',param,...);\n");
+	_printf_(true,"\n");
+	_printf_(true,"      filkml      file name of kml file to be read (char)\n");
+	_printf_(true,"      filexp      file name of exp file to be written (char)\n");
+	_printf_(true,"      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
+	_printf_(true,"\n");
+	_printf_(true,"      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf_(true,"      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf_(true,"\n");
+	_printf_(true,"      ret         return code (non-zero for warning)\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Examples:\n");
+	_printf_(true,"      [ret]=Kml2Exp('file.kml','file.exp', 1);\n");
+	_printf_(true,"      [ret]=Kml2Exp('file.kml','file.exp', 1,'central_meridian',45,'standard_parallel',70);\n");
+	_printf_(true,"      [ret]=Kml2Exp('file.kml','file.exp',-1,'central_meridian', 0,'standard_parallel',71);\n");
+	_printf_(true,"\n");
+}
+
Index: /issm/trunk-jpl-damage/src/mex/Kml2Exp/Kml2Exp.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Kml2Exp/Kml2Exp.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Kml2Exp/Kml2Exp.h	(revision 11330)
@@ -0,0 +1,34 @@
+/*!\file Kml2Exp.h
+ * \brief: prototype for kml to exp file conversion mex module.
+ */
+
+#ifndef _KML2EXP_H
+#define _KML2EXP_H
+
+/* local prototypes: */
+void Kml2ExpUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Kml2Exp"
+
+
+/* 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]
+
+/* serial arg counts: */
+#undef NRHS
+#define NRHS  3
+#undef NLHS
+#define NLHS  1
+
+#endif
+
Index: /issm/trunk-jpl-damage/src/mex/Ll2xy/Ll2xy.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Ll2xy/Ll2xy.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Ll2xy/Ll2xy.cpp	(revision 11330)
@@ -0,0 +1,121 @@
+/*\file Ll2xy.c
+ *\brief: lat/long to x/y coordinate mex module.
+ */
+#include "./Ll2xy.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	int i,verbose=1;
+
+	/*input: */
+	double  *lat=NULL,*lon=NULL;
+	int     nlat,nlon,ncoord;
+	int     sgn;
+
+	Options* options=NULL;
+	double   cm=0.,sp=0.;
+
+	/* output: */
+	double  *x=NULL,*y=NULL;
+	int     iret=0;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if (nlhs > NLHS) {
+		Ll2xyUsage();
+		_error_("Ll2xy usage error");
+	}
+	if (nrhs < NRHS) {
+		Ll2xyUsage();
+		_error_("Ll2xy usage error");
+	}
+
+	/*Input datasets: */
+	if (verbose) printf("Fetching inputs:\n");
+	FetchMatlabData(&lat,&nlat,LAT_IN);
+	if (verbose)
+		if   (nlat == 1) printf("  lat=%g\n",lat[0]);
+		else             printf("  lat=[%d values]\n",nlat);
+//	for (i=0; i<nlat; i++) printf("  lat[%d]=%g\n",i,lat[i]);
+	FetchMatlabData(&lon,&nlon,LON_IN);
+	if (verbose)
+		if   (nlon == 1) printf("  lon=%g\n",lon[0]);
+		else             printf("  lon=[%d values]\n",nlon);
+//	for (i=0; i<nlon; i++) printf("  lon[%d]=%g\n",i,lon[i]);
+	FetchMatlabData(&sgn,SGN_IN);
+	if (verbose) printf("  sgn=%d\n",sgn);
+
+	if (verbose) printf("Parsing options:\n");
+	options=new Options(NRHS,nrhs,prhs);
+	if (options->Size()) for(i=0;i<options->Size();i++) ((Option*)options->GetObjectByOffset(i))->DeepEcho();
+	/*  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=%g\n",cm);
+		options->Get(&sp,"standard_parallel");
+		if (verbose) printf("  sp=%g\n",sp);
+	}
+
+	/*some checks*/
+	if (verbose) printf("Checking inputs:\n");
+
+	if   (nlat != nlon) _error_("Must have same number of lat[%d] and lon[%d] coordinates.",nlat,nlon);
+	else                ncoord=nlat;
+	if (sgn != +1 && sgn != -1) _error_("Hemisphere sgn=%d must be +1 (north) or -1 (south).",sgn);
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=%g must be between -180 (west) and +180 (east) degrees.",cm);
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=%g must be between 0 and 90 degrees (in specified hemisphere).",sp);
+
+	x=(double *)xmalloc(ncoord*sizeof(double));
+	y=(double *)xmalloc(ncoord*sizeof(double));
+
+	/* Run core computations: */
+	if (verbose) printf("Calling core:\n");
+	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);
+	if (verbose) printf("  iret=%d\n",iret);
+
+	/*Write data: */
+	WriteMatlabData(X_OUT,x,ncoord);
+	WriteMatlabData(Y_OUT,y,ncoord);
+
+	/*Clean-up*/
+	delete options;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void Ll2xyUsage(void)
+{
+	_printf_(true,"Ll2xy - lat/long to x/y coordinate transformation module:\n");
+	_printf_(true,"\n");
+	_printf_(true,"   This module transforms lat/long to x/y coordinates.\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"      [x,y]=Ll2xy(lat,lon,sgn,'param name',param,...);\n");
+	_printf_(true,"\n");
+	_printf_(true,"      lat         latitude coordinates (double vector)\n");
+	_printf_(true,"      lon         longitude coordinates (double vector)\n");
+	_printf_(true,"      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
+	_printf_(true,"\n");
+	_printf_(true,"      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf_(true,"      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf_(true,"\n");
+	_printf_(true,"      x           x coordinates (double vector)\n");
+	_printf_(true,"      y           y coordinates (double vector)\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Examples:\n");
+	_printf_(true,"      [x,y]=Ll2xy(lat,lon, 1);\n");
+	_printf_(true,"      [x,y]=Ll2xy(lat,lon, 1,'central_meridian',45,'standard_parallel',70);\n");
+	_printf_(true,"      [x,y]=Ll2xy(lat,lon,-1,'central_meridian', 0,'standard_parallel',71);\n");
+	_printf_(true,"\n");
+}
+
Index: /issm/trunk-jpl-damage/src/mex/Ll2xy/Ll2xy.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Ll2xy/Ll2xy.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Ll2xy/Ll2xy.h	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file Ll2xy.h
+ * \brief: prototype for lat/long to x/y coordinate mex module.
+ */
+
+#ifndef _LL2XY_H
+#define _LL2XY_H
+
+/* local prototypes: */
+void Ll2xyUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Ll2xy"
+
+
+/* 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]
+
+/* serial arg counts: */
+#undef NRHS
+#define NRHS  3
+#undef NLHS
+#define NLHS  2
+
+#endif
+
Index: /issm/trunk-jpl-damage/src/mex/Makefile.am
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Makefile.am	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Makefile.am	(revision 11330)
@@ -0,0 +1,379 @@
+INCLUDES = @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@
+EXEEXT=$(MEXEXT)
+
+#Bin programs {{{1
+if NOSERIAL
+bin_PROGRAMS = 
+else
+bin_PROGRAMS = AverageFilter\
+				AddExternalResult\
+				BamgMesher\
+				BamgConvertMesh\
+				BamgTriangulate\
+				Chaco\
+				ComputeBasalStress\
+				ConfigureObjects \
+				ControlOptimization\
+				ControlInputGetGradient\
+				ControlInputScaleGradient\
+				ControlInputSetGradient\
+				ContourToMesh \
+				ContourToNodes \
+				CostFunction \
+				CreateNodalConstraints\
+				Echo\
+				ElementConnectivity\
+				EnumToString\
+				StringToEnum\
+				InputControlUpdate \
+				InputConvergence\
+				GetSolutionFromInputs\
+				GetVectorFromInputs\
+				Gradj\
+				GroundinglineMigration\
+				HoleFiller \
+				InputDuplicate\
+				InputScale\
+				InputToResult\
+				InternalFront\
+				InterpFromGridToMesh \
+				InterpFromMeshToMesh2d \
+				InterpFromMeshToMesh3d \
+				InterpFromMeshToGrid \
+				InterpFromMesh2d \
+				KMLFileRead \
+				KMLMeshWrite \
+				KMLOverlay \
+				Xy2ll \
+				Ll2xy \
+				Exp2Kml \
+				Kml2Exp \
+				Mergesolutionfromftog\
+				MeshPartition\
+				MeshProfileIntersection\
+				ModelProcessor \
+				NodeConnectivity\
+				NodesDof\
+				Orth\
+				OutputResults\
+				ParsePetscOptions\
+				ConstraintsState\
+				PointCloudFindNeighbors\
+				PropagateFlagsFromConnectivity\
+				ProcessParams\
+				Reduceload\
+				Reducevectorgtos\
+				Reducevectorgtof\
+				Response\
+				ResetCoordinateSystem\
+				Scotch\
+				Solver\
+				SparseToVector\
+				SpcNodes\
+				Shp2Kml\
+				UpdateConstraints\
+				SurfaceArea\
+				SystemMatrices\
+				Test\
+				TimeAdapt\
+				TriaSearch\
+				TriMesh\
+				TriMeshNoDensity\
+				TriMeshProcessRifts\
+				TriMeshRefine\
+				InputUpdateFromConstant\
+				InputUpdateFromSolution\
+				InputUpdateFromVector\
+				UpdateVertexPositions\
+				UpdateDynamicConstraints\
+				VerticesDof
+
+endif 
+#}}}
+#Dakota programs {{{1
+if NOSERIAL
+bin_PROGRAMS += 
+else
+bin_PROGRAMS += DakotaResponses\
+				Dakota\
+				InputUpdateFromDakota
+endif 
+#}}}
+#Flags and libraries {{{1
+LDADD =   $(TRIANGLELIB) ../c/libISSM.a $(PETSCLIB) $(FLIBS)  $(PLAPACKLIB)  $(MUMPSLIB) $(SCALAPACKLIB)  $(BLACSLIB)  $(HYPRELIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB)  $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(SHAPELIBLIB)
+
+AM_LDFLAGS = $(MEXLINK)
+
+#Matlab
+AM_CXXFLAGS=  -DMATLAB  -ansi -D_GNU_SOURCE -fPIC -fno-omit-frame-pointer -pthread 
+
+#Triangle library
+AM_CXXFLAGS+=  -DTRILIBRARY -DANSI_DECLARATORS -DNO_TIMER
+
+
+#64 vs 32 bits
+if LARGEARRAYS
+AM_CXXFLAGS += -D__GCC4BUILD__ -D_SERIAL_ 
+else
+AM_CXXFLAGS += -DMX_COMPAT_32 -D_SERIAL_
+endif
+
+AM_CXXFLAGS += $(CXXOPTFLAGS) 
+
+#}}}
+#Bin sources {{{1
+AddExternalResult_SOURCES = AddExternalResult/AddExternalResult.cpp\
+					AddExternalResult/AddExternalResult.h
+
+BamgMesher_SOURCES = BamgMesher/BamgMesher.cpp\
+					BamgMesher/BamgMesher.h
+
+BamgConvertMesh_SOURCES = BamgConvertMesh/BamgConvertMesh.cpp\
+					BamgConvertMesh/BamgConvertMesh.h
+
+BamgTriangulate_SOURCES = BamgTriangulate/BamgTriangulate.cpp\
+								  BamgTriangulate/BamgTriangulate.h
+
+Chaco_SOURCES = Chaco/Chaco.cpp\
+					Chaco/Chaco.h
+
+ComputeBasalStress_SOURCES = ComputeBasalStress/ComputeBasalStress.cpp\
+								  ComputeBasalStress/ComputeBasalStress.h
+
+ConfigureObjects_SOURCES = ConfigureObjects/ConfigureObjects.cpp\
+			  ConfigureObjects/ConfigureObjects.h
+
+ContourToMesh_SOURCES = ContourToMesh/ContourToMesh.cpp\
+			  ContourToMesh/ContourToMesh.h
+
+ContourToNodes_SOURCES = ContourToNodes/ContourToNodes.cpp\
+			  ContourToNodes/ContourToNodes.h
+
+ControlOptimization_SOURCES = ControlOptimization/ControlOptimization.cpp\
+			  ControlOptimization/ControlOptimization.h
+
+ControlInputGetGradient_SOURCES = ControlInputGetGradient/ControlInputGetGradient.cpp\
+										ControlInputGetGradient/ControlInputGetGradient.h
+
+ControlInputScaleGradient_SOURCES = ControlInputScaleGradient/ControlInputScaleGradient.cpp\
+											 ControlInputScaleGradient/ControlInputScaleGradient.h
+
+ControlInputSetGradient_SOURCES = ControlInputSetGradient/ControlInputSetGradient.cpp\
+			  ControlInputSetGradient/ControlInputSetGradient.h
+
+InputControlUpdate_SOURCES = InputControlUpdate/InputControlUpdate.cpp\
+										  InputControlUpdate/InputControlUpdate.h
+
+InputConvergence_SOURCES = InputConvergence/InputConvergence.cpp\
+			  InputConvergence/InputConvergence.h
+
+CostFunction_SOURCES =  CostFunction/CostFunction.cpp \
+						CostFunction/CostFunction.h
+
+CreateNodalConstraints_SOURCES =  CreateNodalConstraints/CreateNodalConstraints.cpp \
+								CreateNodalConstraints/CreateNodalConstraints.h
+
+NodesDof_SOURCES = NodesDof/NodesDof.cpp\
+			  NodesDof/NodesDof.h
+
+Echo_SOURCES = Echo/Echo.cpp\
+			  Echo/Echo.h
+
+ElementConnectivity_SOURCES = ElementConnectivity/ElementConnectivity.cpp\
+			  ElementConnectivity/ElementConnectivity.h
+
+EnumToString_SOURCES = EnumToString/EnumToString.cpp\
+			  EnumToString/EnumToString.h
+
+StringToEnum_SOURCES = StringToEnum/StringToEnum.cpp\
+			  StringToEnum/StringToEnum.h
+
+GetSolutionFromInputs_SOURCES = GetSolutionFromInputs/GetSolutionFromInputs.cpp\
+			  GetSolutionFromInputs/GetSolutionFromInputs.h
+
+GetVectorFromInputs_SOURCES = GetVectorFromInputs/GetVectorFromInputs.cpp\
+			  GetVectorFromInputs/GetVectorFromInputs.h
+
+Gradj_SOURCES = Gradj/Gradj.cpp\
+			  Gradj/Gradj.h
+
+GroundinglineMigration_SOURCES = GroundinglineMigration/GroundinglineMigration.cpp\
+			  GroundinglineMigration/GroundinglineMigration.h
+
+Test_SOURCES = Test/Test.cpp\
+			  Test/Test.h
+
+HoleFiller_SOURCES = HoleFiller/HoleFiller.cpp\
+			  HoleFiller/HoleFiller.h
+
+InputDuplicate_SOURCES = InputDuplicate/InputDuplicate.cpp\
+			  InputDuplicate/InputDuplicate.h
+
+InputScale_SOURCES = InputScale/InputScale.cpp\
+			  InputScale/InputScale.h
+
+InputToResult_SOURCES = InputToResult/InputToResult.cpp\
+			  InputToResult/InputToResult.h
+
+InternalFront_SOURCES = InternalFront/InternalFront.cpp\
+										 InternalFront/InternalFront.h
+
+InterpFromGridToMesh_SOURCES = InterpFromGridToMesh/InterpFromGridToMesh.cpp\
+			  InterpFromGridToMesh/InterpFromGridToMesh.h
+
+InterpFromMeshToMesh2d_SOURCES = InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
+							InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
+
+InterpFromMeshToMesh3d_SOURCES = InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp\
+									InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
+
+InterpFromMeshToGrid_SOURCES = InterpFromMeshToGrid/InterpFromMeshToGrid.cpp\
+									InterpFromMeshToGrid/InterpFromMeshToGrid.h
+
+InterpFromMesh2d_SOURCES = InterpFromMesh2d/InterpFromMesh2d.cpp\
+									InterpFromMesh2d/InterpFromMesh2d.h
+
+KMLFileRead_SOURCES = KMLFileRead/KMLFileRead.cpp\
+			  KMLFileRead/KMLFileRead.h
+
+KMLMeshWrite_SOURCES = KMLMeshWrite/KMLMeshWrite.cpp\
+			  KMLMeshWrite/KMLMeshWrite.h
+
+KMLOverlay_SOURCES = KMLOverlay/KMLOverlay.cpp\
+			  KMLOverlay/KMLOverlay.h
+
+Xy2ll_SOURCES = Xy2ll/Xy2ll.cpp\
+			  Xy2ll/Xy2ll.h
+
+Ll2xy_SOURCES = Ll2xy/Ll2xy.cpp\
+			  Ll2xy/Ll2xy.h
+
+Exp2Kml_SOURCES = Exp2Kml/Exp2Kml.cpp\
+			  Exp2Kml/Exp2Kml.h
+
+Kml2Exp_SOURCES = Kml2Exp/Kml2Exp.cpp\
+			  Kml2Exp/Kml2Exp.h
+
+AverageFilter_SOURCES = AverageFilter/AverageFilter.cpp\
+			  AverageFilter/AverageFilter.h
+
+Mergesolutionfromftog_SOURCES = Mergesolutionfromftog/Mergesolutionfromftog.cpp\
+			  Mergesolutionfromftog/Mergesolutionfromftog.h
+
+MeshPartition_SOURCES = MeshPartition/MeshPartition.cpp\
+			  MeshPartition/MeshPartition.h
+
+MeshProfileIntersection_SOURCES = MeshProfileIntersection/MeshProfileIntersection.cpp\
+			  MeshProfileIntersection/MeshProfileIntersection.h
+
+ModelProcessor_SOURCES =  ModelProcessor/ModelProcessor.cpp \
+						  ModelProcessor/ModelProcessor.h
+
+NodeConnectivity_SOURCES = NodeConnectivity/NodeConnectivity.cpp\
+			  NodeConnectivity/NodeConnectivity.h
+
+Orth_SOURCES = Orth/Orth.cpp\
+			  Orth/Orth.h
+
+OutputResults_SOURCES = OutputResults/OutputResults.cpp\
+			  OutputResults/OutputResults.h
+
+ConstraintsState_SOURCES = ConstraintsState/ConstraintsState.cpp\
+			  ConstraintsState/ConstraintsState.h
+
+PointCloudFindNeighbors_SOURCES = PointCloudFindNeighbors/PointCloudFindNeighbors.cpp\
+			  PointCloudFindNeighbors/PointCloudFindNeighbors.h
+
+ProcessParams_SOURCES = ProcessParams/ProcessParams.cpp\
+			  ProcessParams/ProcessParams.h
+
+PropagateFlagsFromConnectivity_SOURCES = PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp\
+			  PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
+
+Reduceload_SOURCES = Reduceload/Reduceload.cpp\
+			  Reduceload/Reduceload.h
+
+Reducevectorgtos_SOURCES = Reducevectorgtos/Reducevectorgtos.cpp\
+			  Reducevectorgtos/Reducevectorgtos.h
+
+Reducevectorgtof_SOURCES = Reducevectorgtof/Reducevectorgtof.cpp\
+									Reducevectorgtof/Reducevectorgtof.h
+
+Response_SOURCES = Response/Response.cpp\
+									Response/Response.h
+
+ResetCoordinateSystem_SOURCES = ResetCoordinateSystem/ResetCoordinateSystem.cpp\
+						 ResetCoordinateSystem/ResetCoordinateSystem.h
+
+Scotch_SOURCES = Scotch/Scotch.cpp\
+			  Scotch/Scotch.h
+
+Solver_SOURCES = Solver/Solver.cpp\
+			  Solver/Solver.h
+
+SparseToVector_SOURCES = SparseToVector/SparseToVector.cpp\
+			  SparseToVector/SparseToVector.h
+
+SpcNodes_SOURCES = SpcNodes/SpcNodes.cpp\
+			  SpcNodes/SpcNodes.h
+
+Shp2Kml_SOURCES = Shp2Kml/Shp2Kml.cpp\
+			  Shp2Kml/Shp2Kml.h
+
+UpdateConstraints_SOURCES = UpdateConstraints/UpdateConstraints.cpp\
+			  UpdateConstraints/UpdateConstraints.h
+
+SystemMatrices_SOURCES = SystemMatrices/SystemMatrices.cpp\
+			  SystemMatrices/SystemMatrices.h
+
+SurfaceArea_SOURCES = SurfaceArea/SurfaceArea.cpp\
+								 SurfaceArea/SurfaceArea.h
+
+TimeAdapt_SOURCES = TimeAdapt/TimeAdapt.cpp\
+			  TimeAdapt/TimeAdapt.h
+
+TriaSearch_SOURCES = TriaSearch/TriaSearch.cpp\
+			  TriaSearch/TriaSearch.h
+
+TriMesh_SOURCES = TriMesh/TriMesh.cpp\
+			  TriMesh/TriMesh.h
+
+TriMeshNoDensity_SOURCES = TriMeshNoDensity/TriMeshNoDensity.cpp\
+			  TriMeshNoDensity/TriMeshNoDensity.h
+
+TriMeshProcessRifts_SOURCES = TriMeshProcessRifts/TriMeshProcessRifts.cpp\
+			  TriMeshProcessRifts/TriMeshProcessRifts.h
+
+TriMeshRefine_SOURCES = TriMeshRefine/TriMeshRefine.cpp\
+			  TriMeshRefine/TriMeshRefine.h
+
+InputUpdateFromConstant_SOURCES = InputUpdateFromConstant/InputUpdateFromConstant.cpp\
+			  InputUpdateFromConstant/InputUpdateFromConstant.h
+
+InputUpdateFromSolution_SOURCES = InputUpdateFromSolution/InputUpdateFromSolution.cpp\
+			  InputUpdateFromSolution/InputUpdateFromSolution.h
+
+InputUpdateFromVector_SOURCES = InputUpdateFromVector/InputUpdateFromVector.cpp\
+			  InputUpdateFromVector/InputUpdateFromVector.h
+
+UpdateVertexPositions_SOURCES = UpdateVertexPositions/UpdateVertexPositions.cpp\
+			  UpdateVertexPositions/UpdateVertexPositions.h
+
+UpdateDynamicConstraints_SOURCES = UpdateDynamicConstraints/UpdateDynamicConstraints.cpp\
+			  UpdateDynamicConstraints/UpdateDynamicConstraints.h
+
+ParsePetscOptions_SOURCES = ParsePetscOptions/ParsePetscOptions.cpp\
+			  ParsePetscOptions/ParsePetscOptions.h
+
+VerticesDof_SOURCES = VerticesDof/VerticesDof.cpp\
+			  VerticesDof/VerticesDof.h
+
+#}}}
+#Dakota sources {{{1
+DakotaResponses_SOURCES = DakotaResponses/DakotaResponses.cpp\
+			  DakotaResponses/DakotaResponses.h
+Dakota_SOURCES = Dakota/Dakota.cpp\
+			  Dakota/Dakota.h
+InputUpdateFromDakota_SOURCES = InputUpdateFromDakota/InputUpdateFromDakota.cpp\
+			  InputUpdateFromDakota/InputUpdateFromDakota.h
+#}}}
Index: /issm/trunk-jpl-damage/src/mex/Mergesolutionfromftog/Mergesolutionfromftog.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Mergesolutionfromftog/Mergesolutionfromftog.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Mergesolutionfromftog/Mergesolutionfromftog.cpp	(revision 11330)
@@ -0,0 +1,62 @@
+/*\file Mergesolutionfromftog.c
+ *\brief: merge solution back from f set into g set
+ */
+
+#include "./Mergesolutionfromftog.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	bool        flag_ys0;
+	Vec         uf         = NULL;
+	Vec         ys         = NULL;
+	Nodes*      nodes   = NULL;
+	Parameters* parameters   = NULL;
+
+	/* output datasets: */
+	Vec ug=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if((nlhs!=NLHS) || (nrhs!=4 && nrhs!=5)){
+		MergesolutionfromftogUsage();
+		_error_(" usage. See above");
+	}
+
+	/*Input datasets: */
+	FetchMatlabData(&uf,UF);
+	FetchMatlabData(&ys,YS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*!Reduce vector: */
+	if (nrhs==4){
+		Mergesolutionfromftogx(&ug, uf,ys,nodes,parameters);
+	}
+	else{
+		FetchMatlabData(&flag_ys0,YSFLAG);
+		Mergesolutionfromftogx(&ug, uf,ys,nodes,parameters,flag_ys0);
+	}
+
+	/*write output datasets: */
+	WriteMatlabData(UG,ug);
+
+	/*Free ressources: */
+	VecFree(&uf);
+	VecFree(&ug);
+	VecFree(&ys);
+	delete nodes;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void MergesolutionfromftogUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [ug] = %s(uf,ys,nodes,parameters,[flag_ys0]);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/Mergesolutionfromftog/Mergesolutionfromftog.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Mergesolutionfromftog/Mergesolutionfromftog.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Mergesolutionfromftog/Mergesolutionfromftog.h	(revision 11330)
@@ -0,0 +1,36 @@
+
+/*
+	Mergesolutionfromftog.h
+*/
+
+
+#ifndef _MERGESOLUTIONFROMFTOG_H
+#define _MERGESOLUTIONFROMFTOG_H
+
+/* local prototypes: */
+void MergesolutionfromftogUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Mergesolutionfromftog"
+
+/* serial input macros: */
+#define UF (mxArray*)prhs[0]
+#define YS (mxArray*)prhs[1]
+#define NODES (mxArray*)prhs[2]
+#define PARAMETERS (mxArray*)prhs[3]
+#define YSFLAG (mxArray*)prhs[4]
+
+/* serial output macros: */
+#define UG (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  5
+
+#endif  /* _MERGESOLUTIONFROMFTOG_H */
Index: /issm/trunk-jpl-damage/src/mex/MeshPartition/MeshPartition.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/MeshPartition/MeshPartition.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/MeshPartition/MeshPartition.cpp	(revision 11330)
@@ -0,0 +1,104 @@
+/*!\file:  MeshPartition.cpp
+ * \brief: partition mesh according to number of areas, using Metis library.
+
+	usage:
+	[element_partitioning,node_partitioning]=MeshPartition(model,numareas)
+	
+	%Info needed from model are the following: 
+	%mesh info: 
+	numberofelements,numberofvertices,elements,elements_width
+	%Non-extruded 2d mesh info
+	nel2d,nods2d,elements2d,
+	%Extruded 2d mesh info
+	nel2d_ext,nods2d_ext,elements2d_ext,
+	%Diverse
+	numberoflayers,dim)
+
+	output:
+	vector of partitioning area numbers, for every element.
+	vector of partitioning area numbers, for every node.
+*/
+	
+#include "./MeshPartition.h"
+
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+
+
+	/*Indexing: */
+	int i,j;
+
+	/* required input: */
+	int     dim;
+	int     numberofelements;
+	int     numberofvertices;
+	double *elements         = NULL;
+	int     elements_width;
+
+	int numberofelements2d;
+	int numberofvertices2d;
+	double* elements2d=NULL;
+
+	int numberoflayers;
+	int numareas=1;
+
+	/* output: */
+	int    *int_element_partitioning = NULL;
+	int    *int_node_partitioning    = NULL;
+	double *element_partitioning     = NULL;
+	double *node_partitioning        = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&MeshPartitionUsage);
+
+	/*Fetch data: */
+	FetchMatlabData(&dim,mxGetAssignedField(MODEL,0,"dimension"));
+	FetchMatlabData(&numberofelements,mxGetAssignedField(MODEL,0,"numberofelements"));
+	FetchMatlabData(&numberofvertices,mxGetAssignedField(MODEL,0,"numberofvertices"));
+	FetchMatlabData(&elements,NULL,&elements_width,mxGetAssignedField(MODEL,0,"elements"));
+
+	if (dim==3){
+		FetchMatlabData(&numberofelements2d,mxGetAssignedField(MODEL,0,"numberofelements2d"));
+		FetchMatlabData(&numberofvertices2d,mxGetAssignedField(MODEL,0,"numberofvertices2d"));
+		FetchMatlabData(&elements2d,NULL,NULL,mxGetAssignedField(MODEL,0,"elements2d"));
+	}
+	FetchMatlabData(&numberoflayers,mxGetAssignedField(MODEL,0,"numberoflayers"));
+	FetchMatlabData(&numareas,NUMAREAS);
+
+	/*Run partitioning algorithm based on a "clever" use of the Metis partitioner: */
+	MeshPartitionx(&int_element_partitioning,&int_node_partitioning,numberofelements,numberofvertices,elements,
+		numberofelements2d,numberofvertices2d,elements2d,numberoflayers,elements_width,dim,numareas);
+
+	/*Post process node_partitioning and element_partitioning to be in double format. Metis needed them in int* format: */
+	element_partitioning=(double*)xmalloc(numberofelements*sizeof(double));
+	for (i=0;i<numberofelements;i++){
+		element_partitioning[i]=(double)int_element_partitioning[i]+1; //Metis indexing from 0, matlab from 1.
+	}
+	
+	node_partitioning=(double*)xmalloc(numberofvertices*sizeof(double));
+	for (i=0;i<numberofvertices;i++){
+		node_partitioning[i]=(double)int_node_partitioning[i]+1; //Metis indexing from 0, matlab from 1.
+	}
+
+	/*Write data:*/
+	WriteMatlabData(ELEMENTPARTITIONING,element_partitioning,numberofelements);
+	WriteMatlabData(NODEPARTITIONING,node_partitioning,numberofvertices);
+	
+	/*Free ressources:*/
+	//don't! let matlab do it.
+
+	/*end module: */
+	MODULEEND();
+}
+
+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");
+}
Index: /issm/trunk-jpl-damage/src/mex/MeshPartition/MeshPartition.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/MeshPartition/MeshPartition.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/MeshPartition/MeshPartition.h	(revision 11330)
@@ -0,0 +1,39 @@
+
+/*
+	MeshPartition.h
+*/
+
+
+#ifndef _MESHPARTITION_H
+#define _MESHPARTITION_H
+
+/* local prototypes: */
+void MeshPartitionUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef CLEANUP
+#define CLEANUP MeshPartitionLocalCleanup();
+
+#undef __FUNCT__ 
+#define __FUNCT__  "MeshPartition"
+
+/* serial input macros: */
+#define MODEL (mxArray*)prhs[0]
+#define NUMAREAS (mxArray*)prhs[1]
+
+/* serial output macros: */
+#define ELEMENTPARTITIONING (mxArray**)&plhs[0]
+#define NODEPARTITIONING (mxArray**)&plhs[1]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  2
+#undef NRHS
+#define NRHS  2
+
+
+#endif  /* _MESHPARTITION_H */
+
Index: /issm/trunk-jpl-damage/src/mex/MeshProfileIntersection/MeshProfileIntersection.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 11330)
@@ -0,0 +1,114 @@
+/*! \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 extremitis 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 mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+
+	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
+	mxArray*  matlabstructure=NULL;
+	Contour** contours=NULL;
+	int       numcontours;
+	Contour*  contouri=NULL;
+
+	/* output: */
+	double* segments=NULL;
+	int     numsegs;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&MeshProfileIntersectionUsage);
+
+	/*First, call expread on filename to build a contour array in the matlab workspace: */
+	mexCallMATLAB( 1, &matlabstructure, 1, (mxArray**)&FILENAME, "expread");
+
+	/*Fetch inputs: */
+	//index
+	FetchMatlabData(&double_index,&nel,&dummy,INDEX);
+	if(dummy!=3)_error_(" element triangulation should be of 3 column width!");
+	index=(int*)xmalloc(nel*3*sizeof(int));
+	for(i=0;i<nel;i++){
+		for(j=0;j<3;j++){
+			*(index+3*i+j)=(int)*(double_index+3*i+j)-1; //"C" style indexing
+		}
+	}
+	//x and y
+	FetchMatlabData(&x,&nods,X);
+	FetchMatlabData(&y,&dummy,Y);
+
+	//contours
+	numcontours=mxGetNumberOfElements(matlabstructure);
+	contours=(Contour**)xmalloc(numcontours*sizeof(Contour*));
+	for(i=0;i<numcontours;i++){
+		//allocate
+		contouri=(Contour*)xmalloc(sizeof(Contour));
+		//retrieve dimension of this contour.
+		contouri->nods=(int)mxGetScalar(mxGetField(matlabstructure,i,"nods"));
+		//set pointers.
+		contouri->x=mxGetPr(mxGetField(matlabstructure,i,"x"));
+		contouri->y=mxGetPr(mxGetField(matlabstructure,i,"y"));
+		*(contours+i)=contouri;
+	}
+
+	/* Debugging of contours :{{{1*/
+	/*for(i=0;i<numcontours;i++){
+		printf("\nContour echo: contour number  %i / %i\n",i+1,numcontours);
+		contouri=*(contours+i);
+		printf("   Number of vertices %i\n",contouri->nods);
+		for (j=0;j<contouri->nods;j++){
+			printf("   %lf %lf\n",*(contouri->x+j),*(contouri->y+j));
+		}
+	}*/
+	/*}}}*/
+
+	/*Run interpolation routine: */
+	MeshProfileIntersectionx(&segments,&numsegs,index,x,y,nel,nods,contours,numcontours);
+
+	/* output: */
+	WriteMatlabData(SEGMENTS,segments,numsegs,5);
+
+	/*end module: */
+	MODULEEND();
+
+}
+
+void MeshProfileIntersectionUsage(void){
+	printf("   usage:\n");
+	printf("   [segments]=MeshProfileIntersection(index,x,y,filename);\n");
+	printf("   where:\n");
+	printf("   input:\n");
+	printf("        index,x,y is a triangulation\n");
+	printf("        filename: name of Argus style .exp file containing the segments (can be groups of disconnected segments)\n");
+	printf("   output:\n");
+	printf("        segments: array made of x1,y1,x2,y2,element_id lines (x1,y1) and (x2,y2) are segment extremitis for a segment \n");
+	printf("        belonging to the elemnt_id element. there are as many lines in segments as there are segments intersecting the \n");
+	printf("        mesh.\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/MeshProfileIntersection/MeshProfileIntersection.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/MeshProfileIntersection/MeshProfileIntersection.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/MeshProfileIntersection/MeshProfileIntersection.h	(revision 11330)
@@ -0,0 +1,36 @@
+
+/*
+	MeshProfileIntersection.h
+*/
+
+
+#ifndef _MESHPROFILEINTERSECTION_H
+#define _MESHPROFILEINTERSECTION_H
+
+/* local prototypes: */
+void MeshProfileIntersectionUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__
+#define __FUNCT__ "MeshProfileIntersection"
+
+/* 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]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS 1
+#undef NRHS
+#define NRHS 4
+
+#endif  /* _MESHPROFILEINTERSECTION_H */
+
Index: /issm/trunk-jpl-damage/src/mex/ModelProcessor/ModelProcessor.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ModelProcessor/ModelProcessor.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ModelProcessor/ModelProcessor.cpp	(revision 11330)
@@ -0,0 +1,82 @@
+/*\file ModelProcessor.c
+ *\brief: processes model inputs from the matlab workspace, and transforms them into datasets or vectors 
+ *        that will be used throughout the matlab solution sequences.
+ */
+
+#include "./ModelProcessor.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){ 
+
+	int i;
+
+	/*inputs: */
+	char* inputfilename=NULL;
+	FILE* IOMODEL;
+	int     solution_type;
+	double* double_analyses=NULL;
+	int*    analyses=NULL;
+	int     numanalyses;
+	
+	/* output datasets: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL;
+	Vertices* vertices=NULL;
+	Constraints* constraints=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+	
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ModelProcessorUsage);
+	
+	/*open file input for reading: */
+	FetchMatlabData(&inputfilename,INPUTFILE);
+	IOMODEL= pfopen(inputfilename ,"rb");
+
+	/*retrieve solution type and analyses: */
+	FetchMatlabData(&solution_type,SOLUTIONTYPE);
+	FetchMatlabData(&double_analyses,&numanalyses,ANALYSES);
+	analyses=(int*)xmalloc(numanalyses*sizeof(int));
+	for(i=0;i<numanalyses;i++)analyses[i]=(int)double_analyses[i];
+	
+	/*call x code ModelProcessorx: */
+	ModelProcessorx(&elements,&nodes,&vertices,&materials,&constraints, &loads, &parameters, IOMODEL,solution_type,numanalyses,analyses);
+
+	/*Write output data: */
+	WriteMatlabData(ELEMENTS,elements);
+	WriteMatlabData(NODES,nodes);
+	WriteMatlabData(VERTICES,vertices);
+	WriteMatlabData(CONSTRAINTS,constraints);
+	WriteMatlabData(LOADS,loads);
+	WriteMatlabData(MATERIALS,materials);
+	WriteMatlabData(PARAMETERS,parameters);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete constraints;
+	delete loads;
+	delete materials;
+	delete parameters;
+	xfree((void**)&analyses);
+	xfree((void**)&double_analyses);
+	xfree((void**)&inputfilename);
+	
+	/*Close input file: */
+	pfclose(IOMODEL,inputfilename);
+	
+	/*end module: */
+	MODULEEND();
+}
+	
+void ModelProcessorUsage(void) {
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements,vertices,constraints,loads,materials,parameters,part,tpart]=ModelProcessor(model,analyses,inputfile)\n");
+	_printf_(true,"   where: model is an instance of the matlab @model class and analyses is a list of analysis types being performed.\n");
+	_printf_(true,"          inputfile is the file holding the marshalled datasets from the model.\n");
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ModelProcessor/ModelProcessor.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ModelProcessor/ModelProcessor.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ModelProcessor/ModelProcessor.h	(revision 11330)
@@ -0,0 +1,45 @@
+/*\file ModelProcessor.h
+ * \brief: ModelProcessor module include
+ */
+
+#ifndef _MEXMODELPROCESSOR_H_
+#define _MEXMODELPROCESSOR_H_
+
+/* local prototypes: */
+void ModelProcessorUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ModelProcessor"
+
+#undef CLEANUP
+#define CLEANUP ModelProcessorLocalCleanup();
+
+#undef ALL
+#define ALL 0
+
+/* serial input macros: */
+#define INPUTFILE (mxArray*)prhs[0]
+#define SOLUTIONTYPE (mxArray*)prhs[1]
+#define ANALYSES (mxArray*)prhs[2]
+
+/* serial output macros: */
+#define ELEMENTS (mxArray**)&plhs[0]
+#define NODES (mxArray**)&plhs[1]
+#define VERTICES (mxArray**)&plhs[2]
+#define CONSTRAINTS (mxArray**)&plhs[3]
+#define LOADS (mxArray**)&plhs[4]
+#define MATERIALS (mxArray**)&plhs[5]
+#define PARAMETERS (mxArray**)&plhs[6]
+		
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  7
+#undef NRHS
+#define NRHS  3
+
+#endif  /* _MEXMODELPROCESSOR_H */
+
Index: /issm/trunk-jpl-damage/src/mex/NodeConnectivity/NodeConnectivity.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/NodeConnectivity/NodeConnectivity.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/NodeConnectivity/NodeConnectivity.cpp	(revision 11330)
@@ -0,0 +1,44 @@
+/*\file NodeConnectivity.c
+ *\brief: build node connectivity from elements. 
+ */
+
+#include "./NodeConnectivity.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*inputs: */
+	double* elements=NULL;
+	int     nel,nods;
+
+	/*outputs: */
+	double* connectivity=NULL;
+	int     width;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&NodeConnectivityUsage);
+        
+	/*Input datasets: */
+	FetchMatlabData(&elements,&nel,NULL,ELEMENTS);
+	FetchMatlabData(&nods,NUMNODES);
+
+	/*!Generate internal degree of freedom numbers: */
+	NodeConnectivityx(&connectivity, &width,elements,nel, nods);
+
+	/*write output datasets: */
+	WriteMatlabData(CONNECTIVITY,connectivity,nods,width);
+
+	/*Free ressources: */
+	xfree((void**)&elements);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void NodeConnectivityUsage(void) {
+	_printf_(true,"\n");
+	_printf_(true,"   usage: connectivity = %s(elements, numnodes);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/NodeConnectivity/NodeConnectivity.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/NodeConnectivity/NodeConnectivity.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/NodeConnectivity/NodeConnectivity.h	(revision 11330)
@@ -0,0 +1,35 @@
+
+/*
+	NodeConnectivity.h
+*/
+
+
+#ifndef _NODECONNECTIVITY_H
+#define _NODECONNECTIVITY_H
+
+/* local prototypes: */
+void NodeConnectivityUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "NodeConnectivity"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NUMNODES (mxArray*)prhs[1]
+
+/* serial output macros: */
+#define CONNECTIVITY (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+
+#endif  /* _NODECONNECTIVITY_H */
+
Index: /issm/trunk-jpl-damage/src/mex/NodesDof/NodesDof.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/NodesDof/NodesDof.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/NodesDof/NodesDof.cpp	(revision 11330)
@@ -0,0 +1,45 @@
+/*\file NodesDof.c
+ *\brief: build degrees of freedom for every grid.
+ */
+
+#include "./NodesDof.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Nodes* nodes=NULL;
+	Parameters* parameters=NULL;
+	int     analysis_type;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&NodesDofUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&nodes,NODESIN);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*find analysis_type: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*!Generate internal degree of freedom numbers: */
+	NodesDofx(nodes, parameters,analysis_type); 
+
+	/*write output datasets: */
+	WriteMatlabData(NODES,nodes);
+
+	/*Free ressources: */
+	delete nodes;
+	delete parameters;
+	/*end module: */
+	MODULEEND();
+}
+
+void NodesDofUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [nodes] = %s(nodes,parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/NodesDof/NodesDof.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/NodesDof/NodesDof.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/NodesDof/NodesDof.h	(revision 11330)
@@ -0,0 +1,35 @@
+
+/*
+	NodesDof.h
+*/
+
+
+#ifndef _NODESDOF_H
+#define _NODESDOF_H
+
+/* local prototypes: */
+void NodesDofUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "NodesDof"
+
+/* serial input macros: */
+#define NODESIN (mxArray*)prhs[0]
+#define PARAMETERS (mxArray*)prhs[1]
+
+/* serial output macros: */
+#define NODES (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+
+#endif  /* _NODESDOF_H */
+
Index: /issm/trunk-jpl-damage/src/mex/Orth/Orth.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Orth/Orth.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Orth/Orth.cpp	(revision 11330)
@@ -0,0 +1,46 @@
+/*\file Orth.c
+ *\brief: orthogonalize searching directions for inverse control methods.
+ */
+
+#include "./Orth.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Vec gradj=NULL;
+	Vec oldgradj=NULL;
+
+	/* output datasets: */
+	Vec newgradj=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&OrthUsage);
+
+	/*Input datasets: */
+	FetchMatlabData(&gradj,GRADJ);
+	FetchMatlabData(&oldgradj,OLDGRADJ);
+
+	/*!Reduce load from g to f size: */
+	Orthx(&newgradj, gradj,oldgradj);
+
+	/*write output datasets: */
+	WriteMatlabData(NEWGRADJ,newgradj);
+
+	/*Free ressources: */
+	VecFree(&gradj);
+	VecFree(&oldgradj);
+	VecFree(&newgradj);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void OrthUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [newgradj] = %s(gradj,oldgradj);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/Orth/Orth.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Orth/Orth.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Orth/Orth.h	(revision 11330)
@@ -0,0 +1,35 @@
+
+/*
+	Orth.h
+*/
+
+
+#ifndef _ORTH_H
+#define _ORTH_H
+
+/* local prototypes: */
+void OrthUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Orth"
+
+/* serial input macros: */
+#define GRADJ (mxArray*)prhs[0]
+#define OLDGRADJ (mxArray*)prhs[1]
+
+/* serial output macros: */
+#define NEWGRADJ (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+
+#endif  /* _ORTH_H */
+
Index: /issm/trunk-jpl-damage/src/mex/OutputResults/OutputResults.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/OutputResults/OutputResults.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/OutputResults/OutputResults.cpp	(revision 11330)
@@ -0,0 +1,68 @@
+/*\file OutputResults.c
+ *\brief: output results inside elements, and in femmodel
+ */
+
+#include "./OutputResults.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Nodes*   nodes=NULL;
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+	Results* results=NULL;
+	
+	/* output datasets: */
+	mxArray* dataref=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&OutputResultsUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+	FetchMatlabData((DataSet**)&results,RESULTS);
+
+	/*results might be NULL, allocate: */
+	if(!results)results=new Results();
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*Call "x" code layer: */
+	OutputResultsx(&dataref, elements,nodes,vertices,loads,materials,parameters,&results);
+
+	/*write output datasets: */
+	plhs[0]=dataref;
+	
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+	delete results;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void OutputResultsUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [results] = %s(elements,nodes,vertices,loads,materials,parameters,results);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/OutputResults/OutputResults.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/OutputResults/OutputResults.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/OutputResults/OutputResults.h	(revision 11330)
@@ -0,0 +1,34 @@
+/*
+	OutputResults.h
+*/
+
+#ifndef _OUTPUTRESULTS_H
+#define _OUTPUTRESULTS_H
+
+/* local prototypes: */
+void OutputResultsUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "OutputResults"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADS (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+#define RESULTS (mxArray*)prhs[6]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  7
+
+#endif  /* _OUTPUTRESULTS_H */
Index: /issm/trunk-jpl-damage/src/mex/OutputRifts/OutputRifts.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/OutputRifts/OutputRifts.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/OutputRifts/OutputRifts.cpp	(revision 11330)
@@ -0,0 +1,48 @@
+/*\file OutputRifts.c
+ *\brief: output rift properties (fraction, penetration, etc ...)
+ */
+
+#include "./OutputRifts.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*diverse: */
+	int   numrifts;
+
+	/*input datasets: */
+	Loads* loads=NULL;
+
+	/* output datasets: */
+	Vec riftproperties=NULL;
+
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&OutputRiftsUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData(&numrifts,mxGetField(PARAMETERS,0,"numrifts"));
+
+	/*!Call core code: */
+	OutputRiftsx(&riftproperties,loads,numrifts);
+
+	/*write output : */
+	WriteMatlabData(RIFTPROPERTIES,riftproperties);
+
+	/*Free ressources: */
+	delete loads;
+	VecFree(&riftproperties);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void OutputRiftsUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [riftproperties] = %s(loads,parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/OutputRifts/OutputRifts.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/OutputRifts/OutputRifts.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/OutputRifts/OutputRifts.h	(revision 11330)
@@ -0,0 +1,37 @@
+
+/*
+	OutputRifts.h
+*/
+
+
+#ifndef _OUTPUTRIFTS_H
+#define _OUTPUTRIFTS_H
+
+/* local prototypes: */
+void OutputRiftsUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "OutputRifts"
+
+/* serial input macros: */
+#define LOADS (mxArray*)prhs[0]
+#define PARAMETERS (mxArray*)prhs[1]
+
+/* serial output macros: */
+#define RIFTPROPERTIES (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+
+#endif  /* _OUTPUTRIFTS_H */
+
+
+
Index: /issm/trunk-jpl-damage/src/mex/ParameterOutput/ParameterOutput.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ParameterOutput/ParameterOutput.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ParameterOutput/ParameterOutput.cpp	(revision 11330)
@@ -0,0 +1,61 @@
+/*\file ParameterOutput.c
+ *\brief: build output vectors for parameter outputs (like strain rate, stress, penalty active sets, etc ...)
+ */
+
+#include "./ParameterOutput.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	DataSet* results=NULL;
+	int      analysis_type;
+	int      sub_analysis_type;
+	
+	/* output datasets: */
+	Mat Kgg=NULL;
+	Vec pg=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ParameterOutputUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&results,RESULTS);
+	
+	/*parameters: */
+	FetchMatlabData(&analysis_type,ANALYSIS);
+	FetchMatlabData(&sub_analysis_type,SUBANALYSIS);
+
+	/*!Generate internal degree of freedom numbers: */
+	ParameterOutputx(results, elements,nodes,loads,materials,analysis_type,sub_analysis_type); 
+
+	/*write output datasets: */
+	WriteMatlabData(RESULTS,results,0,0,"DataSet",NULL); 
+	
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete loads;
+	delete materials;
+	delete results;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ParameterOutputUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [Kgg,pg] = %s(eleemnts,nodes,loads,materials,params,analysis_type);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ParameterOutput/ParameterOutput.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ParameterOutput/ParameterOutput.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ParameterOutput/ParameterOutput.h	(revision 11330)
@@ -0,0 +1,37 @@
+/*
+	ParameterOutput.h
+*/
+
+#ifndef _PARAMETEROUTPUT_H
+#define _PARAMETEROUTPUT_H
+
+/* local prototypes: */
+void ParameterOutputUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ParameterOutput"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define LOADS (mxArray*)prhs[2]
+#define MATERIALS (mxArray*)prhs[3]
+#define PARAMETERS (mxArray*)prhs[4]
+#define RESULTS (mxArray*)prhs[5]
+#define ANALYSIS (mxArray*)prhs[6]
+#define SUBANALYSIS (mxArray*)prhs[7]
+
+/* serial output macros: */
+#define OUTPUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  8
+
+#endif  /* _PARAMETEROUTPUT_H */
Index: /issm/trunk-jpl-damage/src/mex/ParsePetscOptions/ParsePetscOptions.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ParsePetscOptions/ParsePetscOptions.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ParsePetscOptions/ParsePetscOptions.cpp	(revision 11330)
@@ -0,0 +1,46 @@
+/*\file ParsePetscOptions.c
+ *\brief: add petsc options to parameters
+ */
+
+#include "./ParsePetscOptions.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Parameters *parameters = NULL;
+	char*       petscoptionsfilename=NULL;
+	FILE*       petscoptionsfid=NULL;
+	
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ParsePetscOptionsUsage);
+
+	/*Input datasets: */
+	FetchMatlabData(&parameters,PARAMETERS);
+	FetchMatlabData(&petscoptionsfilename,PETSCOPTIONSFILENAME); 
+
+	petscoptionsfid=fopen(petscoptionsfilename,"r");
+	if(petscoptionsfid==NULL)_error_("could not open petsc solver options  file for reading\n");
+
+	ParsePetscOptionsx(parameters,petscoptionsfid);
+
+	/*write output datasets: */
+	WriteMatlabData(PARAMETERSOUT,parameters);
+	
+	/*Free ressources: */
+	delete parameters;
+	xfree((void**)&petscoptionsfilename);
+	fclose(petscoptionsfid);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ParsePetscOptionsUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [parameters] = %s(parameters,petscoptionsfilename);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ParsePetscOptions/ParsePetscOptions.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ParsePetscOptions/ParsePetscOptions.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ParsePetscOptions/ParsePetscOptions.h	(revision 11330)
@@ -0,0 +1,32 @@
+/*
+	ParsePetscOptions.h
+*/
+
+#ifndef _PARSEPETSCOPTIONS_H
+#define _PARSEPETSCOPTIONS_H
+
+/* local prototypes: */
+void ParsePetscOptionsUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ParsePetscOptions"
+
+/* serial input macros: */
+#define PARAMETERS   (mxArray *)prhs[0]
+#define PETSCOPTIONSFILENAME        (mxArray *)prhs[1]
+
+/* serial output macros: */
+#define PARAMETERSOUT  (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+#endif  /* _PARSEPETSCOPTIONS_H */
Index: /issm/trunk-jpl-damage/src/mex/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp	(revision 11330)
@@ -0,0 +1,52 @@
+/*! \file  PointCloudFindNeighbors
+    \brief: flag points that are too near one another, within an array of point coordinates
+*/
+	
+#include "./PointCloudFindNeighbors.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+
+	int i,j;
+
+	/* required input: */
+	double* x=NULL;
+	double* y=NULL;
+	int     nods;
+	double  mindistance;
+	double  multithread;
+
+	/* output: */
+	Vec  flags=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&PointCloudFindNeighborsUsage);
+
+	/*Fetch inputs: */
+	FetchMatlabData(&x,&nods,NULL,XHANDLE);  
+	FetchMatlabData(&y,NULL,NULL,YHANDLE);
+	FetchMatlabData(&mindistance,MINDISTANCE);
+	FetchMatlabData(&multithread,MULTITHREAD);
+
+	/*Run core routine: */
+	PointCloudFindNeighborsx(&flags,x,y,nods,mindistance,multithread);
+
+	/* output: */
+	WriteMatlabData(FLAGS,flags);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void PointCloudFindNeighborsUsage(void){
+	printf("   usage:\n");
+	printf("   [flags]=PointCloudFindNeighbors(x,y,mindistance,multithread);\n\n");
+	printf("   where:\n");
+	printf("      x,y: list of points.\n");
+	printf("      mindistance: minimum distance that should exist between points in the cloud.\n");
+	printf("      multithread: run multithreaded or not. with multithreads, flags can get 1 and 2 values in duplicates.\n");
+	printf("      flags: array of flags (flag==1 means point is within mindistance of another point)\n");
+	printf("\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/PointCloudFindNeighbors/PointCloudFindNeighbors.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/PointCloudFindNeighbors/PointCloudFindNeighbors.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/PointCloudFindNeighbors/PointCloudFindNeighbors.h	(revision 11330)
@@ -0,0 +1,42 @@
+
+/*
+	PointCloudFindNeighbors.h
+*/
+
+
+#ifndef _POINTCLOUDFINDNEIGHBORS_H
+#define _POINTCLOUDFINDNEIGHBORS_H
+
+/* local prototypes: */
+void PointCloudFindNeighborsUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__
+#define __FUNCT__ "PointCloudFindNeighbors"
+
+
+#ifndef ALL
+#define ALL 0
+#endif
+
+/* 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]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS 1
+#undef NRHS
+#define NRHS 4
+
+
+#endif  /* _POINTCLOUDFINDNEIGHBORS_H */
+
Index: /issm/trunk-jpl-damage/src/mex/ProcessParams/ProcessParams.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ProcessParams/ProcessParams.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ProcessParams/ProcessParams.cpp	(revision 11330)
@@ -0,0 +1,36 @@
+/*\file ProcessParams.c
+ *\brief: configure objects (elements, loads for example), that need linking with nodes
+ */
+
+#include "./ProcessParams.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Parameters* parameters=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ProcessParamsUsage);
+	
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&parameters,PARAMETERS);
+
+	/*write output datasets: */
+	WriteMatlabData(PARAMETERSOUT,parameters);
+
+	/*Free ressources: */
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ProcessParamsUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [parameters] = %s(parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ProcessParams/ProcessParams.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ProcessParams/ProcessParams.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ProcessParams/ProcessParams.h	(revision 11330)
@@ -0,0 +1,31 @@
+/*
+	ProcessParams.h
+*/
+
+#ifndef _PROCESSPARAMS_H
+#define _PROCESSPARAMS_H
+
+/* local prototypes: */
+void ProcessParamsUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ProcessParams"
+
+/* serial input macros: */
+#define PARAMETERS (mxArray*)prhs[0]
+
+/* serial output macros: */
+#define PARAMETERSOUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  1
+
+#endif  /* _PROCESSPARAMS_H */
+
Index: /issm/trunk-jpl-damage/src/mex/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp	(revision 11330)
@@ -0,0 +1,47 @@
+/*\file PropagateFlagsFromConnectivity.c
+ *\brief: propagate flags onto mesh, element by element, using connectivity.
+ */
+
+#include "./PropagateFlagsFromConnectivity.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*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: */
+	FetchMatlabData(&connectivity,&nel,&dummy,CONNECTIVITY);
+	FetchMatlabData(&pool,&dummy,POOL);
+	FetchMatlabData(&index,INDEX);
+	FetchMatlabData(&flags,&dummy,FLAGS);
+
+	/*!Generate internal degree of freedom numbers: */
+	PropagateFlagsFromConnectivityx(pool,connectivity,index,flags);
+
+	/*write output datasets: */
+	WriteMatlabData(POOLOUT,pool,nel);
+
+	/*Free ressources: */
+	xfree((void**)&connectivity);
+	xfree((void**)&flags);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void PropagateFlagsFromConnectivityUsage(void) {
+	printf("\n");
+	printf("   usage: [pool] = %s(connectivity,pool,index,flags);\n",__FUNCT__);
+	printf("\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h	(revision 11330)
@@ -0,0 +1,38 @@
+
+/*
+	PropagateFlagsFromConnectivity.h
+*/
+
+
+#ifndef _PROPAGATEFLAGSFROMCONNECTIVITY_H
+#define _PROPAGATEFLAGSFROMCONNECTIVITY_H
+
+/* local prototypes: */
+void PropagateFlagsFromConnectivityUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "PropagateFlagsFromConnectivity"
+
+/* serial input macros: */
+#define CONNECTIVITY (mxArray*)prhs[0]
+#define POOL (mxArray*)prhs[1]
+#define INDEX (mxArray*)prhs[2]
+#define FLAGS (mxArray*)prhs[3]
+
+/* serial output macros: */
+#define POOLOUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  4
+
+
+#endif  /* _PROPAGATEFLAGSFROMCONNECTIVITY_H */
+
+
Index: /issm/trunk-jpl-damage/src/mex/Reduceload/Reduceload.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Reduceload/Reduceload.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Reduceload/Reduceload.cpp	(revision 11330)
@@ -0,0 +1,55 @@
+/*\file Reduceload.c
+ *\brief: reduce load from g set to f set
+ */
+
+#include "./Reduceload.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Vec         pf         = NULL;
+	Mat         Kfs        = NULL;
+	Vec         ys         = NULL;
+	bool        flag_ys0=false;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if((nlhs!=NLHS) || (nrhs!=3 && nrhs!=4)){
+		ReduceloadUsage();
+		_error_(" usage. See above");
+	}
+
+	/*Input datasets: */
+	FetchMatlabData(&pf,PF);
+	FetchMatlabData(&Kfs,KFS);
+	FetchMatlabData(&ys,YS);
+
+	/*!Reduce load from g to f size: */
+	if(nrhs==4){
+		FetchMatlabData(&flag_ys0,YSFLAG);
+		Reduceloadx(pf, Kfs, ys,flag_ys0);
+	}
+	else{
+		Reduceloadx(pf, Kfs, ys);
+	}
+
+	/*write output datasets: */
+	WriteMatlabData(PFOUT,pf);
+
+	/*Free ressources: */
+	VecFree(&pf);
+	MatFree(&Kfs);
+	VecFree(&ys);
+
+	MODULEEND();
+}
+
+void ReduceloadUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [pf] = %s(pf,Kfs,ys);\n",__FUNCT__);
+	_printf_(true,"          [pf] = %s(pf,Kfs,ys,ys0_flag);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/Reduceload/Reduceload.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Reduceload/Reduceload.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Reduceload/Reduceload.h	(revision 11330)
@@ -0,0 +1,33 @@
+/*
+	Reduceload.h
+*/
+
+#ifndef _REDUCELOAD_H
+#define _REDUCELOAD_H
+
+/* local prototypes: */
+void ReduceloadUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Reduceload"
+
+/* serial input macros: */
+#define PF (mxArray*)prhs[0]
+#define KFS (mxArray*)prhs[1]
+#define YS (mxArray*)prhs[2]
+#define YSFLAG (mxArray*)prhs[3]
+
+/* serial output macros: */
+#define PFOUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  4
+
+#endif  /* _REDUCELOAD_H */
Index: /issm/trunk-jpl-damage/src/mex/Reducevectorgtof/Reducevectorgtof.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Reducevectorgtof/Reducevectorgtof.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Reducevectorgtof/Reducevectorgtof.cpp	(revision 11330)
@@ -0,0 +1,49 @@
+/*\file Reducevectorgtof.c
+ *\brief: reduce g set vector to s set vector (set of single point constraints)
+ */
+
+#include "./Reducevectorgtof.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Vec ug=NULL;
+	Nodes* nodes=NULL;
+	Parameters* parameters=NULL;
+
+	/* output datasets: */
+	Vec uf=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ReducevectorgtofUsage);
+
+	/*Input datasets: */
+	FetchMatlabData(&ug,UG);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*!Reduce vector: */
+	Reducevectorgtofx(&uf,ug,nodes,parameters);
+
+	/*write output datasets: */
+	WriteMatlabData(UF,uf);
+
+	/*Free ressources: */
+	delete nodes;
+	delete parameters;
+	VecFree(&ug);
+	VecFree(&uf);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ReducevectorgtofUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: uf = %s(ug,nodes,parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/Reducevectorgtof/Reducevectorgtof.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Reducevectorgtof/Reducevectorgtof.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Reducevectorgtof/Reducevectorgtof.h	(revision 11330)
@@ -0,0 +1,36 @@
+
+/*
+	Reducevectorgtof.h
+*/
+
+
+#ifndef _REDUCEVECTORGTOF_H
+#define _REDUCEVECTORGTOF_H
+
+/* local prototypes: */
+void ReducevectorgtofUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Reducevectorgtof"
+
+/* serial input macros: */
+#define UG (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define PARAMETERS (mxArray*)prhs[2]
+
+/* serial output macros: */
+#define UF (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS 3
+
+
+#endif  /* _REDUCEVECTORGTOF_H */
+
Index: /issm/trunk-jpl-damage/src/mex/Reducevectorgtos/Reducevectorgtos.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Reducevectorgtos/Reducevectorgtos.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Reducevectorgtos/Reducevectorgtos.cpp	(revision 11330)
@@ -0,0 +1,49 @@
+/*\file Reducevectorgtos.c
+ *\brief: reduce g set vector to s set vector (set of single point constraints)
+ */
+
+#include "./Reducevectorgtos.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Vec yg=NULL;
+	Nodes* nodes=NULL;
+	Parameters* parameters=NULL;
+
+	/* output datasets: */
+	Vec ys=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ReducevectorgtosUsage);
+
+	/*Input datasets: */
+	FetchMatlabData(&yg,YG);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*!Reduce vector: */
+	Reducevectorgtosx(&ys,yg,nodes,parameters);
+
+	/*write output datasets: */
+	WriteMatlabData(YS,ys);
+
+	/*Free ressources: */
+	delete nodes;
+	delete parameters;
+	VecFree(&yg);
+	VecFree(&ys);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ReducevectorgtosUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: ys = %s(yg,nodes,parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/Reducevectorgtos/Reducevectorgtos.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Reducevectorgtos/Reducevectorgtos.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Reducevectorgtos/Reducevectorgtos.h	(revision 11330)
@@ -0,0 +1,32 @@
+/*
+	Reducevectorgtos.h
+*/
+
+#ifndef _REDUCEVECTORGTOS_H
+#define _REDUCEVECTORGTOS_H
+
+/* local prototypes: */
+void ReducevectorgtosUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Reducevectorgtos"
+
+/* serial input macros: */
+#define YG (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define PARAMETERS (mxArray*)prhs[2]
+
+/* serial output macros: */
+#define YS (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  3
+
+#endif  /* _REDUCEVECTORGTOS_H */
Index: /issm/trunk-jpl-damage/src/mex/ResetCoordinateSystem/ResetCoordinateSystem.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ResetCoordinateSystem/ResetCoordinateSystem.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ResetCoordinateSystem/ResetCoordinateSystem.cpp	(revision 11330)
@@ -0,0 +1,62 @@
+/*\file ResetCoordinateSystem.c
+ *\brief: recover pressure from elements
+ */
+
+#include "./ResetCoordinateSystem.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements* elements=NULL;
+	Nodes* nodes=NULL; 
+	Vertices* vertices=NULL;
+	Loads* loads=NULL;
+	Materials* materials=NULL;
+	Parameters* parameters=NULL;
+	int      numberofnodes;
+
+	/* output datasets: */
+	Vec sigma_g=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ResetCoordinateSystemUsage);
+        
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Generate internal degree of freedom numbers: */
+	ResetCoordinateSystemx(elements,nodes,vertices,loads,materials,parameters);
+
+	/*write output datasets: */
+	WriteMatlabData(NODESOUT,nodes);
+
+	/*Free ressources: */
+	delete nodes;
+	delete vertices;
+	delete elements;
+	delete materials;
+	delete loads;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ResetCoordinateSystemUsage(void) {
+	printf("\n");
+	printf("   usage: [nodes] = %s(elements, nodes, vertices, loads, materials, params);\n",__FUNCT__);
+	printf("\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/ResetCoordinateSystem/ResetCoordinateSystem.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/ResetCoordinateSystem/ResetCoordinateSystem.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/ResetCoordinateSystem/ResetCoordinateSystem.h	(revision 11330)
@@ -0,0 +1,36 @@
+/*
+	ResetCoordinateSystem.h
+*/
+
+#ifndef _RESETCOORDINATESYSTEM_H
+#define _RESETCOORDINATESYSTEM_H
+
+/* local prototypes: */
+void ResetCoordinateSystemUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ResetCoordinateSystem"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADS (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+
+/* serial output macros: */
+#define NODESOUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  6
+
+#endif  /* _COMPUTEPRESSURE_H */
+
Index: /issm/trunk-jpl-damage/src/mex/Response/Response.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Response/Response.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Response/Response.cpp	(revision 11330)
@@ -0,0 +1,72 @@
+/*\file Response.c
+ *\brief: compute response according to a response descriptor
+ */
+
+#include "./Response.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements   *elements   = NULL;
+	Loads      *loads      = NULL;
+	Nodes      *nodes      = NULL;
+	Vertices   *vertices   = NULL;
+	Materials  *materials  = NULL;
+	Parameters *parameters = NULL;
+	char       *response   = NULL;
+	bool        process_units;
+	int         weight_index;
+
+	/* output datasets: */
+	double resp;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ResponseUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+	FetchMatlabData(&response,RESPONSE);
+	FetchMatlabData(&process_units,PROCESSUNITS);
+	FetchMatlabData(&weight_index,WEIGHTINDEX);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Call core code: */
+	Responsex(&resp, elements,nodes,vertices, loads,materials,parameters,response,process_units,weight_index);
+
+	/*write output : */
+	WriteMatlabData(OUTPUT,resp);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+	xfree((void**)&response);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void ResponseUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [resp] = %s(elements,nodes,vertices,loads,materials,parameters,response,process_units);\n",__FUNCT__);
+	_printf_(true,"\n");
+	_printf_(true,"      response:      string ('MinVel', 'MassFlux', 'MaxAbsVx',...)\n");
+	_printf_(true,"      process_units: bolean\n");
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/Response/Response.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Response/Response.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Response/Response.h	(revision 11330)
@@ -0,0 +1,42 @@
+/*
+	Response.h
+*/
+
+#ifndef _RESPONSE_H
+#define _RESPONSE_H
+
+/* local prototypes: */
+void ResponseUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Response"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADS (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+#define RESPONSE (mxArray*)prhs[6]
+#define PROCESSUNITS (mxArray*)prhs[7]
+#define WEIGHTINDEX (mxArray*)prhs[8]
+
+/* serial output macros: */
+#define OUTPUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  9
+
+#endif  /* _RESPONSE_H */
+
+
+
Index: /issm/trunk-jpl-damage/src/mex/Scotch/Scotch.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Scotch/Scotch.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Scotch/Scotch.cpp	(revision 11330)
@@ -0,0 +1,267 @@
+/*\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"
+
+/******************************/
+/*                            */
+/* This is the main function. */
+/*                            */
+/******************************/
+
+void mexFunction( int nlhs,
+				  mxArray *plhs[],
+				  int nrhs,
+				  const mxArray *prhs[] )
+{
+
+#ifndef _HAVE_SCOTCH_ //only works if scotch library has been compiled in.
+	_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_
+}
+
+void GmapUsage( void )
+{
+
+    mexPrintf("\n");
+    mexPrintf("Usage: [maptab]=Scotch(adjmat,vertlb,vertwt,edgewt,archtyp,archpar,\n");
+    mexPrintf("                         Scotch-specific parameters);\n");
+    mexPrintf("\n");
+
+    return;
+}
+
Index: /issm/trunk-jpl-damage/src/mex/Scotch/Scotch.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Scotch/Scotch.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Scotch/Scotch.h	(revision 11330)
@@ -0,0 +1,38 @@
+/*!\file:  Scotch.h
+ * \brief header file for Scotch module.
+ */ 
+
+#ifndef _SCOTCH_H
+#define _SCOTCH_H
+
+/* local prototypes: */
+void GmapUsage(void);
+
+#include <stdio.h>
+#include <string.h>    /*  strcasecmp  */
+#include <time.h>      /*  clock,time,difftime  */
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.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/trunk-jpl-damage/src/mex/Shp2Kml/Shp2Kml.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Shp2Kml/Shp2Kml.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Shp2Kml/Shp2Kml.cpp	(revision 11330)
@@ -0,0 +1,117 @@
+/*\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 mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	int i,verbose=1;
+
+	/*input: */
+	char    *filshp=NULL,*filkml=NULL;
+	int     sgn;
+
+	Options* options=NULL;
+	double   cm=0.,sp=0.;
+
+	/* output: */
+	int     iret=0;
+
+	#ifndef _HAVE_SHAPELIB_ //only works if shapelib library has been compiled in.
+	_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: */
+	if (verbose) printf("Fetching inputs:\n");
+	FetchMatlabData(&filshp,SHP_IN);
+	if (verbose) printf("  filshp=\"%s\"\n",filshp);
+	FetchMatlabData(&filkml,KML_IN);
+	if (verbose) printf("  filkml=\"%s\"\n",filkml);
+	FetchMatlabData(&sgn,SGN_IN);
+	if (verbose) printf("  sgn=%d\n",sgn);
+
+	if (verbose) printf("Parsing options:\n");
+	options=new Options(NRHS,nrhs,prhs);
+	if (options->Size()) for(i=0;i<options->Size();i++) ((Option*)options->GetObjectByOffset(i))->DeepEcho();
+	/*  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=%g\n",cm);
+		options->Get(&sp,"standard_parallel");
+		if (verbose) printf("  sp=%g\n",sp);
+	}
+
+	/*some checks*/
+	if (verbose) printf("Checking inputs:\n");
+
+	if (sgn < -1 || sgn > +1) _error_("Hemisphere sgn=%d must be +1 (north), -1 (south), or 0 (no translation).",sgn);
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=%g must be between -180 (west) and +180 (east) degrees.",cm);
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=%g must be between 0 and 90 degrees (in specified hemisphere).",sp);
+
+	/* Run core computations: */
+	if (verbose) printf("Calling core:\n");
+	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
+		iret=Shp2Kmlx(filshp,filkml,
+					  sgn,cm,sp);
+	else
+		iret=Shp2Kmlx(filshp,filkml,
+					  sgn);
+	if (verbose) printf("  iret=%d\n",iret);
+
+	/*Write data: */
+	WriteMatlabData(RET_OUT,iret);
+
+	/*Clean-up*/
+	delete options;
+	xfree((void**)&filkml);
+	xfree((void**)&filshp);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void Shp2KmlUsage(void)
+{
+	_printf_(true,"Shp2Kml - shp to kml file conversion module:\n");
+	_printf_(true,"\n");
+	_printf_(true,"   This module converts a file from shp to kml format.\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"      [ret]=Shp2Kml(filshp,filkml,sgn,'param name',param,...);\n");
+	_printf_(true,"\n");
+	_printf_(true,"      filshp      file name of shp file to be read (char, extension optional)\n");
+	_printf_(true,"      filkml      file name of kml file to be written (char)\n");
+	_printf_(true,"      sgn         sign for hemisphere (double, +1 (north); -1 (south); or 0 (no translation))\n");
+	_printf_(true,"\n");
+	_printf_(true,"      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf_(true,"      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf_(true,"\n");
+	_printf_(true,"      ret         return code (non-zero for warning)\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Examples:\n");
+	_printf_(true,"      [ret]=Shp2Kml('file.shp','file.kml', 0);\n");
+	_printf_(true,"      [ret]=Shp2Kml('file.shp','file.kml', 1,'central_meridian',45,'standard_parallel',70);\n");
+	_printf_(true,"      [ret]=Shp2Kml('file.shp','file.kml',-1,'central_meridian', 0,'standard_parallel',71);\n");
+	_printf_(true,"\n");
+}
+
Index: /issm/trunk-jpl-damage/src/mex/Shp2Kml/Shp2Kml.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Shp2Kml/Shp2Kml.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Shp2Kml/Shp2Kml.h	(revision 11330)
@@ -0,0 +1,34 @@
+/*!\file Shp2Kml.h
+ * \brief: prototype for shp to kml file conversion mex module.
+ */
+
+#ifndef _SHP2KML_H
+#define _SHP2KML_H
+
+/* local prototypes: */
+void Shp2KmlUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Shp2Kml"
+
+
+/* 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]
+
+/* serial arg counts: */
+#undef NRHS
+#define NRHS  3
+#undef NLHS
+#define NLHS  1
+
+#endif
+
Index: /issm/trunk-jpl-damage/src/mex/Solver/Solver.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Solver/Solver.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Solver/Solver.cpp	(revision 11330)
@@ -0,0 +1,84 @@
+/*\file Solver.c
+ *\brief: solver
+ */
+
+#include "./Solver.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Mat         Kff           = NULL;
+	Vec         pf            = NULL;
+	Vec         uf0           = NULL;
+	Vec         uf            = NULL;
+	Vec         df            = NULL;
+	Parameters *parameters    = NULL;
+	int         analysis_type;
+	char        option[100];
+	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
+	PetscTruth  flag;
+	#else
+	PetscBool flag;
+	#endif
+	
+	/*Matlab solver: */
+	mxArray* array[2];
+
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&SolverUsage);
+	
+	/*parameters: */
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*In serial mode, we have not set any petsc options, do it now: */
+	#ifdef _SERIAL_
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	PetscOptionsFromAnalysis(parameters,analysis_type);
+	#endif
+	
+	/*Retrieve solver type: */
+	PetscOptionsGetString(PETSC_NULL,"-ksp_type",&option[0],100,&flag);
+
+	/*Fetch rest of data only if not running the matlab solver: */
+	if (strcmp(option,"matlab")!=0){
+	
+		/*Input datasets: */
+		FetchMatlabData(&Kff,KFF);
+		FetchMatlabData(&pf,PF);
+		FetchMatlabData(&uf0,UF0);
+		FetchMatlabData(&df,DF);
+
+		/*Core module: */
+		Solverx(&uf, Kff, pf, uf0, df,parameters);
+
+		/*Write output*/
+		WriteMatlabData(UF,uf);
+	}
+	else{
+		/*Matlab solver: */
+		if (VerboseModule()) printf("   Solving\n");
+		array[0]=KFF;
+		array[1]=PF;
+		mexCallMATLAB(1,UF,2,array,"mldivide");
+	}
+
+	/*Free ressources: */
+	MatFree(&Kff);
+	VecFree(&pf);
+	VecFree(&uf0);
+	VecFree(&uf);
+	VecFree(&df);
+	delete parameters;
+
+	MODULEEND();
+
+}
+
+void SolverUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [uf] = %s(Kff,pf,uf0,df,parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/Solver/Solver.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Solver/Solver.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Solver/Solver.h	(revision 11330)
@@ -0,0 +1,39 @@
+
+/*
+	Solver.h
+*/
+
+
+#ifndef _SOLVER_H
+#define _SOLVER_H
+
+/* local prototypes: */
+void SolverUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Solver"
+
+/* serial input macros: */
+#define KFF (mxArray*)prhs[0]
+#define PF (mxArray*)prhs[1]
+#define UF0 (mxArray*)prhs[2]
+#define DF (mxArray*)prhs[3]
+#define PARAMETERS (mxArray*)prhs[4]
+
+/* serial output macros: */
+#define UF (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  5
+
+
+#endif  /* _SOLVER_H */
+
Index: /issm/trunk-jpl-damage/src/mex/SparseToVector/SparseToVector.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/SparseToVector/SparseToVector.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/SparseToVector/SparseToVector.cpp	(revision 11330)
@@ -0,0 +1,87 @@
+/*\file SparseToVector.cpp
+ *\brief: extract from a sparse matlab matrix ir, jc, and other information 
+ */
+
+#include "./SparseToVector.h"
+
+void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) {
+	
+	int     i;
+	
+	/*Output: */
+	mwIndex *ir =NULL;
+	mwIndex *jc =NULL;
+	double  *ird=NULL;
+	double  *jcd=NULL;
+	double   *pr=NULL;
+	double   *prd=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&SparseToVectorUsage);
+
+	/* Create matrices for the return arguments */
+	if (!mxIsNumeric(A_IN) || !mxIsSparse(A_IN)) {
+		mexPrintf("%s -- Input matrix must be numeric and sparse.\n",__FUNCT__);
+		mexErrMsgTxt(" ");
+	}
+	else {
+		if (nlhs >= 4) {
+			M_OUT    =mxCreateDoubleMatrix(1, 1, mxREAL);
+			*mxGetPr(M_OUT)    =mxGetM(A_IN);
+			if (nlhs >= 5) {
+				N_OUT    =mxCreateDoubleMatrix(1, 1, mxREAL);
+				*mxGetPr(N_OUT)    =mxGetN(A_IN);
+				if (nlhs >= 6) {
+					NZMAX_OUT=mxCreateDoubleMatrix(1, 1, mxREAL);
+					*mxGetPr(NZMAX_OUT)=mxGetNzmax(A_IN);
+				}
+			}
+		}
+		if (mxGetNzmax(A_IN)) {
+			ir    =mxGetIr(A_IN);
+			IR_OUT=mxCreateDoubleMatrix(mxGetNzmax(A_IN), 1, mxREAL);
+			ird = mxGetPr(IR_OUT);
+			for (i=0; i<mxGetNzmax(A_IN); i++)
+				ird[i]=(double)ir[i];
+			if (nlhs >= 3) {
+				pr    =mxGetPr(A_IN);
+				PR_OUT=mxCreateDoubleMatrix(mxGetNzmax(A_IN), 1, mxREAL);
+				prd = mxGetPr(PR_OUT);
+				for (i=0; i<mxGetNzmax(A_IN); i++)
+					prd[i]=(double)pr[i];
+			}
+		}
+		else {
+			IR_OUT=mxCreateDoubleMatrix(0, 0, mxREAL);
+			if (nlhs >= 3) {
+				PR_OUT=mxCreateDoubleMatrix(0, 0, mxREAL);
+			}
+		}
+		if (mxGetN(A_IN)) {
+			jc    =mxGetJc(A_IN);
+			JC_OUT=mxCreateDoubleMatrix(mxGetN(A_IN)+1, 1, mxREAL);
+			jcd = mxGetPr(JC_OUT);
+			for (i=0; i<(mxGetN(A_IN)+1); i++)
+				jcd[i]=(double)jc[i];
+		}
+		else {
+			JC_OUT=mxCreateDoubleMatrix(0, 0, mxREAL);
+		}
+		mexPrintf("%s -- Input matrix is of size %d by %d with %d non-zeroes.\n",
+				  __FUNCT__,mxGetM(A_IN),mxGetN(A_IN),mxGetNzmax(A_IN));
+	}
+	
+	/*end module: */
+	MODULEEND();
+}
+
+void SparseToVectorUsage( void ){
+
+    mexPrintf("\n");
+    mexPrintf("Usage: [ir,jc,pr,m,n,nzmax]=SparseToVector(a);\n");
+    mexPrintf("\n");
+}
+
Index: /issm/trunk-jpl-damage/src/mex/SparseToVector/SparseToVector.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/SparseToVector/SparseToVector.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/SparseToVector/SparseToVector.h	(revision 11330)
@@ -0,0 +1,39 @@
+/*
+	SparseToVector.h
+*/
+
+#ifndef _SPARSETOVECTOR_H
+#define _SPARSETOVECTOR_H
+
+/* local prototypes: */
+void SparseToVectorUsage(void);
+
+#include <stdio.h>
+#include <string.h>    /*  strcasecmp  */
+#include <time.h>      /*  clock,time,difftime  */
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "SparseToVector"
+
+/* serial input macros: */
+#define    A_IN         prhs[0]
+
+/* serial output macros: */
+#define    IR_OUT       plhs[0]
+#define    JC_OUT       plhs[1]
+#define    PR_OUT       plhs[2]
+#define    M_OUT        plhs[3]
+#define    N_OUT        plhs[4]
+#define    NZMAX_OUT    plhs[5]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  6
+#undef NRHS
+#define NRHS  1
+
+#endif  /* _SPARSETOVECTOR_H */
Index: /issm/trunk-jpl-damage/src/mex/SpcNodes/SpcNodes.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/SpcNodes/SpcNodes.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/SpcNodes/SpcNodes.cpp	(revision 11330)
@@ -0,0 +1,48 @@
+/*\file SpcNodes.c
+ *\brief: build degrees of freedom for every node.
+ */
+
+#include "./SpcNodes.h"
+
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Nodes* nodes=NULL;
+	Parameters* parameters=NULL;
+	Constraints* constraints=NULL;
+	int      analysis_type;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&SpcNodesUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&nodes,NODESIN);
+	FetchMatlabData((DataSet**)&constraints,CONSTRAINTS);
+	FetchMatlabData(&parameters,PARAMETERS);
+	FetchMatlabData(&analysis_type,ANALYSISTYPE);
+	
+	/*!Generate internal degree of freedom numbers: */
+	SpcNodesx(nodes,constraints,parameters,analysis_type); 
+
+	/*write output datasets: */
+	WriteMatlabData(NODES,nodes);
+
+	/*Free ressources: */
+	delete nodes;
+	delete constraints;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void SpcNodesUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [m.node]=%s(m.nodes,m.constraints,m.parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/SpcNodes/SpcNodes.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/SpcNodes/SpcNodes.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/SpcNodes/SpcNodes.h	(revision 11330)
@@ -0,0 +1,37 @@
+
+/*
+	SpcNodes.h
+*/
+
+
+#ifndef _SPCNODES_H
+#define _SPCNODES_H
+
+/* local prototypes: */
+void SpcNodesUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "SpcNodes"
+
+/* serial input macros: */
+#define NODESIN (mxArray*)prhs[0]
+#define CONSTRAINTS (mxArray*)prhs[1]
+#define PARAMETERS (mxArray*)prhs[2]
+#define ANALYSISTYPE (mxArray*)prhs[3]
+
+/* serial output macros: */
+#define NODES (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  4
+
+
+#endif  /* _SPCNODES_H */
+
Index: /issm/trunk-jpl-damage/src/mex/StringToEnum/StringToEnum.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/StringToEnum/StringToEnum.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/StringToEnum/StringToEnum.cpp	(revision 11330)
@@ -0,0 +1,32 @@
+/*\file StringToEnum.c
+ *\brief:convert enum (int) to string
+ */
+
+#include "./StringToEnum.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	char    *name    = NULL;
+	int      enum_out;
+
+	/*checks on arguments on the matlab side: */
+	if(nrhs!=NRHS){
+		StringToEnumUsage(); _error_(" usage. See above");
+	}
+
+	/*Fetch inputs: */
+	FetchMatlabData(&name,NAME);
+
+	/*Run core function: */
+	enum_out=StringToEnumx(name);
+
+	/* output: */
+	WriteMatlabData(ENUMOUT,enum_out);
+}
+
+void StringToEnumUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: %senum = StringToEnum(string);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/StringToEnum/StringToEnum.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/StringToEnum/StringToEnum.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/StringToEnum/StringToEnum.h	(revision 11330)
@@ -0,0 +1,30 @@
+/*!\file:  StringToEnum.h
+ * \brief header file for StringToEnum module.
+ */ 
+
+#ifndef _STRINGTOENUM_H
+#define _STRINGTOENUM_H
+
+/* local prototypes: */
+void StringToEnumUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+    
+/* serial input macros: */
+#define NAME (mxArray*)prhs[0]
+
+/* serial output macros: */
+#define ENUMOUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  1
+
+#undef __FUNCT__ 
+#define __FUNCT__  "StringToEnum"
+
+#endif  /* _TEST_H */
Index: /issm/trunk-jpl-damage/src/mex/SurfaceArea/SurfaceArea.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/SurfaceArea/SurfaceArea.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/SurfaceArea/SurfaceArea.cpp	(revision 11330)
@@ -0,0 +1,60 @@
+/*\file SurfaceArea.c
+ *\brief: duplicate input
+ */
+
+#include "./SurfaceArea.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements   *elements   = NULL;
+	Nodes      *nodes      = NULL;
+	Vertices   *vertices   = NULL;
+	Loads      *loads      = NULL;
+	Materials  *materials  = NULL;
+	Parameters *parameters = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&SurfaceAreaUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Call core code: */
+	SurfaceAreax(NULL,elements, nodes, vertices, loads, materials,parameters);
+
+	/*write output : */
+	WriteMatlabData(ELEMENTSOUT,elements);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+	
+	/*end module: */
+	MODULEEND();
+
+}
+
+void SurfaceAreaUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements] = %s(elements, nodes, vertices, loads, materials, parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/SurfaceArea/SurfaceArea.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/SurfaceArea/SurfaceArea.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/SurfaceArea/SurfaceArea.h	(revision 11330)
@@ -0,0 +1,35 @@
+/*
+	SurfaceArea.h
+*/
+
+#ifndef _SURFACEAREA_H
+#define _SURFACEAREA_H
+
+/* local prototypes: */
+void SurfaceAreaUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "SurfaceArea"
+
+/* serial input macros: */
+#define ELEMENTS (mxArray*)prhs[0]
+#define NODES (mxArray*)prhs[1]
+#define VERTICES (mxArray*)prhs[2]
+#define LOADS (mxArray*)prhs[3]
+#define MATERIALS (mxArray*)prhs[4]
+#define PARAMETERS (mxArray*)prhs[5]
+
+/* serial output macros: */
+#define ELEMENTSOUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  6
+
+#endif  /* _INPUTTORESULT_H */
Index: /issm/trunk-jpl-damage/src/mex/SystemMatrices/SystemMatrices.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/SystemMatrices/SystemMatrices.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/SystemMatrices/SystemMatrices.cpp	(revision 11330)
@@ -0,0 +1,89 @@
+/*\file SystemMatrices.c
+ *\brief: build system matrices (stiffness matrix, loads vector)
+ */
+
+#include "./SystemMatrices.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements   *elements   = NULL;
+	Nodes      *nodes      = NULL;
+	Vertices   *vertices   = NULL;
+	Loads      *loads      = NULL;
+	Materials  *materials  = NULL;
+	Parameters *parameters = NULL;
+	bool        kflag,pflag,penalty_kflag,penalty_pflag;
+	
+	/* output datasets: */
+	Mat    Kff  = NULL;
+	Mat    Kfs  = NULL;
+	Vec    pf   = NULL;
+	Vec    df   = NULL;
+
+	double kmax;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if((nlhs!=NLHS) || (nrhs!=6 && nrhs!=10)){
+		SystemMatricesUsage();
+		_error_(" usage. See above");
+	}
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTS);
+	FetchMatlabData((DataSet**)&nodes,NODES);
+	FetchMatlabData((DataSet**)&vertices,VERTICES);
+	FetchMatlabData((DataSet**)&loads,LOADS);
+	FetchMatlabData((DataSet**)&materials,MATERIALS);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+	materials-> Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*!Generate internal degree of freedom numbers: */
+	if(nrhs==10){
+		FetchMatlabData(&kflag,KFLAG);
+		FetchMatlabData(&pflag,PFLAG);
+		FetchMatlabData(&penalty_kflag,PENALTYKFLAG);
+		FetchMatlabData(&penalty_pflag,PENALTYPFLAG);
+		SystemMatricesx(&Kff,&Kfs,&pf,&df,&kmax,elements,nodes,vertices,loads,materials,parameters,kflag,pflag,penalty_kflag,penalty_pflag);
+	}
+	else
+	 SystemMatricesx(&Kff,&Kfs,&pf,&df,&kmax,elements,nodes,vertices,loads,materials,parameters);
+
+	/*write output datasets: */
+	WriteMatlabData(KFF,Kff);
+	WriteMatlabData(KFS,Kfs);
+	WriteMatlabData(PF,pf);
+	WriteMatlabData(DF,df);
+	WriteMatlabData(KMAX,kmax);
+	
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+	MatFree(&Kff);
+	MatFree(&Kfs);
+	VecFree(&pf);
+	VecFree(&df);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void SystemMatricesUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [Kff,Kfs,pf,df,kmax] = %s(elements,nodes,vertices,loads,materials,parameters);\n",__FUNCT__);
+	_printf_(true,"   usage: [Kff,Kfs,pf,df,kmax] = %s(elements,nodes,vertices,loads,materials,parameters,kflag,pflag,penalty_kflag,penalty_pflag);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/SystemMatrices/SystemMatrices.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/SystemMatrices/SystemMatrices.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/SystemMatrices/SystemMatrices.h	(revision 11330)
@@ -0,0 +1,44 @@
+/*
+	SystemMatrices.h
+*/
+
+#ifndef _SYSTEMMATRICES_H
+#define _SYSTEMMATRICES_H
+
+/* local prototypes: */
+void SystemMatricesUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "SystemMatrices"
+
+/* serial input macros: */
+#define ELEMENTS     (mxArray *)prhs[0]
+#define NODES        (mxArray *)prhs[1]
+#define VERTICES     (mxArray *)prhs[2]
+#define LOADS        (mxArray *)prhs[3]
+#define MATERIALS    (mxArray *)prhs[4]
+#define PARAMETERS   (mxArray *)prhs[5]
+#define KFLAG        (mxArray *)prhs[6]
+#define PFLAG        (mxArray *)prhs[7]
+#define PENALTYKFLAG (mxArray *)prhs[8]
+#define PENALTYPFLAG (mxArray *)prhs[9]
+
+/* serial output macros: */
+#define KFF  (mxArray**)&plhs[0]
+#define KFS  (mxArray**)&plhs[1]
+#define PF   (mxArray**)&plhs[2]
+#define DF   (mxArray**)&plhs[3]
+#define KMAX (mxArray**)&plhs[4]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  5
+#undef NRHS
+#define NRHS  10
+
+#endif  /* _SYSTEMMATRICES_H */
Index: /issm/trunk-jpl-damage/src/mex/Test/Test.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Test/Test.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Test/Test.cpp	(revision 11330)
@@ -0,0 +1,31 @@
+/*\file Test.c
+ *\brief:  test module. do whatever you want in here
+ */
+
+#include "./Test.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	char *string = NULL;
+	PetscErrorCode ierr;
+
+	FetchMatlabData(&string,STRING);
+
+	 if (!strcmp(string,"Init")){
+		 ierr=PetscInitializeNoArguments();
+		 ierr=PetscPopSignalHandler();
+	 }
+	 else if(!strcmp(string,"Finalize")) {
+		 ierr=PetscFinalize();
+	 }
+	 else{
+		 printf("NOTHING to be done\n");
+	 }
+}
+
+void TestUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: %s(whatever in here);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/Test/Test.cpp.grid
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Test/Test.cpp.grid	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Test/Test.cpp.grid	(revision 11330)
@@ -0,0 +1,43 @@
+/*\file Test.c
+ *\brief:  test module. do whatever you want in here
+ */
+
+#include "./Test.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&TestUsage);
+
+	double* pr=mxGetPr(prhs[0]);
+	int M=mxGetM(prhs[0]);
+	int N=mxGetM(prhs[0]);
+	mwIndex* ir=mxGetIr(prhs[0]);
+	mwIndex* jc=mxGetJc(prhs[0]);
+	int     nzmax=(int)mxGetNzmax(prhs[0]);
+
+	int i;
+	printf("nzmax %i\n",nzmax);
+	printf("jc:\n");
+	for(i=0;i<N+1;i++){
+		printf("%i\n",jc[i]);
+	}
+	printf("ir vale:\n");
+	for(i=0;i<nzmax;i++){
+		printf("%i %g\n",ir[i],pr[i]);
+	}	
+
+
+	/*end module: */
+	MODULEEND();
+}
+
+void TestUsage(void)
+{
+	_printf_("\n");
+	_printf_("   usage: %s(whatever in here);\n",__FUNCT__);
+	_printf_("\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/Test/Test.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Test/Test.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Test/Test.h	(revision 11330)
@@ -0,0 +1,27 @@
+/*!\file:  Test.h
+ * \brief header file for Test module.
+ */ 
+
+#ifndef _TEST_H
+#define _TEST_H
+
+/* local prototypes: */
+void TestUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+    
+/* serial input macros: */
+#define STRING (mxArray*)prhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  0
+#undef NRHS
+#define NRHS  1
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Test"
+
+#endif  /* _TEST_H */
Index: /issm/trunk-jpl-damage/src/mex/TimeAdapt/TimeAdapt.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/TimeAdapt/TimeAdapt.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/TimeAdapt/TimeAdapt.cpp	(revision 11330)
@@ -0,0 +1,62 @@
+/*\file TimeAdapt.c
+*\brief: update time steps to respect CFL condition
+*/
+
+#include "./TimeAdapt.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+/*input datasets: */
+Elements*   elements          = NULL;
+Nodes      *nodes             = NULL;
+Vertices    *vertices          = NULL;
+Loads     *loads             = NULL;
+Materials   *materials         = NULL;
+Parameters *parameters        = NULL;
+
+/*output*/
+double dt;
+
+/*Boot module: */
+MODULEBOOT();
+
+/*checks on arguments on the matlab side: */
+CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&TimeAdaptUsage);
+
+/*Input datasets: */
+FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+FetchMatlabData((DataSet**)&nodes,NODESIN);
+FetchMatlabData((DataSet**)&vertices,VERTICESIN);
+FetchMatlabData((DataSet**)&loads,LOADSIN);
+FetchMatlabData((DataSet**)&materials,MATERIALSIN);
+FetchMatlabData(&parameters,PARAMETERSIN);
+
+/*configure: */
+elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+/*call "x" code layer*/
+TimeAdaptx(&dt,elements,nodes,vertices,loads, materials,parameters);
+
+/*write output datasets: */
+WriteMatlabData(DT,dt);
+
+/*Free ressources: */
+delete elements;
+delete nodes;
+delete vertices;
+delete loads;
+delete materials;
+delete parameters;
+
+/*end module: */
+MODULEEND();
+}
+
+void TimeAdaptUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: dt = %s(elements,nodes,vertices,loads,materials,parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/TimeAdapt/TimeAdapt.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/TimeAdapt/TimeAdapt.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/TimeAdapt/TimeAdapt.h	(revision 11330)
@@ -0,0 +1,37 @@
+/*
+	TimeAdapt.h
+*/
+
+#ifndef _TIMEADAPT_H
+#define _TIMEADAPT_H
+
+/* local prototypes: */
+void TimeAdaptUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "TimeAdapt"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODESIN (mxArray*)prhs[1]
+#define VERTICESIN (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALSIN (mxArray*)prhs[4]
+#define PARAMETERSIN (mxArray*)prhs[5]
+
+/* serial output macros: */
+#define DT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  6
+
+#endif  /* _TIMEADAPT_H */
+
Index: /issm/trunk-jpl-damage/src/mex/TriMesh/TriMesh.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/TriMesh/TriMesh.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/TriMesh/TriMesh.cpp	(revision 11330)
@@ -0,0 +1,323 @@
+/*
+ * TriMesh: out of a domain outline file ( Argus format ), 
+ * use the Triangle package to create a triangular mesh 
+ *
+ */
+
+#include "./TriMesh.h"
+
+
+void mexFunction(	int nlhs, mxArray* plhs[],
+					int nrhs, const mxArray* prhs[] )
+{
+
+
+	/*Matlab arrays: */
+	mxArray* pmxa_array=NULL;
+	int i,j;
+	int counter,counter2,backcounter;
+	int prhs_counter;
+	
+	/* returned quantities: */
+
+	double* index=NULL;
+	double* x=NULL;
+	double* y=NULL;
+	double* segments=NULL;
+	double*    segmentmarkerlist=NULL;
+
+	/* input: */
+	char*  domainname=NULL;
+	char*  riftname=NULL;
+	double area;
+	char*  order=NULL;
+	
+	/*Domain outline variables: */
+	int      nprof;
+	int*     profnvertices=NULL;
+	double** pprofx=NULL;
+	double** pprofy=NULL;
+	double*  xprof=NULL;
+	double*  yprof=NULL;
+	int      numberofpoints;
+
+	/*Rift outline variables: */
+	int      numrifts;
+	int*     riftsnumvertices=NULL;
+	double** riftsverticesx=NULL;
+	double** riftsverticesy=NULL;
+
+	/* Triangle structures: */
+	struct triangulateio in,out;
+	char   options[256];
+
+	/* verify correct usage: */
+	if (nlhs==0 && nrhs==0) {
+		/* special case: */
+		TriMeshUsage();
+		return;
+	}
+
+	if (!(  (nlhs==5) ||(nrhs==2) || (nrhs==3)  || (nrhs==4) )){
+		mexPrintf("   %s format error.\n", __FUNCT__);
+		TriMeshUsage();
+		printf("   ");
+		mexErrMsgTxt(" ");
+	}
+
+	/*Fetch data needed by Triangle: */
+
+	prhs_counter=0;
+	/*First recover the domain outline file name: */
+	if (!mxIsChar(prhs[prhs_counter])){
+		mexPrintf("%s%s\n",__FUNCT__," error message; first argument should be the domain outline file name!");
+		mexErrMsgTxt(" ");
+	}
+	domainname = (char *) mxMalloc((mxGetN(prhs[prhs_counter])+1)*sizeof(char));
+	mxGetString(prhs[prhs_counter],domainname,mxGetN(prhs[prhs_counter])+1);
+
+	/*Look for optional rifts file name: */
+	prhs_counter++;
+	if (mxIsChar(prhs[prhs_counter])){
+		riftname = (char *) mxMalloc((mxGetN(prhs[prhs_counter])+1)*sizeof(char));
+		mxGetString(prhs[prhs_counter],riftname,mxGetN(prhs[prhs_counter])+1);
+		prhs_counter++;
+	}
+
+	/*Recover the mesh density desired:*/
+	area=mxGetScalar(prhs[prhs_counter]);
+
+	/*Optionaly, recover desired order: */
+	prhs_counter++;
+	if (mxIsChar(prhs[prhs_counter])){
+		order = (char *) mxMalloc((mxGetN(prhs[prhs_counter])+1)*sizeof(char));
+		mxGetString(prhs[prhs_counter],order,mxGetN(prhs[prhs_counter])+1);
+	}
+	
+	/*Start reading the domain outline file: */
+	if(!DomainOutlineRead(&nprof,&profnvertices,&pprofx,&pprofy,NULL,domainname,false)){
+		printf("%s%s%s\n",__FUNCT__," error message reading domain outline ",domainname);
+		mexErrMsgTxt(" ");
+	}
+
+	/*Read rifts file if present: */
+	if(riftname){
+		if(!DomainOutlineRead(&numrifts,&riftsnumvertices,&riftsverticesx,&riftsverticesy,NULL,riftname,false)){
+			printf("%s%s%s\n",__FUNCT__," error message reading rifts outline ",riftname);
+			mexErrMsgTxt(" ");
+		}
+	}
+
+	/*Create initial triangulation to call triangulate():*/
+	numberofpoints=0;
+	for (i=0;i<nprof;i++){
+		numberofpoints+=profnvertices[i];
+	}
+	if (riftname){
+		for (i=0;i<numrifts;i++){
+			numberofpoints+=riftsnumvertices[i];
+		}
+	}
+	in.numberofpoints=numberofpoints;
+
+	in.numberofpointattributes=1;
+	in.pointlist = (REAL *) mxMalloc(in.numberofpoints * 2 * sizeof(REAL));
+
+	counter=0;
+	for (i=0;i<nprof;i++){
+		xprof=pprofx[i];
+		yprof=pprofy[i];
+		for (j=0;j<profnvertices[i];j++){
+			in.pointlist[2*counter+0]=xprof[j];
+			in.pointlist[2*counter+1]=yprof[j];
+			counter++;
+		}
+	}
+	if(riftname){
+		for (i=0;i<numrifts;i++){
+			xprof=riftsverticesx[i];
+			yprof=riftsverticesy[i];
+			for (j=0;j<riftsnumvertices[i];j++){
+				in.pointlist[2*counter+0]=xprof[j];
+				in.pointlist[2*counter+1]=yprof[j];
+				counter++;
+			}
+		}
+	}
+	
+	in.pointattributelist = (REAL *) mxMalloc(in.numberofpoints *
+										  in.numberofpointattributes *
+										  sizeof(REAL));
+	for (i=0;i<in.numberofpoints;i++){
+		in.pointattributelist[i] = 0.0;
+	}
+	in.pointmarkerlist = (int *) mxMalloc(in.numberofpoints * sizeof(int));
+	for(i=0;i<in.numberofpoints;i++){
+		in.pointmarkerlist[i] = 0;
+	}
+
+	/*Build segments: */
+	/*Figure out number of segments: holes and closed outlines have as many segments as vertices, 
+	 *for rifts, we have one less segment as we have vertices*/
+	in.numberofsegments=0;
+	for (i=0;i<nprof;i++){
+		in.numberofsegments+=profnvertices[i];
+	}
+	if (riftname){
+		for (i=0;i<numrifts;i++){
+			in.numberofsegments+=riftsnumvertices[i]-1;
+		}
+	}
+	
+	in.segmentlist = (int *) mxMalloc(in.numberofsegments * 2 * sizeof(int));
+	in.segmentmarkerlist = (int *) mxCalloc(in.numberofsegments,sizeof(int));
+	counter=0;
+	backcounter=0;
+	for (i=0;i<nprof;i++){
+		for (j=0;j<(profnvertices[i]-1);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;
+	if(riftname){
+		for (i=0;i<numrifts;i++){
+			for (j=0;j<(riftsnumvertices[i]-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 = nprof-1; /*everything is a hole, but for the first profile.*/
+	in.holelist = (REAL *) mxMalloc(in.numberofholes * 2 * sizeof(REAL));
+	for (i=0;i<nprof-1;i++){
+		/*We are looking for a vertex that lies inside the hole: */
+		GridInsideHole(&in.holelist[2*i+0],&in.holelist[2*i+1],profnvertices[i+1],pprofx[i+1],pprofy[i+1]);
+	}
+
+	/* 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=(double*)mxMalloc(3*out.numberoftriangles*sizeof(double));
+	x=(double*)mxMalloc(out.numberofpoints*sizeof(double));
+	y=(double*)mxMalloc(out.numberofpoints*sizeof(double));
+	segments=(double*)mxMalloc(3*out.numberofsegments*sizeof(double));
+	segmentmarkerlist=(double*)mxMalloc(out.numberofsegments*sizeof(double));
+
+	for (i = 0; i < out.numberoftriangles; i++) {
+		for (j = 0; j < out.numberofcorners; j++) {
+			*(index+3*i+j)=(double)out.trianglelist[i * out.numberofcorners + j]+1;
+		}
+	}
+	for (i = 0; i < out.numberofpoints; i++) {
+		x[i]=out.pointlist[i * 2 + 0];
+		y[i]=out.pointlist[i * 2 + 1];
+	}
+	
+	for (i = 0; i < out.numberofsegments; i++) {
+		segments[3*i+0]=(double)out.segmentlist[i*2+0]+1;
+		segments[3*i+1]=(double)out.segmentlist[i*2+1]+1;
+		segmentmarkerlist[i]=(double)out.segmentmarkerlist[i];
+	}
+
+	/*Associate elements with segments: */
+	AssociateSegmentToElement(&segments,out.numberofsegments,index,out.numberoftriangles);
+
+	/*Order segments so that their normals point outside the domain: */
+	if(!strcmp(order,"yes")){
+		OrderSegments(&segments,out.numberofsegments, index,out.numberoftriangles);
+	}
+
+	/*Output : */
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,3);
+	mxSetN(pmxa_array,out.numberoftriangles);
+	mxSetPr(pmxa_array,index);
+	mexCallMATLAB( 1, &plhs[0], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,1);
+	mxSetN(pmxa_array,out.numberofpoints);
+	mxSetPr(pmxa_array,x);
+	mexCallMATLAB( 1, &plhs[1], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,1);
+	mxSetN(pmxa_array,out.numberofpoints);
+	mxSetPr(pmxa_array,y);
+	mexCallMATLAB( 1, &plhs[2], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,3);
+	mxSetN(pmxa_array,out.numberofsegments);
+	mxSetPr(pmxa_array,segments);
+	mexCallMATLAB( 1, &plhs[3], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,1);
+	mxSetN(pmxa_array,out.numberofsegments);
+	mxSetPr(pmxa_array,segmentmarkerlist);
+	mexCallMATLAB( 1, &plhs[4], 1, &pmxa_array, "transpose");
+	
+	return;
+}
+
+void TriMeshUsage(void)
+{
+	printf("\n");
+	printf("   usage: [index,x,y,segments,segmentmarkers]=TriMesh(domainoutlinefilename,riftsoutlinename,area,ordered) \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("      (if rifts are present, markers >=2 flag them ), outlinefilename an Argus domain outline file.\n");
+	printf("      riftsoutlinename is an Argus domain file, defining rifts (ie: open profiles), \n");
+	printf("      area is the maximum area desired for any element of the resulting mesh. \n");
+	printf("      and ordered is a string ('yes' or 'no') that determines whether segments are output in the \n");
+	printf("      order they are made by Triangle (ie none), or ordered counter clockwise around the domain outline.\n");
+	printf("      riftsoutlinename and ordered are optional arguments.\n");
+	printf("\n");
+}
+
+
+
+
Index: /issm/trunk-jpl-damage/src/mex/TriMesh/TriMesh.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/TriMesh/TriMesh.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/TriMesh/TriMesh.h	(revision 11330)
@@ -0,0 +1,21 @@
+/*!\file:  TriMesh.h
+ * \brief header prototype
+ */ 
+
+#ifndef _TRIMESH_H_
+#define _TRIMESH_H_
+
+#include "mex.h"
+#include "triangle.h"
+#include "string.h"
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+void TriMeshUsage(void);
+
+#undef __FUNCT__ 
+#define __FUNCT__ "TriMesh"
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/TriMeshNoDensity/TriMeshNoDensity.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/TriMeshNoDensity/TriMeshNoDensity.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/TriMeshNoDensity/TriMeshNoDensity.cpp	(revision 11330)
@@ -0,0 +1,305 @@
+/*
+ * TriMeshNoDensity: out of a domain outline file ( Argus format ), 
+ * use the Triangle package to create a triangular mesh 
+ *
+ */
+
+#include "./TriMeshNoDensity.h"
+
+
+void mexFunction(	int nlhs, mxArray* plhs[],
+					int nrhs, const mxArray* prhs[] )
+{
+
+
+	/*Matlab arrays: */
+	mxArray* pmxa_array=NULL;
+	int i,j;
+	int counter,counter2,backcounter;
+	int prhs_counter;
+	
+	/* returned quantities: */
+
+	double* index=NULL;
+	double* x=NULL;
+	double* y=NULL;
+	double* segments=NULL;
+	double*    segmentmarkerlist=NULL;
+
+	/* input: */
+	char*  domainname=NULL;
+	char*  riftname=NULL;
+	
+	/*Domain outline variables: */
+	int      nprof;
+	int*     profnvertices=NULL;
+	double** pprofx=NULL;
+	double** pprofy=NULL;
+	double*  xprof=NULL;
+	double*  yprof=NULL;
+	int      numberofpoints;
+
+	/*Rift outline variables: */
+	int      numrifts;
+	int*     riftsnumvertices=NULL;
+	double** riftsverticesx=NULL;
+	double** riftsverticesy=NULL;
+
+	/* Triangle structures: */
+	struct triangulateio in,out;
+	char   options[256];
+
+	/* verify correct usage: */
+	if (nlhs==0 && nrhs==0) {
+		/* special case: */
+		TriMeshNoDensityUsage();
+		return;
+	}
+
+	if (!(  (nlhs==5) ||(nrhs==2) || (nrhs==3)  )){
+		mexPrintf("   %s format error.\n", __FUNCT__);
+		TriMeshNoDensityUsage();
+		printf("   ");
+		mexErrMsgTxt(" ");
+	}
+
+	/*Fetch data needed by Triangle: */
+
+	prhs_counter=0;
+	/*First recover the domain outline file name: */
+	if (!mxIsChar(prhs[prhs_counter])){
+		mexPrintf("%s%s\n",__FUNCT__," error message; first argument should be the domain outline file name!");
+		mexErrMsgTxt(" ");
+	}
+	domainname = (char *) mxMalloc((mxGetN(prhs[prhs_counter])+1)*sizeof(char));
+	mxGetString(prhs[prhs_counter],domainname,mxGetN(prhs[prhs_counter])+1);
+
+	/*Look for optional rifts file name: */
+	if (nrhs==2){
+		prhs_counter++;
+		if (mxIsChar(prhs[prhs_counter])){
+			riftname = (char *) mxMalloc((mxGetN(prhs[prhs_counter])+1)*sizeof(char));
+			mxGetString(prhs[prhs_counter],riftname,mxGetN(prhs[prhs_counter])+1);
+			prhs_counter++;
+		}
+	}
+	
+	/*Start reading the domain outline file: */
+	if(!DomainOutlineRead(&nprof,&profnvertices,&pprofx,&pprofy,NULL,domainname,false)){
+		printf("%s%s%s\n",__FUNCT__," error message reading domain outline ",domainname);
+		mexErrMsgTxt(" ");
+	}
+
+	/*Read rifts file if present: */
+	if(riftname){
+		if(!DomainOutlineRead(&numrifts,&riftsnumvertices,&riftsverticesx,&riftsverticesy,NULL,riftname,false)){
+			printf("%s%s%s\n",__FUNCT__," error message reading rifts outline ",riftname);
+			mexErrMsgTxt(" ");
+		}
+	}
+
+	/*Create initial triangulation to call triangulate():*/
+	numberofpoints=0;
+	for (i=0;i<nprof;i++){
+		numberofpoints+=profnvertices[i];
+	}
+	if (riftname){
+		for (i=0;i<numrifts;i++){
+			numberofpoints+=riftsnumvertices[i];
+		}
+	}
+	in.numberofpoints=numberofpoints;
+
+	in.numberofpointattributes=1;
+	in.pointlist = (REAL *) mxMalloc(in.numberofpoints * 2 * sizeof(REAL));
+
+	counter=0;
+	for (i=0;i<nprof;i++){
+		xprof=pprofx[i];
+		yprof=pprofy[i];
+		for (j=0;j<profnvertices[i];j++){
+			in.pointlist[2*counter+0]=xprof[j];
+			in.pointlist[2*counter+1]=yprof[j];
+			counter++;
+		}
+	}
+	if(riftname){
+		for (i=0;i<numrifts;i++){
+			xprof=riftsverticesx[i];
+			yprof=riftsverticesy[i];
+			for (j=0;j<riftsnumvertices[i];j++){
+				in.pointlist[2*counter+0]=xprof[j];
+				in.pointlist[2*counter+1]=yprof[j];
+				counter++;
+			}
+		}
+	}
+	
+	in.pointattributelist = (REAL *) mxMalloc(in.numberofpoints *
+										  in.numberofpointattributes *
+										  sizeof(REAL));
+	for (i=0;i<in.numberofpoints;i++){
+		in.pointattributelist[i] = 0.0;
+	}
+	in.pointmarkerlist = (int *) mxMalloc(in.numberofpoints * sizeof(int));
+	for(i=0;i<in.numberofpoints;i++){
+		in.pointmarkerlist[i] = 0;
+	}
+	
+
+	/*Build segments: */
+	/*Figure out number of segments: holes and closed outlines have as many segments as vertices, 
+	 *for rifts, we have one less segment as we have vertices*/
+	in.numberofsegments=0;
+	for (i=0;i<nprof;i++){
+		in.numberofsegments+=profnvertices[i];
+	}
+	if (riftname){
+		for (i=0;i<numrifts;i++){
+			in.numberofsegments+=riftsnumvertices[i]-1;
+		}
+	}
+	
+	in.segmentlist = (int *) mxMalloc(in.numberofsegments * 2 * sizeof(int));
+	in.segmentmarkerlist = (int *) mxCalloc(in.numberofsegments,sizeof(int));
+	counter=0;
+	backcounter=0;
+	for (i=0;i<nprof;i++){
+		for (j=0;j<(profnvertices[i]-1);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;
+	if(riftname){
+		for (i=0;i<numrifts;i++){
+			for (j=0;j<(riftsnumvertices[i]-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 = nprof-1; /*everything is a hole, but for the first profile.*/
+	in.holelist = (REAL *) mxMalloc(in.numberofholes * 2 * sizeof(REAL));
+	for (i=0;i<nprof-1;i++){
+		/*We are looking for a vertex that lies inside the hole: */
+		GridInsideHole(&in.holelist[2*i+0],&in.holelist[2*i+1],profnvertices[i+1],pprofx[i+1],pprofy[i+1]);
+	}
+
+	/* 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","pQzDq30i"); /*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=(double*)mxMalloc(3*out.numberoftriangles*sizeof(double));
+	x=(double*)mxMalloc(out.numberofpoints*sizeof(double));
+	y=(double*)mxMalloc(out.numberofpoints*sizeof(double));
+	segments=(double*)mxMalloc(3*out.numberofsegments*sizeof(double));
+	segmentmarkerlist=(double*)mxMalloc(out.numberofsegments*sizeof(double));
+
+	for (i = 0; i < out.numberoftriangles; i++) {
+		for (j = 0; j < out.numberofcorners; j++) {
+			*(index+3*i+j)=(double)out.trianglelist[i * out.numberofcorners + j]+1;
+		}
+	}
+	for (i = 0; i < out.numberofpoints; i++) {
+		x[i]=out.pointlist[i * 2 + 0];
+		y[i]=out.pointlist[i * 2 + 1];
+	}
+	
+	for (i = 0; i < out.numberofsegments; i++) {
+		segments[3*i+0]=(double)out.segmentlist[i*2+0]+1;
+		segments[3*i+1]=(double)out.segmentlist[i*2+1]+1;
+		segmentmarkerlist[i]=(double)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 : */
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,3);
+	mxSetN(pmxa_array,out.numberoftriangles);
+	mxSetPr(pmxa_array,index);
+	mexCallMATLAB( 1, &plhs[0], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,1);
+	mxSetN(pmxa_array,out.numberofpoints);
+	mxSetPr(pmxa_array,x);
+	mexCallMATLAB( 1, &plhs[1], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,1);
+	mxSetN(pmxa_array,out.numberofpoints);
+	mxSetPr(pmxa_array,y);
+	mexCallMATLAB( 1, &plhs[2], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,3);
+	mxSetN(pmxa_array,out.numberofsegments);
+	mxSetPr(pmxa_array,segments);
+	mexCallMATLAB( 1, &plhs[3], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,1);
+	mxSetN(pmxa_array,out.numberofsegments);
+	mxSetPr(pmxa_array,segmentmarkerlist);
+	mexCallMATLAB( 1, &plhs[4], 1, &pmxa_array, "transpose");
+	
+	return;
+}
+
+void TriMeshNoDensityUsage(void)
+{
+	printf("\n");
+	printf("   usage: [index,x,y,segments,segmentmarkers]=TriMeshNoDensity(domainoutlinefilename,riftsoutlinename) \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("      (if rifts are present, markers >=2 flag them ), outlinefilename an Argus domain outline file.\n");
+	printf("      riftsoutlinename is an Argus domain file, defining rifts (ie: open profiles), \n");
+	printf("      riftsoutlinename is an optional arguments.\n");
+	printf("\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/TriMeshNoDensity/TriMeshNoDensity.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/TriMeshNoDensity/TriMeshNoDensity.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/TriMeshNoDensity/TriMeshNoDensity.h	(revision 11330)
@@ -0,0 +1,21 @@
+/*!\file:  TriMeshNoDensity.h
+ * \brief header prototype
+ */ 
+
+#ifndef _TRIMESH_H_
+#define _TRIMESH_H_
+
+#include "mex.h"
+#include "triangle.h"
+#include "string.h"
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+void TriMeshNoDensityUsage(void);
+
+#undef __FUNCT__ 
+#define __FUNCT__ "TriMeshNoDensity"
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/TriMeshProcessRifts/TriMeshProcessRifts.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 11330)
@@ -0,0 +1,328 @@
+/*!\file:  TriMeshProcessRifts.cpp
+ * \brief split a mesh where a rift (or fault) is present
+ */ 
+
+#include "./TriMeshProcessRifts.h"
+
+void mexFunction(	int nlhs, mxArray* plhs[],
+					int nrhs, const mxArray* prhs[] ) {
+
+
+	/*Matlab arrays: */
+	mxArray* pmxa_array=NULL;
+	mxArray* pmxa_array2=NULL;
+	mxArray* pmxa_array3=NULL;
+	int i,j,k,counter;
+	
+	/* returned quantities: */
+	int      out_numrifts;
+	int*     out_riftsnumsegments=NULL;
+	double** out_riftssegments=NULL; 
+	int*     out_riftsnumpairs=NULL;
+	double** out_riftspairs=NULL;
+	double*  out_riftstips=NULL;
+	double** out_riftspenaltypairs=NULL;
+	int*     out_riftsnumpenaltypairs=NULL;
+
+	/*empty rifts structure: */
+	double* pNaN=NULL;
+	const	char*	fnames[10];
+	mwSize     ndim=2;
+	mwSize		dimensions[2] = {1,1};
+	double* pair=NULL;
+
+	
+	/* input: */
+	double* tindex_in=NULL;
+	double* index_in=NULL;
+	int     nel;
+	double* x_inm=NULL; //matlab vector
+	double* x_in=NULL; //copy of matlab vector
+	int     nods;
+	double* y_inm=NULL;//matlab vector
+	double* y_in=NULL;//copy of matlab vector
+	double* tsegments_in=NULL;
+	double* segments_in=NULL;
+	double* tsegmentmarkers_in=NULL;
+	double* segmentmarkers_in=NULL;
+
+	/* state: */
+	double* state=NULL;
+
+	int     num_seg;
+
+	/*rifts: */
+	int     riftflag;
+	int     numrifts;
+
+	/* verify correct usage: */
+	if (nlhs==0 && nrhs==0) {
+		/* special case: */
+		TriMeshProcessRiftsUsage();
+		return;
+	}
+	
+	if (!(  (nlhs==6) || (nrhs==5))){
+		mexPrintf("   %s format error.\n", __FUNCT__);
+		TriMeshProcessRiftsUsage();
+		printf("   ");
+		mexErrMsgTxt(" ");
+	}
+
+	/*Fetch index_in: */
+	if(mxIsDouble(prhs[0])){
+		nel=mxGetM(prhs[0]);
+		tindex_in=mxGetPr(prhs[0]);
+		index_in=(double*)xmalloc(nel*3*sizeof(double));
+		for (i=0;i<nel;i++){
+			for (j=0;j<3;j++){
+				*(index_in+3*i+j)=*(tindex_in+nel*j+i);
+			}
+		}
+	}
+	else{
+		printf("%s%s\n",__FUNCT__," error message: first argument should be the element list!");
+		mexErrMsgTxt(" ");
+	}
+
+	/*Fetch x_in: */
+	if(mxIsDouble(prhs[1])){
+		nods=mxGetM(prhs[1]);
+		x_inm=mxGetPr(prhs[1]);
+		x_in=(double*)xmalloc(nods*sizeof(double));
+		for (i=0;i<nods;i++){
+			x_in[i]=x_inm[i];
+		}
+	}
+	else{
+		printf("%s%s\n",__FUNCT__," error message: second argument should be the x corrdinate list!");
+		mexErrMsgTxt(" ");
+	}
+
+	/*Fetch y_in: */
+	if(mxIsDouble(prhs[2])){
+		y_inm=mxGetPr(prhs[2]);
+		y_in=(double*)xmalloc(nods*sizeof(double));
+		for (i=0;i<nods;i++){
+			y_in[i]=y_inm[i];
+		}
+	}
+	else{
+		printf("%s%s\n",__FUNCT__," error message: third argument should be the y corrdinate list!");
+		mexErrMsgTxt(" ");
+	}	
+
+	/*Fetch segments_in: */
+	if(mxIsDouble(prhs[3])){
+		num_seg=mxGetM(prhs[3]);
+		tsegments_in=mxGetPr(prhs[3]);
+		segments_in=(double*)xmalloc(num_seg*3*sizeof(double));
+		for (i=0;i<num_seg;i++){
+			for (j=0;j<3;j++){
+				*(segments_in+3*i+j)=*(tsegments_in+num_seg*j+i);
+			}
+		}
+	}
+	else{
+		printf("%s%s\n",__FUNCT__," error message: fourth argument should be the segments list!");
+		mexErrMsgTxt(" ");
+	}
+
+	/*Fetch segment markers: */
+	if(mxIsDouble(prhs[4])){
+		tsegmentmarkers_in=mxGetPr(prhs[4]);
+		segmentmarkers_in=(double*)xmalloc(num_seg*sizeof(double));
+		for (i=0;i<num_seg;i++){
+			segmentmarkers_in[i]=tsegmentmarkers_in[i];
+		}
+	}
+	else{
+		printf("%s%s\n",__FUNCT__," error message: fourth argument should be the segmentmarkers list!");
+		mexErrMsgTxt(" ");
+	}
+
+	/*
+	printf("Index: \n");
+	for (i=0;i<nel;i++){
+		for(j=0;j<3;j++){
+			printf("%lf ",*(index_in+3*i+j));
+		}
+		printf("\n");
+	}
+	printf("x,y: \n");
+	for (i=0;i<nods;i++){
+		printf("%16.16lf %16.16lf\n",x_in[i],y_in[i]);
+	}
+	printf("segments:\n");
+	for (i=0;i<num_seg;i++){
+		for(j=0;j<3;j++){
+			printf("%lf ",*(segments_in+3*i+j));
+		}
+		printf("%lf ",segmentmarkers_in[i]);
+		printf("\n");
+	}
+	*/
+
+	/*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_in,&nel,&x_in,&y_in,&nods,segments_in,segmentmarkers_in,num_seg);
+
+	/*Figure out if we have rifts, and how many: */
+	IsRiftPresent(&riftflag,&numrifts,segmentmarkers_in,num_seg);
+	
+	if(riftflag){	
+		SplitMeshForRifts(&nel,&index_in,&nods,&x_in,&y_in,&num_seg,&segments_in,&segmentmarkers_in);
+	}
+
+	/*Order segments so that their normals point outside the domain: */
+	OrderSegments(&segments_in,num_seg, index_in,nel);
+
+	
+	if(riftflag){
+		
+		/*We do not want to output segments mixed with rift segments: wring out the rifts from the segments, using the 
+		 *segmentmarkerlist:*/
+		SplitRiftSegments(&segments_in,&segmentmarkers_in,&num_seg,&out_numrifts,&out_riftsnumsegments,&out_riftssegments,numrifts);
+
+		/*Using rift segments, associate rift faces in pairs, each pair face representing opposite flanks of the rifts facing one another directly: */
+		PairRiftElements(&out_riftsnumpairs,&out_riftspairs,out_numrifts,out_riftsnumsegments,out_riftssegments,x_in,y_in);
+		
+		/*Order rifts so that they start from one tip, go to the other tip, and back: */
+		OrderRifts(&out_riftstips, out_riftssegments,out_riftspairs,numrifts,out_riftsnumsegments,x_in,y_in);
+
+		/*Create penalty pairs, used by Imp: */
+		PenaltyPairs(&out_riftspenaltypairs,&out_riftsnumpenaltypairs,numrifts,out_riftssegments,out_riftsnumsegments,out_riftspairs,out_riftstips,x_in,y_in);
+	}
+
+
+	/*Output : */
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,3);
+	mxSetN(pmxa_array,nel);
+	mxSetPr(pmxa_array,index_in);
+	mexCallMATLAB( 1, &plhs[0], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,1);
+	mxSetN(pmxa_array,nods);
+	mxSetPr(pmxa_array,x_in);
+	mexCallMATLAB( 1, &plhs[1], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,1);
+	mxSetN(pmxa_array,nods);
+	mxSetPr(pmxa_array,y_in);
+	mexCallMATLAB( 1, &plhs[2], 1, &pmxa_array, "transpose");
+
+	
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,3);
+	mxSetN(pmxa_array,num_seg);
+	mxSetPr(pmxa_array,segments_in);
+	mexCallMATLAB( 1, &plhs[3], 1, &pmxa_array, "transpose");
+	
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,1);
+	mxSetN(pmxa_array,num_seg);
+	mxSetPr(pmxa_array,segmentmarkers_in);
+	mexCallMATLAB( 1, &plhs[4], 1, &pmxa_array, "transpose");
+
+	if(riftflag){
+		/*Create a structure rifts where if i is a rift number, we have the following fields rifts(i).segments and rifts(i).numsegs: */
+
+		fnames[0] = "numsegs";
+		fnames[1] = "segments";
+		fnames[2] = "pairs";
+		fnames[3] = "tips";
+		fnames[4] = "penaltypairs";
+		fnames[5] = "fill";
+		fnames[6] = "friction";
+		fnames[7] = "fraction";
+		fnames[8] = "fractionincrement";
+		fnames[9] = "state";
+
+		dimensions[0]=out_numrifts;
+
+		pmxa_array=mxCreateStructArray( ndim,dimensions,10,fnames);
+		
+		for (i=0;i<out_numrifts;i++){
+			/*Segments: */
+			pmxa_array2= mxCreateDoubleMatrix(0,0,mxREAL);
+			mxSetM(pmxa_array2,3);
+			mxSetN(pmxa_array2,out_riftsnumsegments[i]);
+			mxSetPr(pmxa_array2,out_riftssegments[i]);
+			mexCallMATLAB( 1, &pmxa_array3, 1, &pmxa_array2, "transpose");
+			
+			mxSetField(pmxa_array,i,"segments",pmxa_array3);
+			mxSetField(pmxa_array,i,"numsegs",mxCreateDoubleScalar((double)out_riftsnumsegments[i]));
+
+			/*Element pairs: */
+			pmxa_array2= mxCreateDoubleMatrix(0,0,mxREAL);
+			mxSetM(pmxa_array2,2);
+			mxSetN(pmxa_array2,out_riftsnumpairs[i]);
+			mxSetPr(pmxa_array2,out_riftspairs[i]);
+			mexCallMATLAB( 1, &pmxa_array3, 1, &pmxa_array2, "transpose");
+			
+			mxSetField(pmxa_array,i,"pairs",pmxa_array3);
+
+			/*Tips: */
+			pmxa_array2= mxCreateDoubleMatrix(0,0,mxREAL);
+			mxSetM(pmxa_array2,1);
+			pair=(double*)xmalloc(2*sizeof(double));
+			pair[0]=*(out_riftstips+2*i+0);
+			pair[1]=*(out_riftstips+2*i+1);
+			mxSetN(pmxa_array2,2);
+			mxSetPr(pmxa_array2,pair);
+			mxSetField(pmxa_array,i,"tips",pmxa_array2);
+
+			/*Penalty pairs: */
+			pmxa_array2= mxCreateDoubleMatrix(0,0,mxREAL);
+			mxSetM(pmxa_array2,7);
+			mxSetN(pmxa_array2,out_riftsnumpenaltypairs[i]);
+			mxSetPr(pmxa_array2,out_riftspenaltypairs[i]);
+			mexCallMATLAB( 1, &pmxa_array3, 1, &pmxa_array2, "transpose");
+			
+			mxSetField(pmxa_array,i,"penaltypairs",pmxa_array3);
+
+			/*Friction fraction, fractionincrement  and fill: */
+			mxSetField(pmxa_array,i,"friction",mxCreateDoubleScalar(0));
+			mxSetField(pmxa_array,i,"fill",mxCreateDoubleScalar(IceEnum)); //default is ice
+			mxSetField(pmxa_array,i,"fraction",mxCreateDoubleScalar(0)); //default is ice
+			mxSetField(pmxa_array,i,"fractionincrement",mxCreateDoubleScalar(0.1)); 
+
+			/*State: */
+			state=(double*)xmalloc(out_riftsnumpenaltypairs[i]*sizeof(double));
+			for(j=0;j<out_riftsnumpenaltypairs[i];j++)state[j]=FreeEnum;
+			pmxa_array2= mxCreateDoubleMatrix(0,0,mxREAL);
+			mxSetM(pmxa_array2,1);
+			mxSetN(pmxa_array2,out_riftsnumpenaltypairs[i]);
+			mxSetPr(pmxa_array2,state);
+			mexCallMATLAB( 1, &pmxa_array3, 1, &pmxa_array2, "transpose");
+			
+			mxSetField(pmxa_array,i,"state",pmxa_array3);
+		}
+	}
+	else{
+		/*output NaN :*/
+		pNaN=(double*)xmalloc(sizeof(double));
+		*pNaN=NAN;
+		pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+		mxSetM(pmxa_array,1);
+		mxSetN(pmxa_array,1);
+		mxSetPr(pmxa_array,pNaN);
+		
+	}
+	plhs[5]=pmxa_array;
+
+	return;
+}
+
+
+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");
+}
Index: /issm/trunk-jpl-damage/src/mex/TriMeshProcessRifts/TriMeshProcessRifts.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/TriMeshProcessRifts/TriMeshProcessRifts.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/TriMeshProcessRifts/TriMeshProcessRifts.h	(revision 11330)
@@ -0,0 +1,21 @@
+/*!\file:  TriMeshProcessRifts.h
+ * \brief header prototype
+ */ 
+
+#ifndef _TRIMESH_PROCESSRIFTS_H_
+#define _TRIMESH_PROCESSRIFTS_H_
+
+#include "mex.h"
+#include "triangle.h"
+#include "string.h"
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+void TriMeshProcessRiftsUsage(void);
+#undef __FUNCT__ 
+#define __FUNCT__ "TriMeshProcessRifts"
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/TriMeshRefine/TriMeshRefine.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/TriMeshRefine/TriMeshRefine.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/TriMeshRefine/TriMeshRefine.cpp	(revision 11330)
@@ -0,0 +1,327 @@
+/*!\file:  TriMeshRefine
+ * \brief refine a mesh output by TriMesh:
+ */ 
+
+#include "./TriMeshRefine.h"
+
+
+void mexFunction(	int nlhs, mxArray* plhs[],
+					int nrhs, const mxArray* prhs[] )
+{
+
+
+	/*Matlab arrays: */
+	mxArray* pmxa_array=NULL;
+	mxArray* pmxa_array2=NULL;
+	mxArray* pmxa_array3=NULL;
+	int i,j,k,counter;
+	
+	/* returned quantities: */
+
+	double* index=NULL;
+	double* x=NULL;
+	double* y=NULL;
+	double* segments=NULL;
+	double* segmentmarkerlist=NULL;
+	
+	/* input: */
+	double* area=NULL;
+	double* tindex_in=NULL;
+	double*    index_in=NULL;
+	int     nel;
+	double* x_inm=NULL; //matlab vector
+	double* x_in=NULL; //copy of matlab vector
+	int     nods;
+	double* y_inm=NULL;//matlab vector
+	double* y_in=NULL;//copy of matlab vector
+	double* tsegments_in=NULL;
+	double* segments_in=NULL;
+	double* tsegmentmarkers_in=NULL;
+	double* segmentmarkers_in=NULL;
+
+	int     num_seg;
+	char*   order=NULL;
+
+	/* Triangle structures: */
+	struct triangulateio in,out;
+	char   options[256];
+
+	/* verify correct usage: */
+	if (nlhs==0 && nrhs==0) {
+		/* special case: */
+		TriMeshRefineUsage();
+		return;
+	}
+
+	if (!(  (nlhs==5) || (nrhs==6) || (nrhs==7)  )){
+		mexPrintf("   %s format error.\n", __FUNCT__);
+		TriMeshRefineUsage();
+		printf("   ");
+		mexErrMsgTxt(" ");
+	}
+
+	/*Fetch index_in: */
+	if(mxIsDouble(prhs[0])){
+		nel=mxGetM(prhs[0]);
+		tindex_in=mxGetPr(prhs[0]);
+		index_in=(double*)xmalloc(nel*3*sizeof(double));
+		for (i=0;i<nel;i++){
+			for (j=0;j<3;j++){
+				*(index_in+3*i+j)=*(tindex_in+nel*j+i)-1;
+			}
+		}
+	}
+	else{
+		printf("%s%s\n",__FUNCT__," error message: first argument should be the element list!");
+		mexErrMsgTxt(" ");
+	}
+
+	/*Fetch x_in: */
+	if(mxIsDouble(prhs[1])){
+		nods=mxGetM(prhs[1]);
+		x_inm=mxGetPr(prhs[1]);
+		x_in=(double*)xmalloc(nods*sizeof(double));
+		for (i=0;i<nods;i++){
+			x_in[i]=x_inm[i];
+		}
+	}
+	else{
+		printf("%s%s\n",__FUNCT__," error message: second argument should be the x corrdinate list!");
+		mexErrMsgTxt(" ");
+	}
+
+	/*Fetch y_in: */
+	if(mxIsDouble(prhs[2])){
+		y_inm=mxGetPr(prhs[2]);
+		y_in=(double*)xmalloc(nods*sizeof(double));
+		for (i=0;i<nods;i++){
+			y_in[i]=y_inm[i];
+		}
+	}
+	else{
+		printf("%s%s\n",__FUNCT__," error message: third argument should be the y corrdinate list!");
+		mexErrMsgTxt(" ");
+	}	
+
+	/*Fetch segments_in: */
+	if(mxIsDouble(prhs[3])){
+		num_seg=mxGetM(prhs[3]);
+		tsegments_in=mxGetPr(prhs[3]);
+		segments_in=(double*)xmalloc(num_seg*3*sizeof(double));
+		for (i=0;i<num_seg;i++){
+			for (j=0;j<3;j++){
+				*(segments_in+3*i+j)=*(tsegments_in+num_seg*j+i)-1;
+			}
+		}
+	}
+	else{
+		printf("%s%s\n",__FUNCT__," error message: fourth argument should be the segments list!");
+		mexErrMsgTxt(" ");
+	}
+
+	/*Fetch segment markers: */
+	if(mxIsDouble(prhs[4])){
+		tsegmentmarkers_in=mxGetPr(prhs[4]);
+		segmentmarkers_in=(double*)xmalloc(num_seg*sizeof(double));
+		for (i=0;i<num_seg;i++){
+			segmentmarkers_in[i]=tsegmentmarkers_in[i];
+		}
+	}
+	else{
+		printf("%s%s\n",__FUNCT__," error message: fourth argument should be the segmentmarkers list!");
+		mexErrMsgTxt(" ");
+	}
+	
+	/*Fetch area: */
+	if(mxIsDouble(prhs[5])){
+		if (mxGetM(prhs[5])!=nel){
+			printf("%s%s\n",__FUNCT__," error message: area vector should be of the same size as index\n");
+			mexErrMsgTxt(" ");
+		}
+		area=mxGetPr(prhs[5]);
+	}
+	else{
+		printf("%s%s\n",__FUNCT__," error message: fifth argument should be the area list!");
+		mexErrMsgTxt(" ");
+	}
+
+	/*Optionaly, recover desired order: */
+	if(nrhs==7){
+		if (!mxIsChar(prhs[6])){
+			mexPrintf("%s%s\n",__FUNCT__," error message; sixth argument should be a string ('yes' or 'no')!");
+			mexErrMsgTxt(" ");
+		}
+		order = (char *) xmalloc((mxGetN(prhs[6])+1)*sizeof(char));
+		mxGetString(prhs[6],order,mxGetN(prhs[6])+1);
+	}
+
+	/*printf("Index: \n");
+	for (i=0;i<nel;i++){
+		for(j=0;j<3;j++){
+			printf("%lf ",*(index_in+3*i+j));
+		}
+		printf("\n");
+	}*/
+	/*printf("x,y: \n");
+	for (i=0;i<nods;i++){
+		printf("%16.16lf %16.16lf\n",x_in[i],y_in[i]);
+	}*/
+	/*printf("segments:\n");
+	for (i=0;i<num_seg;i++){
+		for(j=0;j<3;j++){
+			printf("%lf ",*(segments_in+3*i+j));
+		}
+		printf("%lf ",segmentmarkers_in[i]);
+		printf("\n");
+	}*/
+	/*printf("area: \n");
+	for (i=0;i<nel;i++){
+		printf("%16.16lf \n",area[i]);
+	}*/
+	//if(nrhs==6)printf("Order: %s\n",order);
+
+	/*Create initial triangulation to call triangulate():*/
+	in.numberoftriangles=nel;
+	in.numberoftriangleattributes=1;
+	in.numberofcorners=3;
+	
+	in.trianglelist = (int *) xmalloc(3*in.numberoftriangles * sizeof(int));
+	for(i=0;i<in.numberoftriangles;i++){
+		for(j=0;j<3;j++){
+			in.trianglelist[3*i+j]=(int)index_in[3*i+j];
+		}
+	}
+	in.triangleattributelist = (REAL *) xmalloc(in.numberoftriangles * in.numberoftriangleattributes * sizeof(REAL));
+	for(i=0;i<in.numberoftriangles;i++){
+		in.triangleattributelist[i]=0.0;
+	}
+	in.trianglearealist = (REAL *) xmalloc(in.numberoftriangles * sizeof(REAL));
+	for(i=0;i<in.numberoftriangles;i++){
+		in.trianglearealist[i]=area[i];
+	}
+
+	in.numberofpoints=nods;
+	in.numberofpointattributes=1;
+	in.pointlist = (REAL *) xmalloc(in.numberofpoints * 2 * sizeof(REAL));
+	for (i=0;i<nods;i++){
+		in.pointlist[2*i+0]=x_in[i];
+		in.pointlist[2*i+1]=y_in[i];
+	}
+	in.pointattributelist = (REAL *) xmalloc(in.numberofpoints * in.numberofpointattributes * sizeof(REAL));
+	for (i=0;i<nods;i++){
+		in.pointattributelist[i] = 0.0;
+	}	
+
+	in.numberofsegments = num_seg;
+	in.segmentlist = (int *) xmalloc(in.numberofsegments * 2 * sizeof(REAL));
+	in.segmentmarkerlist = (int *) mxCalloc(in.numberofsegments,sizeof(int));
+	for (i=0;i<num_seg;i++){
+		in.segmentlist[2*i+0]=(int)segments_in[3*i+0];
+		in.segmentlist[2*i+1]=(int)segments_in[3*i+1];
+		in.segmentmarkerlist[i]=(int)segmentmarkers_in[i];
+	}
+	
+	in.numberofholes = 0;
+
+	/* 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","QzDq30iarp",area); //replace V by Q to quiet down the logging
+
+
+	triangulate(options, &in, &out, NULL);
+	
+	/*Allocate index, x and y: */
+	index=(double*)xmalloc(3*out.numberoftriangles*sizeof(double));
+	x=(double*)xmalloc(out.numberofpoints*sizeof(double));
+	y=(double*)xmalloc(out.numberofpoints*sizeof(double));
+	segments=(double*)xmalloc(3*out.numberofsegments*sizeof(double));
+	segmentmarkerlist=(double*)xmalloc(out.numberofsegments*sizeof(double));
+
+	for (i = 0; i < out.numberoftriangles; i++) {
+		for (j = 0; j < out.numberofcorners; j++) {
+			*(index+3*i+j)=(double)out.trianglelist[i * out.numberofcorners + j]+1;
+		}
+	}
+	for (i = 0; i < out.numberofpoints; i++) {
+		x[i]=out.pointlist[i * 2 + 0];
+		y[i]=out.pointlist[i * 2 + 1];
+	}
+	
+	for (i = 0; i < out.numberofsegments; i++) {
+		segments[3*i+0]=(double)out.segmentlist[i*2+0]+1;
+		segments[3*i+1]=(double)out.segmentlist[i*2+1]+1;
+		segmentmarkerlist[i]=(double)out.segmentmarkerlist[i];
+	}
+
+	/*Associate elements with segments: */
+	AssociateSegmentToElement(&segments,out.numberofsegments,index,out.numberoftriangles);
+
+	/*Order segments so that their normals point outside the domain: */
+	if(!strcmp(order,"yes")){
+		OrderSegments(&segments,out.numberofsegments, index,out.numberoftriangles);
+	}
+	
+	/*Output : */
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,3);
+	mxSetN(pmxa_array,out.numberoftriangles);
+	mxSetPr(pmxa_array,index);
+	mexCallMATLAB( 1, &plhs[0], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,1);
+	mxSetN(pmxa_array,out.numberofpoints);
+	mxSetPr(pmxa_array,x);
+	mexCallMATLAB( 1, &plhs[1], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,1);
+	mxSetN(pmxa_array,out.numberofpoints);
+	mxSetPr(pmxa_array,y);
+	mexCallMATLAB( 1, &plhs[2], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,3);
+	mxSetN(pmxa_array,out.numberofsegments);
+	mxSetPr(pmxa_array,segments);
+	mexCallMATLAB( 1, &plhs[3], 1, &pmxa_array, "transpose");
+
+	pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
+	mxSetM(pmxa_array,1);
+	mxSetN(pmxa_array,out.numberofsegments);
+	mxSetPr(pmxa_array,segmentmarkerlist);
+	mexCallMATLAB( 1, &plhs[4], 1, &pmxa_array, "transpose");
+
+	return;
+}
+
+
+void TriMeshRefineUsage(void)
+{
+	printf("\n");
+	printf("   usage: [index2,x2,y2,segments2,segmentmarkers2]=TriMeshRefine(index1,x1,y1,segments1,segmentmarkers1,area,order) \n");
+	printf("      where: (index1,x1,y1,segments1,segmentmarkers1) is an initial triangulation (segment1 does not need to be ordered).\n");
+	printf("      area is a vector of element areas determining which elements will be refined.\n");
+	printf("      order is an optional argument that determines whether segments are output in the \n");
+	printf("      order they are made by Triangle (ie none), or ordered counter clockwise around the domain outline.\n");
+	printf("      (index2,x2,y2,segments2,segmentmarkers2) is the resulting refined triangulation.\n");
+	printf("   note: order is an optional arguments\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/TriMeshRefine/TriMeshRefine.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/TriMeshRefine/TriMeshRefine.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/TriMeshRefine/TriMeshRefine.h	(revision 11330)
@@ -0,0 +1,20 @@
+/*!\file:  TriMeshRefine.h
+ * \brief header prototype
+ */ 
+
+#ifndef _TRIMESH_REFINE_H_
+#define _TRIMESH_REFINE_H_
+
+#include "mex.h"
+#include "triangle.h"
+#include "string.h"
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+void TriMeshRefineUsage(void);
+#undef __FUNCT__ 
+#define __FUNCT__ "TriMeshRefine"
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/TriaSearch/TriaSearch.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/TriaSearch/TriaSearch.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/TriaSearch/TriaSearch.cpp	(revision 11330)
@@ -0,0 +1,66 @@
+/*\file TriaSearch.c
+ *\brief: TriaSearch module. See TriaSearchx for more details.
+ */
+#include "./TriaSearch.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	int i;
+
+	/*input: */
+	double* 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: */
+	FetchMatlabData(&index,&nel,&dummy,INDEXHANDLE);
+	FetchMatlabData(&x,&nods,XHANDLE);
+	FetchMatlabData(&y,&nods,YHANDLE);
+	FetchMatlabData(&x0,&numberofnodes,X0HANDLE);
+	FetchMatlabData(&y0,&numberofnodes,Y0HANDLE);
+
+	/* Echo: {{{1*/
+	//printf("(x0,y0)=(%g,%g)\n",x0,y0);
+	/*}}}*/
+
+	/* Run core computations: */
+	TriaSearchx(&tria,index,nel,x,y,nods,x0,y0,numberofnodes);
+
+	/* c to matlab: */
+	for(i=0;i<numberofnodes;i++)tria[i]++;
+
+	/*Write data: */
+	WriteMatlabData(TRIA,tria,numberofnodes);
+
+	/*end module: */
+	MODULEEND();
+}
+
+void TriaSearchUsage(void)
+{
+	_printf_(true,"TriaSearch- find triangle holding a point (x0,y0) in a mesh\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"         tria=TriaSearch(index,x,y,x0,y0);\n");
+	_printf_(true,"      index,x,y: mesh triangulatrion\n");
+	_printf_(true,"      x0,y0: coordinates of the point for which we are trying to find a triangle\n");
+	_printf_(true,"      x0,y0 can be an array of points\n");
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/TriaSearch/TriaSearch.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/TriaSearch/TriaSearch.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/TriaSearch/TriaSearch.h	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file TriaSearch.h
+ */
+
+#ifndef _TRIASEARCH_H
+#define _TRIASEARCH_H
+
+/* local prototypes: */
+void TriaSearchUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "TriaSearch"
+
+
+/* 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]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+
+#undef NRHS
+#define NRHS  5
+
+#endif
Index: /issm/trunk-jpl-damage/src/mex/UpdateConstraints/UpdateConstraints.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/UpdateConstraints/UpdateConstraints.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/UpdateConstraints/UpdateConstraints.cpp	(revision 11330)
@@ -0,0 +1,46 @@
+/*\file UpdateConstraints.c
+ *\brief: build degrees of freedom for every node.
+ */
+
+#include "./UpdateConstraints.h"
+
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Nodes* nodes=NULL;
+	Parameters* parameters=NULL;
+	Constraints* constraints=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&UpdateConstraintsUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&nodes,NODESIN);
+	FetchMatlabData((DataSet**)&constraints,CONSTRAINTS);
+	FetchMatlabData(&parameters,PARAMETERS);
+	
+	/*!Generate internal degree of freedom numbers: */
+	UpdateConstraintsx(nodes,constraints,parameters);
+
+	/*write output datasets: */
+	WriteMatlabData(NODES,nodes);
+
+	/*Free ressources: */
+	delete nodes;
+	delete constraints;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void UpdateConstraintsUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [m.node]=%s(m.nodes,m.constraints,m.parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/UpdateConstraints/UpdateConstraints.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/UpdateConstraints/UpdateConstraints.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/UpdateConstraints/UpdateConstraints.h	(revision 11330)
@@ -0,0 +1,36 @@
+
+/*
+	UpdateConstraints.h
+*/
+
+
+#ifndef _UPDATECONSTRAINTS_H
+#define _UPDATECONSTRAINTS_H
+
+/* local prototypes: */
+void UpdateConstraintsUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "UpdateConstraints"
+
+/* serial input macros: */
+#define NODESIN (mxArray*)prhs[0]
+#define CONSTRAINTS (mxArray*)prhs[1]
+#define PARAMETERS (mxArray*)prhs[2]
+
+/* serial output macros: */
+#define NODES (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  3
+
+
+#endif  /* _UPDATECONSTRAINTS_H */
+
Index: /issm/trunk-jpl-damage/src/mex/UpdateDynamicConstraints/UpdateDynamicConstraints.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/UpdateDynamicConstraints/UpdateDynamicConstraints.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/UpdateDynamicConstraints/UpdateDynamicConstraints.cpp	(revision 11330)
@@ -0,0 +1,48 @@
+/*\file UpdateDynamicConstraints.c
+ *\brief: update single point constraints inside nodes out of constrain vector ys
+ */
+
+#include "./UpdateDynamicConstraints.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Constraints *constraints = NULL;
+	Nodes       *nodes       = NULL;
+	Parameters  *parameters  = NULL;
+	Vec          yg          = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&UpdateDynamicConstraintsUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&constraints,CONSTRAINTSIN);
+	FetchMatlabData((DataSet**)&nodes,NODESIN);
+	FetchMatlabData((Parameters**)&parameters,PARAMETERS);
+	FetchMatlabData(&yg,YG);
+	
+	/*!Generate internal degree of freedom numbers: */
+	UpdateDynamicConstraintsx(constraints,nodes,parameters,yg);
+
+	/*write output datasets: */
+	WriteMatlabData(CONSTRAINTSOUT,constraints);
+
+	/*Free ressources: */
+	VecFree(&yg);
+	delete constraints;
+	delete nodes;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void UpdateDynamicConstraintsUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: m.constraints=%s(m.constraints,m.nodes,m.parameters,ys);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/UpdateDynamicConstraints/UpdateDynamicConstraints.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/UpdateDynamicConstraints/UpdateDynamicConstraints.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/UpdateDynamicConstraints/UpdateDynamicConstraints.h	(revision 11330)
@@ -0,0 +1,33 @@
+/*
+	UpdateDynamicConstraints.h
+*/
+
+#ifndef _UPDATEDYNAMICCONSTRAINTS_H
+#define _UPDATEDYNAMICCONSTRAINTS_H
+
+/* local prototypes: */
+void UpdateDynamicConstraintsUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "UpdateDynamicConstraints"
+
+/* serial input macros: */
+#define CONSTRAINTSIN (mxArray*)prhs[0]
+#define NODESIN (mxArray*)prhs[1]
+#define PARAMETERS (mxArray*)prhs[2]
+#define YG (mxArray*)prhs[3]
+
+/* serial output macros: */
+#define CONSTRAINTSOUT (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  4
+
+#endif 
Index: /issm/trunk-jpl-damage/src/mex/UpdateVertexPositions/UpdateVertexPositions.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/UpdateVertexPositions/UpdateVertexPositions.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/UpdateVertexPositions/UpdateVertexPositions.cpp	(revision 11330)
@@ -0,0 +1,64 @@
+/*\file UpdateVertexPositions.c
+*\brief: update elements properties using an input  vector
+*/
+
+#include "./UpdateVertexPositions.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Elements*   elements          = NULL;
+	Nodes      *nodes             = NULL;
+	Vertices    *vertices          = NULL;
+	Loads     *loads             = NULL;
+	Materials   *materials         = NULL;
+	Parameters *parameters        = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&UpdateVertexPositionsUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&elements,ELEMENTSIN);
+	FetchMatlabData((DataSet**)&nodes,NODESIN);
+	FetchMatlabData((DataSet**)&vertices,VERTICESIN);
+	FetchMatlabData((DataSet**)&loads,LOADSIN);
+	FetchMatlabData((DataSet**)&materials,MATERIALSIN);
+	FetchMatlabData(&parameters,PARAMETERSIN);
+
+	/*configure: */
+	elements->  Configure(elements,loads, nodes,vertices, materials,parameters);
+	nodes->     Configure(elements,loads, nodes,vertices, materials,parameters);
+	loads->     Configure(elements, loads, nodes,vertices, materials,parameters);
+
+	/*call "x" code layer*/
+	UpdateVertexPositionsx(elements,nodes,vertices,loads, materials,parameters);
+
+	/*write output datasets: */
+	WriteMatlabData(ELEMENTS,elements);
+	WriteMatlabData(NODES,nodes);
+	WriteMatlabData(VERTICES,vertices);
+	WriteMatlabData(LOADS,loads);
+	WriteMatlabData(MATERIALS,materials);
+	WriteMatlabData(PARAMETERS,parameters);
+
+	/*Free ressources: */
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete loads;
+	delete materials;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void UpdateVertexPositionsUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [elements,nodes,vertices,loads,materials,parameters] = %s(elements,nodes,vertices,loads,materials,parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/UpdateVertexPositions/UpdateVertexPositions.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/UpdateVertexPositions/UpdateVertexPositions.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/UpdateVertexPositions/UpdateVertexPositions.h	(revision 11330)
@@ -0,0 +1,42 @@
+/*
+	UpdateVertexPositions.h
+*/
+
+#ifndef _UPDATEVERTEXPOSITIONS_H
+#define _UPDATEVERTEXPOSITIONS_H
+
+/* local prototypes: */
+void UpdateVertexPositionsUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "UpdateVertexPositions"
+
+/* serial input macros: */
+#define ELEMENTSIN (mxArray*)prhs[0]
+#define NODESIN (mxArray*)prhs[1]
+#define VERTICESIN (mxArray*)prhs[2]
+#define LOADSIN (mxArray*)prhs[3]
+#define MATERIALSIN (mxArray*)prhs[4]
+#define PARAMETERSIN (mxArray*)prhs[5]
+
+/* serial output macros: */
+#define ELEMENTS (mxArray**)&plhs[0]
+#define NODES (mxArray**)&plhs[1]
+#define VERTICES (mxArray**)&plhs[2]
+#define LOADS (mxArray**)&plhs[3]
+#define MATERIALS (mxArray**)&plhs[4]
+#define PARAMETERS (mxArray**)&plhs[5]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  6
+#undef NRHS
+#define NRHS  6
+
+#endif  /* _UPDATEVERTEXPOSITIONS_H */
+
Index: /issm/trunk-jpl-damage/src/mex/VerticesDof/VerticesDof.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/VerticesDof/VerticesDof.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/VerticesDof/VerticesDof.cpp	(revision 11330)
@@ -0,0 +1,42 @@
+/*\file VerticesDof.c
+ *\brief: build degrees of freedom for every vertex
+ */
+
+#include "./VerticesDof.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	/*input datasets: */
+	Vertices* vertices=NULL;
+	Parameters* parameters=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&VerticesDofUsage);
+
+	/*Input datasets: */
+	FetchMatlabData((DataSet**)&vertices,VERTICESIN);
+	FetchMatlabData(&parameters,PARAMETERS);
+
+	/*!Generate internal degree of freedom numbers: */
+	VerticesDofx(vertices, parameters); 
+
+	/*write output datasets: */
+	WriteMatlabData(VERTICES,vertices);
+
+	/*Free ressources: */
+	delete vertices;
+	delete parameters;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void VerticesDofUsage(void)
+{
+	_printf_(true,"\n");
+	_printf_(true,"   usage: [vertices] = %s(vertices,parameters);\n",__FUNCT__);
+	_printf_(true,"\n");
+}
Index: /issm/trunk-jpl-damage/src/mex/VerticesDof/VerticesDof.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/VerticesDof/VerticesDof.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/VerticesDof/VerticesDof.h	(revision 11330)
@@ -0,0 +1,32 @@
+/*
+	VerticesDof.h
+*/
+
+#ifndef _VERTICESDOF_H
+#define _VERTICESDOF_H
+
+/* local prototypes: */
+void VerticesDofUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "VerticesDof"
+
+/* serial input macros: */
+#define VERTICESIN (mxArray*)prhs[0]
+#define PARAMETERS (mxArray*)prhs[1]
+
+/* serial output macros: */
+#define VERTICES (mxArray**)&plhs[0]
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+#endif  /* _VERTICESDOF_H */
+
Index: /issm/trunk-jpl-damage/src/mex/Xy2ll/Xy2ll.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Xy2ll/Xy2ll.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Xy2ll/Xy2ll.cpp	(revision 11330)
@@ -0,0 +1,121 @@
+/*\file Xy2ll.c
+ *\brief: x/y to lat/long coordinate mex module.
+ */
+#include "./Xy2ll.h"
+
+void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+
+	int i,verbose=1;
+
+	/*input: */
+	double  *x=NULL,*y=NULL;
+	int     nx,ny,ncoord;
+	int     sgn;
+
+	Options* options=NULL;
+	double   cm=0.,sp=0.;
+
+	/* output: */
+	double  *lat=NULL,*lon=NULL;
+	int     iret=0;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if (nlhs > NLHS) {
+		Xy2llUsage();
+		_error_("Xy2ll usage error");
+	}
+	if (nrhs < NRHS) {
+		Xy2llUsage();
+		_error_("Xy2ll usage error");
+	}
+
+	/*Input datasets: */
+	if (verbose) printf("Fetching inputs:\n");
+	FetchMatlabData(&x,&nx,X_IN);
+	if (verbose)
+		if   (nx == 1) printf("  x=%g\n",x[0]);
+		else           printf("  x=[%d values]\n",nx);
+//	for (i=0; i<nx; i++) printf("  x[%d]=%g\n",i,x[i]);
+	FetchMatlabData(&y,&ny,Y_IN);
+	if (verbose)
+		if   (ny == 1) printf("  y=%g\n",y[0]);
+		else           printf("  y=[%d values]\n",ny);
+//	for (i=0; i<ny; i++) printf("  y[%d]=%g\n",i,y[i]);
+	FetchMatlabData(&sgn,SGN_IN);
+	if (verbose) printf("  sgn=%d\n",sgn);
+
+	if (verbose) printf("Parsing options:\n");
+	options=new Options(NRHS,nrhs,prhs);
+	if (options->Size()) for(i=0;i<options->Size();i++) ((Option*)options->GetObjectByOffset(i))->DeepEcho();
+	/*  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=%g\n",cm);
+		options->Get(&sp,"standard_parallel");
+		if (verbose) printf("  sp=%g\n",sp);
+	}
+
+	/*some checks*/
+	if (verbose) printf("Checking inputs:\n");
+
+	if   (nx != ny) _error_("Must have same number of x[%d] and y[%d] coordinates.",nx,ny);
+	else            ncoord=nx;
+	if (sgn != +1 && sgn != -1) _error_("Hemisphere sgn=%d must be +1 (north) or -1 (south).",sgn);
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=%g must be between -180 (west) and +180 (east) degrees.",cm);
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=%g must be between 0 and 90 degrees (in specified hemisphere).",sp);
+
+	lat=(double *)xmalloc(ncoord*sizeof(double));
+	lon=(double *)xmalloc(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);
+	if (verbose) printf("  iret=%d\n",iret);
+
+	/*Write data: */
+	WriteMatlabData(LAT_OUT,lat,ncoord);
+	WriteMatlabData(LON_OUT,lon,ncoord);
+
+	/*Clean-up*/
+	delete options;
+
+	/*end module: */
+	MODULEEND();
+}
+
+void Xy2llUsage(void)
+{
+	_printf_(true,"Xy2ll - x/y to lat/long coordinate transformation module:\n");
+	_printf_(true,"\n");
+	_printf_(true,"   This module transforms x/y to lat/long coordinates.\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Usage:\n");
+	_printf_(true,"      [lat,lon]=Xy2ll(x,y,sgn,'param name',param,...);\n");
+	_printf_(true,"\n");
+	_printf_(true,"      x           x coordinates (double vector)\n");
+	_printf_(true,"      y           y coordinates (double vector)\n");
+	_printf_(true,"      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
+	_printf_(true,"\n");
+	_printf_(true,"      central_meridian     central meridian (double, optional, but must specify with sp)\n");
+	_printf_(true,"      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
+	_printf_(true,"\n");
+	_printf_(true,"      lat         latitude coordinates (double vector)\n");
+	_printf_(true,"      lon         longitude coordinates (double vector)\n");
+	_printf_(true,"\n");
+	_printf_(true,"   Examples:\n");
+	_printf_(true,"      [lat,lon]=Xy2ll(x,y, 1);\n");
+	_printf_(true,"      [lat,lon]=Xy2ll(x,y, 1,'central_meridian',45,'standard_parallel',70);\n");
+	_printf_(true,"      [lat,lon]=Xy2ll(x,y,-1,'central_meridian', 0,'standard_parallel',71);\n");
+	_printf_(true,"\n");
+}
+
Index: /issm/trunk-jpl-damage/src/mex/Xy2ll/Xy2ll.h
===================================================================
--- /issm/trunk-jpl-damage/src/mex/Xy2ll/Xy2ll.h	(revision 11330)
+++ /issm/trunk-jpl-damage/src/mex/Xy2ll/Xy2ll.h	(revision 11330)
@@ -0,0 +1,35 @@
+/*!\file Xy2ll.h
+ * \brief: prototype for x/y to lat/long coordinate mex module.
+ */
+
+#ifndef _XY2LL_H
+#define _XY2LL_H
+
+/* local prototypes: */
+void Xy2llUsage(void);
+
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Xy2ll"
+
+
+/* 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]
+
+/* serial arg counts: */
+#undef NRHS
+#define NRHS  3
+#undef NLHS
+#define NLHS  2
+
+#endif
+
Index: /issm/trunk-jpl-damage/src/perl/DiagnosticAlter.pl
===================================================================
--- /issm/trunk-jpl-damage/src/perl/DiagnosticAlter.pl	(revision 11330)
+++ /issm/trunk-jpl-damage/src/perl/DiagnosticAlter.pl	(revision 11330)
@@ -0,0 +1,18 @@
+#!/usr/bin/perl
+# alter file perl script
+
+open(INFILE,  "icediagnostic_core_nonlinear.m");
+open(OUTFILE, ">icediagnostic_core_nonlinear.alt.m");
+
+
+while (<INFILE>) {
+	if(/\[K_gg,p_g\]=SystemMatrices\(elements,grids,loads,materials,kflag, pflag, sparsity,inputs,analysis_type\);/){
+		print OUTFILE "    [K_gg,p_g]=SystemMatrices(elements,grids,loads,materials,kflag, pflag, sparsity,inputs,analysis_type);\n    save systemmatrices_ice K_gg p_g; error\('debug'\);\n"
+	}
+	else{
+		print OUTFILE "$_";
+	}
+}
+
+close INFILE;
+close OUTFILE;
Index: /issm/trunk-jpl-damage/src/perl/m2cpp.pl
===================================================================
--- /issm/trunk-jpl-damage/src/perl/m2cpp.pl	(revision 11330)
+++ /issm/trunk-jpl-damage/src/perl/m2cpp.pl	(revision 11330)
@@ -0,0 +1,211 @@
+#!/usr/bin/perl --
+if ($#ARGV != 0){
+  die "Argument must contain filename $#ARGV"
+}
+else{
+  $fname=$ARGV[0];
+}
+
+# If we have a .m file inside a (@)-folder with the same name :
+# we will read each file of this folder
+if ($fname =~ /^(.*)\@([\d\w-_]*)[\/\\](\2)\.m/){
+  $name = $2;
+  $nameExt = $name.".m";
+  $dir = $1."@".$name."/\*.m";
+  @fic = glob($dir);
+  $i = 0;
+  @listeFic[0] = $fname;
+  foreach $my_test (@fic){
+    if (!($my_test =~ $nameExt)){
+      $i++;
+      @listeFic[$i] = $my_test;
+    }
+  }
+}
+# otherwise @-folder, but .m with a different name : ignore it
+elsif ($fname =~ /^(.*)\@([\d\w-_]*)[\/\\](.*)\.m/){
+}
+# otherwise
+else{
+  @listeFic[0] = $fname;
+}
+foreach $my_fic (@listeFic){
+
+  open(my $in, $my_fic);
+
+  $declTypeDef="";
+  $inClass = 0;
+  $inAbstractMethodBlock = 0;
+  $listeProperties = 0;
+  $listeEnumeration = 0;
+
+  $methodAttribute = "";
+
+  while (<$in>){
+	  #if (/(^\s*)(%)(.*)/){
+	  #  $output=$output."$1/// \@brief $3";
+	  #}
+    if (/(^\s*)(%>)(.*)/){
+      $output=$output."$1///$3";
+    }
+    if (($listeProperties == 1) && (/(^\s*\bend\b\s*)/)){
+      $listeProperties = 0;
+    }
+    if (($inAbstractMethodBlock == 1) && (/(^\s*\bend\b\s*)/)){
+      $inAbstractMethodBlock = 0;
+    }
+    if (($listeProperties == 1) && (/^\s*([\w\d]*)\s*(=\s*[\w\d{}'',\s\[\]\.]*)?.*(%>.*)?/)){
+      $propertyName = $1;
+      $propertyValue = $2;
+      $propertyComment = $3;
+      if (!($propertyName =~ /^$/)){
+        if ($typeProperties =~ /Constant/){
+          $properties = $propertyName."$propertyValue;$propertyComment";
+        }
+        else{
+          $properties = $propertyName.";$propertyComment";
+        }
+
+        $properties =~ s/%>/\/\/\//g;
+        $properties =~ s/%/\/\//g;
+        $output=$output.$typeProperties."Property ".$properties;
+      }
+    }
+    if (($listeEnumeration == 1) && (/(^\s*\bend\b\s*)/)){
+      $listeEnumeration = 0;
+      $output=$output."};";
+    }
+    if (($listeEvents == 1) && (/(^\s*\bend\b\s*)/)){
+      $listeEvents = 0;
+      $output=$output."};";
+    }
+    if (($listeEvents == 1) && (/^\s*([\w\d]*)\s*/)){
+      $name_event = $1;
+      if (!($name_event =~ /^$/)){
+        $event = $name_event.",";
+        $event =~ s/%>/\/\/\//g;
+        $event =~ s/%/\/\//g;
+        $output=$output.$event;
+      }
+    }
+    if (($listeEnumeration == 1) && (/^\s*([\w\d]*)\s*(\(.*\))?(%>.*)?/)){
+      $name_enum = $1;
+      $val_enum = $2;
+      if (!($name_enum =~ /^$/)){
+        if (!($val_enum =~ /^$/)){
+          $enum = "$name_enum=$val_enum,";
+          $enum =~ s/%>/\/\/\//g;
+          $enum =~ s/%/\/\//g;
+          $output=$output.$enum;
+        }
+        else{
+          $enum = "$name_enum,";
+          $enum =~ s/%>/\/\/\//g;
+          $enum =~ s/%/\/\//g;
+          $output=$output.$enum;
+        }
+      }
+    }
+    if (/(^\s*function)\s*([\] \w\d,_\[]+=)?\s*([.\w\d_-]*)\s*\(?([\w\d\s,~]*)\)?(%?.*)/){
+      $functionKeyWord = $1;
+      $functionName = $3;
+      $arguments = $4;
+      if ($inClass == 0){
+        $output = $declTypeDef.$output;
+        $declTypeDef = "";
+      }
+      $arguments =~ s/,/,in /g;
+      $arguments =~ s/~/ignoredArg/g;
+      $arguments = "in $arguments";
+      if ($arguments =~ /^in $/){
+        $arguments = "";
+      }
+      $ligne = "$methodAttribute $functionKeyWord $functionName($arguments);"; 
+      $output=$output.$ligne;
+    }
+    # Signature of functions in abstract methods
+    elsif ((/^\s*([\] \w\d,_\[]+=)?\s*([.\w\d_-]+)\s*\(?([\w\d\s,~]*)\)?(%?.*)/) & ($inAbstractMethodBlock == 1) ){
+      $functionName = $2;
+      $arguments = $3;
+      $arguments =~ s/,/,in /g;
+      $arguments =~ s/~/ignoredArg/g;
+      $arguments = "in $arguments";
+      if ($arguments =~ /^in $/){
+        $arguments = "";
+      }
+      $ligne = "$methodAttribute $functionKeyWord $functionName($arguments);"; 
+      $output=$output.$ligne;
+    }
+    # inheritance for classes
+    if (/(^\s*classdef)\s*(\s*\([\{\}\?\w,=\s]+\s*\))?\s*([\w\d_]+)\s*<?\s*([\s\w\d._&]+)?(.*)/){
+      $className = $3;
+      $classInheritance = $4;
+      $classAttributes = $2;
+      if (!($classInheritance =~ /^$/)){
+        $classInheritance =~ s/&/,public /g;
+        $classDef = "class ".$className.":public $classInheritance";
+      }
+      else{
+        $classDef = "class ".$className;
+      }
+      $output=$output.$classDef;
+      $output=$output."{";
+      $output=$output.$declTypeDef;
+      $output=$output."public:\n";
+      $inClass = 1;
+    }
+    if (/(^\s*properties)\s*(\s*\([\w,=\s]+\s*\))?(.*)/){
+      $listeProperties = 1;
+      $propertiesAttributes = $2;
+      $typeProperties = "public:\n";
+      if (lc($propertiesAttributes) =~ /(access\s*=\s*private)/){
+        $typeProperties = "private:\n"
+      }
+      elsif (lc($propertiesAttributes) =~ /(access\s*=\s*public)/){
+        $typeProperties = "public:\n"
+      }
+      elsif (lc($propertiesAttributes) =~ /(access\s*=\s*protected)/){
+        $typeProperties = "protected:\n"
+      }
+      if ((lc($propertiesAttributes) =~ /(constant\s*=\s*false)/) || (lc($propertiesAttributes) =~ /(~constant)/)){
+      }
+      elsif (lc($propertiesAttributes) =~ /(constant(\s*=\s*true\s*)?)/){
+        $typeProperties = $typeProperties." Constant ";
+      }
+    }
+    if (/(^\s*enumeration)\s*(.*)/){
+      $listeEnumeration = 1;
+      $output=$output."public:\nenum ".$className." {";
+    }
+    if (/(^\s*events)\s*(.*)/){
+      $listeEvents = 1;
+      $output=$output."public:\nenum Events {";
+    }
+    if (/(^\s*methods)\s*(\s*\([\w,=\s]+\s*\))?(.*)/){
+      $methodAttribute = "public:\n";
+      $methodsAttributes = $2;
+      if (lc($methodsAttributes) =~ /(access\s*=\s*private)/){
+        $methodAttribute = "private:\n"
+      }
+      elsif (lc($methodsAttributes) =~ /(access\s*=\s*protected)/){
+        $methodAttribute = "protected:\n"
+      }
+      elsif (lc($methodsAttributes) =~ /(access\s*=\s*public)/){
+        $methodAttribute = "public:\n"
+      }
+      if (lc($methodsAttributes) =~ /(abstract(\s*=\s*true\s*)?)/){
+        $inAbstractMethodBlock = 1;
+        $methodAttribute = $methodAttribute." virtual ";
+      }
+      if ((lc($methodsAttributes) =~ /(static\s*=\s*false)/) || (lc($methodsAttributes) =~ /(~static)/)){
+      }
+      elsif (lc($methodsAttributes) =~ /(static(\s*=\s*true\s*)?)/){
+        $methodAttribute = $methodAttribute." static";
+      }
+    }
+	 $output=$output."\n";
+  }
+  close $in;
+}
+$output=$output."};\n";
+print $output;
Index: /issm/trunk-jpl-damage/src/perl/rsp_formatter.pl
===================================================================
--- /issm/trunk-jpl-damage/src/perl/rsp_formatter.pl	(revision 11330)
+++ /issm/trunk-jpl-damage/src/perl/rsp_formatter.pl	(revision 11330)
@@ -0,0 +1,55 @@
+#!/usr/bin/perl
+#
+#
+# write a list of object filenames to an .rsp file,
+# formatted according to tlib's input requirements
+#
+# usage:  rsp_formatter infile.rsp
+# where:  infile.rsp is a one line file consisting of
+#         object filenames
+# output: is the tlib-formatted infile.rsp
+# note:   multiple input files can be specified, e.g.
+#         rsp_formatter infile1.rsp infile2.rsp -etc.-
+
+use Fatal qw/ open /;
+use File::Basename;
+use Text::ParseWords;
+
+
+foreach (@ARGV) {
+
+#	loop (re)initialisation:
+	@words = ();
+	@new_words =();
+
+	($name,$path,$suffix) = fileparse($_,"\.rsp");
+	print "formatting $name$suffix for input to tlib...\n";
+
+#	open, read explicitly so we can treat one ARGV at a time:
+	open INFILE, "$_";
+	$line=<INFILE>;
+	close INFILE;
+	chomp($line);
+
+	@words = &parse_line('\s+', 0, $line);
+
+	$i=0;
+	foreach(@words) {
+		if ($i < $#words) {
+			push( @new_words, "+$_ &");
+		}
+		else {
+			push( @new_words, "+$_,$name");
+		}
+		$i++;
+	}
+
+	open(OUTFILE, ">$_");
+	foreach(@new_words) {
+		print OUTFILE "$_\n";
+	}
+	close(OUTFILE); 
+
+	print "...done\n";
+}
+
Index: /issm/trunk-jpl-damage/src/pro/bytscl.m
===================================================================
--- /issm/trunk-jpl-damage/src/pro/bytscl.m	(revision 11330)
+++ /issm/trunk-jpl-damage/src/pro/bytscl.m	(revision 11330)
@@ -0,0 +1,10 @@
+function value=bytscl(value)
+%INPUT function value=bytscl(value)
+%Equivalent of the bytscl idl routine.
+
+Min=min(value(:));
+Max=max(value(:));
+Top=255;
+
+pow=1;
+value=(Top + 0.9999)*(value - Min).^(pow)/(Max - Min)^(pow);
Index: /issm/trunk-jpl-damage/src/pro/plot_cielo.pro
===================================================================
--- /issm/trunk-jpl-damage/src/pro/plot_cielo.pro	(revision 11330)
+++ /issm/trunk-jpl-damage/src/pro/plot_cielo.pro	(revision 11330)
@@ -0,0 +1,146 @@
+print,'Cielo ..'
+openr,1,'Antarctica_CIELO_1km.bin'
+vel=fltarr(5601,5601)
+readu,1,vel & close,1
+
+print,'Read MOA ..'
+read_jpeg,'moa1000_r1_hp1.bamber_white_edit.jpg',im0,order=1
+
+vel=abs(vel)<3000.
+
+val=float(im0)/max(im0)
+indzero=where(vel EQ 0)
+ind=where(vel EQ 0) & ind0=where(vel LT 1.5) & vel(ind0)=1.5
+h=bytscl(alog(vel))/255.*360. & h(ind)=0. & vel(ind)=0.
+s=(0.5+vel/125)/1.5 & s=s<1 & s(ind)=0.
+
+color_convert,h,s,val,r,g,b,/hsv_rgb
+
+a=bytarr(3,5601,5601)
+a(0,*,*)=r
+a(1,*,*)=g
+a(2,*,*)=b
+ss=size(a) & six=ss(2) & siy=ss(3)
+
+re0=bytarr(5601,5601) & re0(*,*)=a(0,*,*)
+gr0=bytarr(5601,5601) & gr0(*,*)=a(1,*,*)
+bl0=bytarr(5601,5601) & bl0(*,*)=a(2,*,*)
+
+write_jpeg,'Antarctic_CIELO_1km_no_label'+'.jpg',a,true=1,order=1
+
+titi=bytarr(5601,5601)
+
+name=['/u/adelie1/eric/FOUND10196/Foundation_basin_index.save',$
+'/u/adelie1/eric/FOUND10196/Mollereisstrom_basin_index.save',$
+'/u/adelie1/eric/FOUND10196/Institute_basin_index.save',$
+'/u/adelie0/eric/Antarctic_GIS/Ian/IceStreamAW_basin_index.save',$
+'/u/adelie0/eric/Antarctic_GIS/Ian/IceStreamC_basin_index.save',$
+'/u/adelie0/eric/Antarctic_GIS/Ian/IceStreamD_basin_index.save',$
+'/u/adelie0/eric/Antarctic_GIS/Ian/IceStreamE_basin_index.save',$
+'/u/adelie0/eric/Antarctic_GIS/Ian/IceStreamF_basin_index.save',$
+'/u/adelie2/eric/RSAT9822-10165SLE/Slessor_basin_index.save',$
+'/u/adelie2/eric/RSAT9822-10165SLE/Bailey_basin_index.save',$
+'/u/adelie7/eric/Jutulstraumen94/Jutul_basin_index.save',$
+'/u/pib3b/eric/Getz/basin_getz_index.save',$
+'/u/adelie7/eric/Land_237/Land_basin_index.save',$
+'/u/adelie10/eric/Getz_437/basin_Hull_index.save',$
+'/u/pib3b/eric/Georges_1994/Track_009/basin_George9_index.save',$  ;Rym
+'/u/adelie9b/eric/RSAT9852-10195REC/rec_basin_index_ext_new.save',$
+'/u/pib1/eric/RSAT9806-10149Byrd/byrd_basin_index.save',$
+'/u/enderby3/eric/Nimrod_1997/basin_nimrod_index.save',$
+'/u/adelie7/eric/PIG22625/THW_basin_index.save',$
+'/u/adelie7/eric/PIG22625/PIG_basin_index.save',$
+'/u/adelie7/eric/PIG22625/KOH_SMI_POP_basin_index.save',$
+'/u/adelie7/eric/PIG22625/ISR_basin_index.save',$
+'/u/adelie7/eric/PIG22625/HAY_basin_index.save',$
+'/u/adelie45/adelie4/eric/Evans96_94/Evans_basin_index.save',$
+'/u/adelie45/adelie4/eric/Rutford96_t65/RUT_basin_index.save',$
+'/u/adelie45/adelie4/eric/Rutford96_t65/CAR_basin_index.save',$
+'/u/adelie45/adelie4/eric/Lambert_318/lambert_basin_index.save',$
+'/u/adelie13c/eric/ScottDenman/basin_DenmanScott_index.save',$
+'/u/adelie13b/eric/Totten24868/Totten_basin_index.save',$
+'/u/adelie45/eric/David23763-24765/david_basin_indexbis.save',$
+'/u/enderby2/eric/Mertz/Mertz_basin_index.save',$
+'/u/enderby2/eric/Mertz/Ninnis_basin_index.save',$
+;'/u/pib1/eric/Stancomb_450/stancomb_basin_index.save',$
+'/u/pib1/eric/Shirase_229/shirase_basin_index.save',$
+'/u/adelie10/eric/Cook/basin_Cook_index.save.new',$
+'/u/adelie9b/eric/RSAT25731_Rayner2000/Rayner_basin_index.save',$
+'/u/adelie1/eric/RSAT9806-10149MUL/Mulock_basin_index.save',$
+'/u/adelie13b/eric/Sabrina_431/Moscow_basin_index.save',$
+;'/u/pib3a/eric/RL_450/Vest_basin_index.save',$
+'/u/adelie1/eric/RSAT9805_10148BEARD/Beardmore_basin_index.save',$
+'/u/adelie2/eric/Frost_402/frost_basin_index_new.save',$
+'/u/adelie13b/eric/Dibble/Dibble_basin_index.save',$
+'/u/enderby2/eric/Phil/basin_Phil_new_index.save',$
+'/u/adelie1/eric/VenableIS/Venable_basin_index.save',$
+'/u/enderby0/eric/Track_482/basin_Abbot92_10_index.save',$
+'/u/enderby0/eric/Track_482/basin_Abbot92_24_index.save',$
+'/u/enderby0/eric/Track_482/basin_Eights_index.save',$
+'/u/adelie2/eric/Eltanin92/Eltanin_basin_index.save',$
+'/u/adelie1/eric/FOUND10196/SUF_basin_index.save',$
+'/u/pib3b/eric/Ragnhild/basin_Ragnhild_index.save',$
+'/u/pib3b/eric/Ragnhild/basin_Astrid_index.save',$
+'/u/enderby2/eric/Scylla25569/basin_american_index.save',$
+'/u/enderby2/eric/Scylla25569/basin_scylla_index.save',$
+'/u/pib3b/eric/Budd_231/basin_Buddetal_index.save',$
+'/u/enderby2/eric/Scylla25269/Part0/basin_robert_index.save',$
+'/u/amundsen1/eric/GeorgeVI_1996_66/basin_lidke_index.save',$
+'/u/amundsen1/eric/GeorgeVI_1996_66/basin_berg_index.save',$
+'/u/enderby3/eric/RL/basin_Ekstrom_index.save',$
+'/u/enderby3/eric/RL/basin_Jelbart_index.save',$
+'/u/enderby3/eric/RL/basin_Riiser_index.save',$
+'/u/enderby3/eric/RL/basin_Stancomb_index.save',$
+'/u/enderby3/eric/RL/basin_Veststraumen_index.save',$
+'/u/enderby3/eric/RL/basin_Coats_index.save',$
+;'/u/adelie12c/eric/Scylla/basin_track166_index.save',$
+'/u/enderby2/eric/Track166/basin_Eng_index.save',$ ;Eng
+'/u/enderby3/eric/RSAT25469-25812-26155Rennick_2000/basin_index_Rennick.save',$
+'/u/enderby3/eric/RSAT25362-25705-26048Ronne_2000/basin_index_Lassiter.save',$
+'/u/pib3b/eric/Georges_1994/Track_019/basin_SmithEwing_index.save',$
+'/u/enderby3/eric/Sulzberger_424/basin_Sulzberger_index.save']
+
+xmin_bamber=-560*5e03
+ymax_bamber=+560*5e03
+for i=0,n_elements(name)-1 do begin
+restore,name(i)
+xmin=xmin0 & ymax=ymax0
+pix=(xfill*1e3+xmin-xmin_bamber)/1000. & lin=(ymax_bamber-(ymax-yfill*1e3))/1000.
+for k=-1,1 do begin
+for l=-1,1 do begin
+titi(pix+k,lin+l)=255
+endfor
+endfor
+endfor
+
+xmin0=-560.*5e3 & ymax0=+560*5e3
+
+namebis=['/u/adelie7/eric/Wordie_381/basin_index_fleming.save',$
+'/u/adelie9b/eric/AP_018/basin_index_Crane.save',$
+'/u/adelie9b/eric/AP_018/basin_index_Jorum.save',$
+'/u/adelie9b/eric/AP_061/basin_index_flask.save',$
+'/u/adelie9b/eric/AP_061/basin_index_leppard.save',$
+;'/u/adelie9b/eric/AP_233/basin_index_mobil.new.save',$
+'/u/adelie9b/eric/AP_476/basin_index_drygalski.save',$
+'/u/adelie9b/eric/AP_476/basin_index_evans.save']
+for i=0,n_elements(namebis)-1 do begin
+restore,namebis(i)
+pix=(xfill*1e2+xmin-xmin0)/1000. & lin=(ymax0-(ymax-yfill*1e2))/1000.
+for k=-1,1 do begin
+for l=-1,1 do begin
+titi(pix+k,lin+l)=255
+endfor
+endfor
+endfor
+
+ind=where(titi ne 0)
+
+help,re0,gr0,bl0,a
+
+re0(ind)=0 & gr0(ind)=0 & bl0(ind)=0
+
+a(0,*,*)=re0 & a(1,*,*)=gr0 & a(2,*,*)=bl0
+
+write_jpeg,'Antarctic_CIELO_1km'+'.jpg',a,true=1,order=1
+
+end
Index: /issm/trunk-jpl-damage/src/py/README
===================================================================
--- /issm/trunk-jpl-damage/src/py/README	(revision 11330)
+++ /issm/trunk-jpl-damage/src/py/README	(revision 11330)
@@ -0,0 +1,24 @@
+# add in your bashrc 
+# export PYTHONSTARTUP="$ISSM_TIER/startup.py"
+# so that all python tools are loaded
+#
+# launch python
+
+>>> md=mode();
+>>> md
+>>> md.mesh
+>>> md.mesh.x
+
+# to try the hello module:
+
+>>> import hello
+>>> hello.say_hello("Mathieu")
+
+#to try test TriMesh (which converts a python list to a double pointer and echoes
+#its values:
+
+>>> import TriMesh
+>>> TriMesh.mesh([1,2,3])
+1
+2
+3
Index: /issm/trunk-jpl-damage/src/py/classes/mesh.py
===================================================================
--- /issm/trunk-jpl-damage/src/py/classes/mesh.py	(revision 11330)
+++ /issm/trunk-jpl-damage/src/py/classes/mesh.py	(revision 11330)
@@ -0,0 +1,9 @@
+class mesh:
+	"""Python mesh class"""
+	x = []
+	y = []
+	elements = []
+	def __repr__(self):
+		return """x: X coordinates
+		        y: Y coordinates
+				  elements: indexing """
Index: /issm/trunk-jpl-damage/src/py/classes/model.py
===================================================================
--- /issm/trunk-jpl-damage/src/py/classes/model.py	(revision 11330)
+++ /issm/trunk-jpl-damage/src/py/classes/model.py	(revision 11330)
@@ -0,0 +1,9 @@
+from mesh import *
+
+class model:
+	"""Python model class"""
+	mesh=mesh()
+	def __init__(self):
+		print 'new model created'
+	def __repr__(self):
+		return "   mesh: mesh properties"
Index: /issm/trunk-jpl-damage/src/py/modules/TriMesh/Makefile
===================================================================
--- /issm/trunk-jpl-damage/src/py/modules/TriMesh/Makefile	(revision 11330)
+++ /issm/trunk-jpl-damage/src/py/modules/TriMesh/Makefile	(revision 11330)
@@ -0,0 +1,19 @@
+all: ogive
+
+ice:
+	g++ -bundle  -bind \
+		-I$(ISSM_TIER)/externalpackages/boost/install/include \
+		-L$(ISSM_TIER)/externalpackages/boost/install/lib -lboost_python \
+		-L/usr/lib/python2.6/config/ -lpython2.6 \
+		TriMeshmodule.cpp -o TriMesh.so
+
+ogive:
+	g++ \
+		-I$(ISSM_TIER)/externalpackages/boost/install/include \
+		-I/opt/local/include/python2.5/ \
+		-L$(ISSM_TIER)/externalpackages/boost/install/lib -lboost_python \
+		-L/usr/lib/ -lpython2.5 \
+		TriMeshmodule.cpp -o TriMesh.so -bundle
+
+clean:
+	rm TriMesh.so
Index: /issm/trunk-jpl-damage/src/py/modules/TriMesh/TriMeshmodule.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/py/modules/TriMesh/TriMeshmodule.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/py/modules/TriMesh/TriMeshmodule.cpp	(revision 11330)
@@ -0,0 +1,50 @@
+#include <stdio.h>
+using namespace std; 
+
+void meshx(double* index,int n) {
+	int i,j;
+	for(int i=0;i<n;i++){
+		printf("%g\n",index[i]);
+	}
+}
+
+#include <boost/python.hpp>
+#include <boost/python/module.hpp>
+#include <boost/python/def.hpp>
+using namespace boost::python;
+
+void FetchData(double** array,int* N,boost::python::list pythonlist){/*{{{*/
+
+	/*Get list size*/
+	int n = boost::python::extract<int>(pythonlist.attr("__len__")());
+
+	/*Assign double array and populate*/
+	double* clist = new double[n];
+	for (int i=0;i<n;i++) clist[i] = extract<double>(pythonlist[i]);
+
+	/*Assign output pointers*/
+	*array = clist;
+	if(N) *N = n;
+}/*}}}*/
+
+void mesh(boost::python::list INDEX){
+	double *index=NULL;
+	int     n;
+
+	FetchData(&index,&n,INDEX);
+
+	/*Call x layer*/
+	meshx(index,n);
+
+	/*Clean up*/
+	delete index;
+}
+
+
+#include <boost/python/module.hpp>
+#include <boost/python/def.hpp>
+using namespace boost::python;
+
+BOOST_PYTHON_MODULE(TriMesh){
+	def("mesh",mesh);
+}
Index: /issm/trunk-jpl-damage/src/py/modules/hello/Makefile
===================================================================
--- /issm/trunk-jpl-damage/src/py/modules/hello/Makefile	(revision 11330)
+++ /issm/trunk-jpl-damage/src/py/modules/hello/Makefile	(revision 11330)
@@ -0,0 +1,20 @@
+all: ogive
+
+ice:
+	g++ -bundle  -bind \
+		-I$(ISSM_TIER)/externalpackages/boost/install/include \
+		-I/usr/include/python2.6/ \
+		-L$(ISSM_TIER)/externalpackages/boost/install/lib -lboost_python \
+		-L/usr/lib/python2.6/config/ -lpython2.6 \
+		hellomodule.cpp -o hello.so
+
+ogive:
+	g++ \
+		-I$(ISSM_TIER)/externalpackages/boost/install/include \
+		-I/usr/include/python2.5/ \
+		-L$(ISSM_TIER)/externalpackages/boost/install/lib -lboost_python \
+		-L/usr/lib/python2.5/config/ -lpython2.5 \
+		hellomodule.cpp -o hello.so -bundle
+
+clean:
+	rm hello.so
Index: /issm/trunk-jpl-damage/src/py/modules/hello/hellomodule.cpp
===================================================================
--- /issm/trunk-jpl-damage/src/py/modules/hello/hellomodule.cpp	(revision 11330)
+++ /issm/trunk-jpl-damage/src/py/modules/hello/hellomodule.cpp	(revision 11330)
@@ -0,0 +1,14 @@
+#include <iostream>
+using namespace std; 
+void say_hello(const char* name) {
+	    cout << "Hello " <<  name << "!\n";
+}
+
+#include <boost/python/module.hpp>
+#include <boost/python/def.hpp>
+using namespace boost::python;
+
+BOOST_PYTHON_MODULE(hello)
+{
+	    def("say_hello", say_hello);
+}
Index: /issm/trunk-jpl-damage/startup.m
===================================================================
--- /issm/trunk-jpl-damage/startup.m	(revision 11330)
+++ /issm/trunk-jpl-damage/startup.m	(revision 11330)
@@ -0,0 +1,61 @@
+%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 
+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 '/src/m/utils/']); %loads recursivepath
+addpath([ISSM_TIER '/doc']);
+addpath([ISSM_TIER '/bin']);
+addpath(recursivepath([ISSM_TIER '/src/m']));
+addpath(recursivepath([ISSM_TIER '/externalpackages/scotch']));
+addpath(recursivepath([ISSM_TIER '/externalpackages/canos']));
+addpath(recursivepath([ISSM_TIER '/externalpackages/kml']));
+addpath(recursivepath([ISSM_TIER '/externalpackages/googleearthtoolbox/']));
+addpath(recursivepath([ISSM_TIER '/externalpackages/export_fig']));
+clear ISSM_TIER;
+
+%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
+
+%  deal with Matlab bug (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;
+clear ans;
+
+%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/trunk-jpl-damage/startup.py
===================================================================
--- /issm/trunk-jpl-damage/startup.py	(revision 11330)
+++ /issm/trunk-jpl-damage/startup.py	(revision 11330)
@@ -0,0 +1,29 @@
+#!/usr/bin/env python
+# STARTUP - Python startup script
+#
+#  startup.py is a script run by python at the beginning of a session, just
+#  before handing over the prompt to the user if the environment variable
+#  PYTHONSTARTUP is defined:
+#  export PYTHONSTARTUP=$ISSM_TIER/startup.py
+#  This startup script should be run by users before trying to use ISSM.
+
+import os,sys
+
+#Recover ISSM_TIER, ISSM_DIR  and USERNAME
+ISSM_TIER=os.getenv('ISSM_TIER')
+USERNAME =os.getenv('USER')
+if(ISSM_TIER==None):
+	raise NameError('"ISSM_TIER" environment variable is empty! You should define ISSM_TIER in your .cshrc or .bashrc!')
+
+#Now add all issm code paths necessary to run issm smoothly. 
+#We capture the error output, so that we can warn the user to update 
+#the variable ISSM_TIER in this file, in case it is not correctly setup. 
+
+#ISSM path
+sys.path.append(ISSM_TIER+'/src/py')
+sys.path.append(ISSM_TIER+'/src/py/classes')
+sys.path.append(ISSM_TIER+'/src/py/modules/TriMesh')
+sys.path.append(ISSM_TIER+'/src/py/modules/hello')
+from model import *
+
+print "\n  To get started with ISSM, type issmdoc at the command prompt.\n\n"
Index: /issm/trunk-jpl-damage/test/Exp/79North.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/79North.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/79North.exp	(revision 11330)
@@ -0,0 +1,22 @@
+## Name:DomainOutline
+## Icon:0
+# Points Count Value
+16 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
+489754.9899476374 -1026299.4221655356
+477094.8404779918 -1020390.2025476890
+468158.2643817714 -1015096.5266400346
+464009.1397656691 -1027407.4008438819
+
Index: /issm/trunk-jpl-damage/test/Exp/79NorthShelf.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/79NorthShelf.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/79NorthShelf.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/CrossLineEISMINT.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/CrossLineEISMINT.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/CrossLineEISMINT.exp	(revision 11330)
@@ -0,0 +1,7 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+10000 199999 
+10000 1
Index: /issm/trunk-jpl-damage/test/Exp/ISMIP10000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/ISMIP10000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/ISMIP10000.exp	(revision 11330)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 2500
+10000 2500
Index: /issm/trunk-jpl-damage/test/Exp/ISMIP100000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/ISMIP100000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/ISMIP100000.exp	(revision 11330)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 50000
+100000 50000
Index: /issm/trunk-jpl-damage/test/Exp/ISMIP160000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/ISMIP160000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/ISMIP160000.exp	(revision 11330)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 40000
+160000 40000
Index: /issm/trunk-jpl-damage/test/Exp/ISMIP20000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/ISMIP20000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/ISMIP20000.exp	(revision 11330)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 5000
+20000 5000
Index: /issm/trunk-jpl-damage/test/Exp/ISMIP40000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/ISMIP40000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/ISMIP40000.exp	(revision 11330)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 10000
+40000 10000
Index: /issm/trunk-jpl-damage/test/Exp/ISMIP5000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/ISMIP5000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/ISMIP5000.exp	(revision 11330)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 1225
+5000 1225
Index: /issm/trunk-jpl-damage/test/Exp/ISMIP80000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/ISMIP80000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/ISMIP80000.exp	(revision 11330)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+0 20000
+80000 20000
Index: /issm/trunk-jpl-damage/test/Exp/ISMIPE.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/ISMIPE.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/ISMIPE.exp	(revision 11330)
@@ -0,0 +1,7 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+2 1.
+# X pos Y pos
+5 0 
+5 5000
Index: /issm/trunk-jpl-damage/test/Exp/MassFlux1.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/MassFlux1.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/MassFlux1.exp	(revision 11330)
@@ -0,0 +1,7 @@
+## Name:MassFlux1
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+200000 400000
+500000 800000
Index: /issm/trunk-jpl-damage/test/Exp/MassFlux2.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/MassFlux2.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/MassFlux2.exp	(revision 11330)
@@ -0,0 +1,7 @@
+## Name:MassFlux2
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+500000 800000
+800000 400000
Index: /issm/trunk-jpl-damage/test/Exp/MassFlux3.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/MassFlux3.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/MassFlux3.exp	(revision 11330)
@@ -0,0 +1,7 @@
+## Name:MassFlux3
+## Icon:0
+# Points Count Value
+2 1.000000
+# X pos Y pos
+200000 400000
+800000 400000
Index: /issm/trunk-jpl-damage/test/Exp/MassFlux4.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/MassFlux4.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/MassFlux4.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/MassFlux5.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/MassFlux5.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/MassFlux5.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/MassFlux6.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/MassFlux6.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/MassFlux6.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/Pig.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/Pig.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/Pig.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/PigIslands.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/PigIslands.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/PigIslands.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/PigShelves.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/PigShelves.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/PigShelves.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/Rifts.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/Rifts.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/Rifts.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/RoundFrontEISMINT.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/RoundFrontEISMINT.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/RoundFrontEISMINT.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/Square.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/Square.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/Square.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/SquareEISMINT.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/SquareEISMINT.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/SquareEISMINT.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/SquareEISMINT750000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/SquareEISMINT750000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/SquareEISMINT750000.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/SquareFront.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/SquareFront.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/SquareFront.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/SquareFrontEISMINT.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/SquareFrontEISMINT.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/SquareFrontEISMINT.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/SquareHalfRight.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/SquareHalfRight.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/SquareHalfRight.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/SquareHole.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/SquareHole.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/SquareHole.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/SquareISMIP.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/SquareISMIP.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/SquareISMIP.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/SquareRifts.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/SquareRifts.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/SquareRifts.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/SquareRiftsLateral.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/SquareRiftsLateral.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/SquareRiftsLateral.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/SquareShelf.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/SquareShelf.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/SquareShelf.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/Square_10000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/Square_10000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/Square_10000.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/Square_160000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/Square_160000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/Square_160000.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/Square_20000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/Square_20000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/Square_20000.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/Square_40000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/Square_40000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/Square_40000.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/Square_5000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/Square_5000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/Square_5000.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/Exp/Square_80000.exp
===================================================================
--- /issm/trunk-jpl-damage/test/Exp/Square_80000.exp	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Exp/Square_80000.exp	(revision 11330)
@@ -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/trunk-jpl-damage/test/NightlyRun/IdFromString.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/IdFromString.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/IdFromString.m	(revision 11330)
@@ -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/trunk-jpl-damage/test/NightlyRun/IdToName.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/IdToName.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/IdToName.m	(revision 11330)
@@ -0,0 +1,308 @@
+function name=IdToName(id);
+%IDTONAME- return name of test
+%
+%   Usage:
+%      name=IdToName(id);
+
+switch id,
+
+	case 101, name='SquareShelfConstrainedDiagM2dSerial';
+	case 102, name='SquareShelfConstrainedDiagM2dParallel';
+	case 103, name='SquareShelfConstrainedDiagM3dSerial';
+	case 104, name='SquareShelfConstrainedDiagM3dParallel';
+	case 105, name='SquareShelfConstrainedDiagP3dSerial';
+	case 106, name='SquareShelfConstrainedDiagP3dParallel';
+	case 107, name='SquareShelfConstrainedDiagS3dSerial';
+	case 108, name='SquareShelfConstrainedDiagS3dParallel';
+	case 109, name='SquareShelfConstrainedProg2dSerial';
+	case 110, name='SquareShelfConstrainedProg2dParallel';
+	case 111, name='SquareShelfConstrainedProg2dDGSerial';
+	case 112, name='SquareShelfConstrainedProg2dDGParallel';
+	case 113, name='SquareShelfConstrainedProg3dSerial';
+	case 114, name='SquareShelfConstrainedProg3dParallel';
+	case 115, name='SquareShelfConstrainedTherSteaSerial';
+	case 116, name='SquareShelfConstrainedTherSteaParallel';
+	case 117, name='SquareShelfConstrainedTherTranSerial';
+	case 118, name='SquareShelfConstrainedTherTranParallel';
+	case 119, name='SquareShelfConstrainedTranM2dSerial';
+	case 120, name='SquareShelfConstrainedTranM2dParallel';
+	case 121, name='SquareShelfConstrainedTranP3dSerial';
+	case 122, name='SquareShelfConstrainedTranP3dParallel';
+	case 123, name='SquareShelfConstrainedSurfSlop2dSerial';
+	case 124, name='SquareShelfConstrainedSurfSlop2dParallel';
+	case 125, name='SquareShelfConstrainedSurfSlop3dSerial';
+	case 126, name='SquareShelfConstrainedSurfSlope3dParallel';
+	case 127, name='SquareShelfConstrainedBedSlop2dSerial';
+	case 128, name='SquareShelfConstrainedBedSlop2dParallel';
+	case 129, name='SquareShelfConstrainedBedSlop3dSerial';
+	case 130, name='SquareShelfConstrainedBedSlop3dParallel';
+	case 131, name='SquareShelfConstrainedBalThic2dSerial';
+	case 132, name='SquareShelfConstrainedBalThic2dParallel';
+	case 133, name='SquareShelfConstrainedBalThic3dSerial';
+	case 134, name='SquareShelfConstrainedBalThic3dParallel';
+	case 135, name='SquareShelfConstrainedBalThic2dDGSerial';
+	case 136, name='SquareShelfConstrainedBalThic2dDGParallel';
+	case 137, name='SquareBamgMesh';
+	case 139, name='SquareShelfConstrainedEnthalpySteaSerial';
+	case 140, name='SquareShelfConstrainedEnthalpySteaParallel';
+	case 141, name='SquareShelfConstrainedEnthalpyTranSerial';
+	case 142, name='SquareShelfConstrainedEnthalpyTranParallel';
+	case 201, name='SquareShelfDiagM2dSerial';
+	case 202, name='SquareShelfDiagM2dParallel';
+	case 203, name='SquareShelfDiagM3dSerial';
+	case 204, name='SquareShelfDiagM3dParallel';
+	case 205, name='SquareShelfDiagP3dSerial';
+	case 206, name='SquareShelfDiagP3dParallel';
+	case 207, name='SquareShelfDiagS3dSerial';
+	case 208, name='SquareShelfDiagS3dParallel';
+	case 209, name='SquareShelfDiagMP3dPenaltiesSerial';
+	case 210, name='SquareShelfDiagMP3dPenaltiesParallel';
+	case 211, name='SquareShelfTherSteaSerial';
+	case 212, name='SquareShelfTherSteaParallel';
+	case 213, name='SquareShelfTherTranSerial';
+	case 214, name='SquareShelfTherTranParallel';
+	case 215, name='SquareShelfTranM2dSerial';
+	case 216, name='SquareShelfTranM2dParallel';
+	case 217, name='SquareShelfTranM3dSerial';
+	case 218, name='SquareShelfTranM3dParallel';
+	case 219, name='SquareShelfTranP3dSerial';
+	case 220, name='SquareShelfTranP3dParallel';
+	case 221, name='SquareShelfTranS3dSerial';
+	case 222, name='SquareShelfTranS3dParallel';
+	case 223, name='SquareShelfCMBM2dSerial';
+	case 224, name='SquareShelfCMBM2dParallel';
+	case 225, name='SquareShelfCMBM3dSerial';
+	case 226, name='SquareShelfCMBM3dParallel';
+	case 227, name='SquareShelfCMBP3dSerial';
+	case 228, name='SquareShelfCMBP3dParallel';
+	case 229, name='SquareShelfCMBS3dSerial';
+	case 230, name='SquareShelfCMBS3dParallel';
+	case 231, name='SquareShelfDiagM2dRiftSerial';
+	case 232, name='SquareShelfDiagM2dRiftParallel';
+	case 233, name='SquareShelfConstrainedSerial';
+	case 234, name='SquareShelfConstrainedParallel';
+	case 235, name='SquareShelfConstrainedDakotaBSerial';
+	case 236, name='SquareShelfConstrainedDakotaBParallel';
+	case 237, name='SquareShelfDiagMP3dTilingSerial';
+	case 238, name='SquareShelfDiagMP3dTilingParallel';
+	case 239, name='SquareShelfDiagPS3dTilingSerial';
+	case 240, name='SquareShelfDiagPS3dTilingParallel';
+	case 241, name='SquareShelfDiagMS3dTilingSerial';
+	case 242, name='SquareShelfDiagMS3dTilingParallel';
+	case 243, name='SquareShelfDiagM2dTransientIncrHydroSerial';
+	case 244, name='SquareShelfDiagM2dTransientIncrHydroParallel';
+	case 245, name='SquareShelfDiagM2dTransientIncrNonHydroSerial';
+	case 246, name='SquareShelfDiagM2dTransientIncrNonHydroParallel';
+	case 247, name='SquareShelfDiagP3dTransientIncrHydroSerial';
+	case 248, name='SquareShelfDiagP3dTransientIncrHydroParallel';
+	case 249, name='SquareShelfDiagP3dTransientIncrNonHydroSerial';
+	case 250, name='SquareShelfDiagP3dTransientIncrNonHydroParallel';
+	case 251, name='SquareShelfTranCflM2dSerial';
+	case 252, name='SquareShelfTranCflM2dParallel';
+	case 253, name='SquareShelfTranCflP3dSerial';
+	case 254, name='SquareShelfTranCflP3dParallel';
+	case 255, name='SquareShelfTranForceNeg2dSerial';
+	case 256, name='SquareShelfTranForceNeg2dParallel';
+	case 257, name='SquareShelfTranForcePos2dSerial';
+	case 258, name='SquareShelfTranForcePos2dParallel';
+	case 259, name='SquareShelfTranForceNeg3dSerial';
+	case 260, name='SquareShelfTranForceNeg3dParallel';
+	case 261, name='SquareShelfTranForcePos3dSerial';
+	case 262, name='SquareShelfTranForcePos3dParallel';
+	case 263, name='SquareShelfTherTranForcTempSerial';
+	case 264, name='SquareShelfTherTranForcTempParallel';
+	case 265, name='SquareShelfTranP3dForcTempSerial';
+	case 266, name='SquareShelfTranP3dForcTempParallel';
+	case 267, name='SquareShelfTranForceNeg2dDakotaSamp';
+   case 268, name='SquareShelfTranForceNeg2dDakotaLocal';
+	case 301, name='SquareSheetConstrainedDiagM2dSerial';
+	case 302, name='SquareSheetConstrainedDiagM2dParallel';
+	case 303, name='SquareSheetConstrainedDiagH2dSerial';
+	case 304, name='SquareSheetConstrainedDiagH2dParallel';
+	case 305, name='SquareSheetConstrainedDiagHM2dSerial';
+	case 306, name='SquareSheetConstrainedDiagHM2dParallel';
+	case 307, name='SquareSheetConstrainedDiagM3dSerial';
+	case 308, name='SquareSheetConstrainedDiagM3dParallel';
+	case 309, name='SquareSheetConstrainedDiagH3dSerial';
+	case 310, name='SquareSheetConstrainedDiagH3dParallel';
+	case 311, name='SquareSheetConstrainedDiagHM3dSerial';
+	case 312, name='SquareSheetConstrainedDiagHM3dParallel';
+	case 313, name='SquareSheetConstrainedDiagP3dSerial';
+	case 314, name='SquareSheetConstrainedDiagP3dParallel';
+	case 315, name='SquareSheetConstrainedDiagS3dSerial';
+	case 316, name='SquareSheetConstrainedDiagS3dParallel';
+	case 317, name='SquareSheetConstrainedProg2dSerial';
+	case 318, name='SquareSheetConstrainedProg2dParallel';
+	case 319, name='SquareSheetConstrainedProg2dDGSerial';
+	case 320, name='SquareSheetConstrainedProg2dDGParallel';
+	case 321, name='SquareSheetConstrainedProg3dSerial';
+	case 322, name='SquareSheetConstrainedProg3dParallel';
+	case 323, name='SquareSheetConstrainedTherSteaSerial';
+	case 324, name='SquareSheetConstrainedTherSteaParallel';
+	case 325, name='SquareSheetConstrainedTherTranSerial';
+	case 326, name='SquareSheetConstrainedTherTranParallel';
+	case 327, name='SquareSheetConstrainedTranH2dSerial';
+	case 328, name='SquareSheetConstrainedTranH2dParallel';
+	case 329, name='SquareSheetConstrainedTranH3dSerial';
+	case 330, name='SquareSheetConstrainedTranH3dParallel';
+	case 331, name='SquareSheetConstrainedTranM2dSerial';
+	case 332, name='SquareSheetConstrainedTranM2dParallel';
+	case 333, name='SquareSheetConstrainedTranP3dSerial';
+	case 334, name='SquareSheetConstrainedTranP3dParallel';
+	case 335, name='SquareSheetConstrainedSteaH3dSerial';
+	case 336, name='SquareSheetConstrainedSteaH3dParallel';
+	case 337, name='SquareSheetConstrainedCMDragM2dSerial';
+	case 338, name='SquareSheetConstrainedCMDragM2dParallel';
+	case 339, name='SquareSheetConstrainedCMDragM3dSerial';
+	case 340, name='SquareSheetConstrainedCMDragM3dParallel';
+	case 341, name='SquareSheetConstrainedCMDragP3dSerial';
+	case 342, name='SquareSheetConstrainedCMDragP3dParallel';
+	case 343, name='SquareSheetConstrainedCMDragS3dSerial';
+	case 344, name='SquareSheetConstrainedCMDragS3dParallel';
+	case 345, name='SquareSheetConstrainedTranCflM2dSerial';
+	case 346, name='SquareSheetConstrainedTranCflM2dParallel';
+	case 347, name='SquareSheetConstrainedTranCflH3dSerial';
+	case 348, name='SquareSheetConstrainedTranCflH3dParallel';
+	case 349, name='SquareSheetConstrainedEnthalpySteaSerial';
+	case 350, name='SquareSheetConstrainedEnthalpySteaParallel';
+	case 351, name='SquareSheetConstrainedEnthalpyTranSerial';
+	case 352, name='SquareSheetConstrainedEnthalpyTranParallel';
+	case 401, name='SquareSheetShelfDiagM2dSerial';
+	case 402, name='SquareSheetShelfDiagM2dParallel';
+	case 403, name='SquareSheetShelfDiagM3dSerial';
+	case 404, name='SquareSheetShelfDiagM3dParallel';
+	case 405, name='SquareSheetShelfDiagP3dSerial';
+	case 406, name='SquareSheetShelfDiagP3dParallel';
+	case 407, name='SquareSheetShelfDiagS3dSerial';
+	case 408, name='SquareSheetShelfDiagS3dParallel';
+	case 409, name='SquareSheetShelfDiagMP3dPenaltiesSerial';
+	case 410, name='SquareSheetShelfDiagMP3dPenaltiesParallel';
+	case 411, name='SquareSheetShelfTherSteaSerial';
+	case 412, name='SquareSheetShelfTherSteaParallel';
+	case 413, name='SquareSheetShelfTherTranSerial';
+	case 414, name='SquareSheetShelfTherTranParallel';
+	case 415, name='SquareSheetShelfTranM2dSerial';
+	case 416, name='SquareSheetShelfTranM2dParallel';
+	case 417, name='SquareSheetShelfTranMP3dPenaltiesSerial';
+	case 418, name='SquareSheetShelfTranMP3dPenaltiesParallel';
+	case 419, name='SquareSheetShelfSteaM3dSerial';
+	case 420, name='SquareSheetShelfSteaM3dParallel';
+	case 421, name='SquareSheetShelfSteaP3dSerial';
+	case 422, name='SquareSheetShelfSteaP3dParallel';
+	case 423, name='SquareSheetShelfDiadM3dDakotaSerial';
+	case 424, name='SquareSheetShelfDiadM3dDakotaParallel';
+	case 425, name='SquareSheetShelfDiadM3dDakotaPartSerial';
+	case 426, name='SquareSheetShelfDiadM3dDakotaPartParallel';
+	case 427, name='SquareSheetShelfDiadM3dDakotaMassFluxSerial';
+	case 428, name='SquareSheetShelfDiadM3dDakotaMassFluxParallel';
+	case 429, name='SquareSheetShelfCMDragSteaM3dSerial';
+	case 430, name='SquareSheetShelfCMDragSteaM3dParallel';
+	case 431, name='SquareSheetShelfCMDragSteaP3dSerial';
+	case 432, name='SquareSheetShelfCMDragSteaP3dParallel';
+	case 434, name='SquareSheetShelfDiadM3dDakotaSamp';
+	case 435, name='SquareSheetShelfDiadM3dDakotaAreaAverage';
+	case 437, name='SquareSheetShelfDiagMP3dTilingSerial';
+	case 438, name='SquareSheetShelfDiagMP3dTilingParallel';
+	case 439, name='SquareSheetShelfDakotaScaledResponse';
+	case 440, name='SquareSheetShelfDakotaScaledResponse';
+	case 441, name='SquareSheetShelfDiagPS3dTilingSerial';
+	case 442, name='SquareSheetShelfDiagPS3dTilingParallel';
+	case 443, name='SquareSheetShelfDiagMS3dTilingSerial';
+	case 444, name='SquareSheetShelfDiagMS3dTilingParallel';
+	case 445, name='RoundSheetShelfGLMigrationM2dSerial';
+	case 446, name='RoundSheetShelfGLMigrationM2dParallel';
+	case 447, name='SquareSheetShelfGroundingLine2dAgressiceSerial';
+	case 448, name='SquareSheetShelfGroundingLine2dAgressiceParallel';
+	case 449, name='SquareSheetShelfGroundingLine2dSoftSerial';
+	case 450, name='SquareSheetShelfGroundingLine2dSoftParallel';
+	case 451, name='SquareSheetShelfGroundingLine3dAgressiceSerial';
+	case 452, name='SquareSheetShelfGroundingLine3dAgressiceParallel';
+	case 453, name='SquareSheetShelfGroundingLine3dSoftSerial';
+	case 454, name='SquareSheetShelfGroundingLine3dSoftParallel';
+	case 501, name='PigDiagM2dSerial';
+	case 502, name='PigDiagM2dParallel';
+	case 503, name='PigDiagP3dSerial';
+	case 504, name='PigDiagP3dParallel';
+	case 505, name='PigDiagS3dSerial';
+	case 506, name='PigDiagS3dParallel';
+	case 507, name='PigTranM2dSerial';
+	case 508, name='PigTranM2dParallel';
+	case 509, name='PigTranM3dSerial';
+	case 510, name='PigTranM3dParallel';
+	case 511, name='PigTranP3dSerial';
+	case 512, name='PigTranP3dParallel';
+	case 513, name='PigTranS3dSerial';
+	case 514, name='PigTranS3dParallel';
+	case 515, name='PigSteaM3dSerial';
+	case 516, name='PigSteaM3dParallel';
+	case 517, name='PigSteaP3dSerial';
+	case 518, name='PigSteaP3dParallel';
+	case 519, name='PigSteaS3dSerial';
+	case 520, name='PigSteaS3dParallel';
+	case 521, name='PigCMBS3dSerial';
+	case 522, name='PigCMBS3dparallel';
+	case 523, name='PigCMDragP3dSerial';
+	case 524, name='PigCMDragP3dparallel';
+	case 525, name='PigCMDragSteaM3dSerial';
+	case 526, name='PigCMDragSteaM3dparallel';
+	case 527, name='PigBamgMesh';
+	case 529, name='PigTherTranSUPGSerial';
+	case 530, name='PigTherTranSUPGParallel';
+	case 531, name='PigTherSteaSUPGSerial';
+	case 532, name='PigTherSteaSUPGParallel';
+	case 601, name='79NorthProg2dSerial';
+	case 602, name='79NorthProg2dParallel';
+	case 603, name='79NorthProg2dDGSerial';
+	case 604, name='79NorthProg2dDGParallel';
+	case 605, name='79NorthProg3dSerial';
+	case 606, name='79NorthProg3dParallel';
+	case 607, name='79NorthSurfSlop2dSerial';
+	case 608, name='79NorthSurfSlop2dParallel';
+	case 609, name='79NorthSurfSlop3dSerial';
+	case 610, name='79NorthSurfSlop3dParallel';
+	case 611, name='79NorthBedSlop2dSerial';
+	case 612, name='79NorthBedSlop2dParallel';
+	case 613, name='79NorthBedSlop3dSerial';
+	case 614, name='79NorthBedSlop3dParallel';
+	case 615, name='79NorthBalThic2dSerial';
+	case 616, name='79NorthBalThic2dParallel';
+	case 617, name='79NorthBalThic2dDGSerial';
+	case 618, name='79NorthBalThic2dDGParallel';
+	case 619, name='79NorthBalThic3dSerial';
+	case 620, name='79NorthBalThic3dParallel';
+	case 621, name='79NorthCMBalThic2dCGSerial';
+	case 622, name='79NorthCMBalThic2dCGParallel';
+	case 623, name='79NorthCMBalThic2dDGSerial';
+	case 624, name='79NorthCMBalThic2dDGParallel';
+	case 625, name='79NorthCMBalThicVxVyParallel';
+	case 626, name='79NorthCMBalThicVxVySerial';
+	case 1101, name='ISMIPAPattyn';
+	case 1102, name='ISMIPAStokes';
+	case 1103, name='ISMIPBPattyn';
+	case 1104, name='ISMIPBStokes';
+	case 1105, name='ISMIPCPattyn';
+	case 1106, name='ISMIPCStokes';
+	case 1107, name='ISMIPDPattyn';
+	case 1108, name='ISMIPDStokes';
+	case 1109, name='ISMIPE';
+	case 1110, name='ISMIPF';
+	case 1201, name='EISMINTMassConservation';
+	case 1202, name='EISMINTDiag1';
+	case 1203, name='EISMINTDiag2';
+	case 1204, name='EISMINTTran2';
+	case 1205, name='EISMINTRoundIceSheetStaticHutter';
+	case 1206, name='EISMINTRoundIceSheetStaticPattyn';
+	case 1207, name='EISMINTRoundIceSheetStaticStokes';
+	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='SquareShelfM2dRotation';
+	case 1602, name='SquareSheetShelfP3dRotation';
+	otherwise, name='N/A';
+end
Index: /issm/trunk-jpl-damage/test/NightlyRun/Makefile
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/Makefile	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/Makefile	(revision 11330)
@@ -0,0 +1,2 @@
+clean: 
+	rm -rf *.tar.gz *.bin *.errlog *.outlog  *.outbin *.petsc *.queue *.run valgrind.log*
Index: /issm/trunk-jpl-damage/test/NightlyRun/README
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/README	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/README	(revision 11330)
@@ -0,0 +1,37 @@
+
+# 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 to many .par and .exp files, so try to use the existing ones as much as possible.
+To modify some characteristics, do it in the testxxx.m file.
+The testxxx_nightly.m is used to define the parameters you want to check in the nightlyruns.
+Specify the field_names the field_values and the tolerance in this file.
+Don't forget to commit the archive (Archivexxx in ../Archives)
Index: /issm/trunk-jpl-damage/test/NightlyRun/dak.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/dak.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/dak.m	(revision 11330)
@@ -0,0 +1,52 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',1);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+%Set up transient
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1 ];
+
+md.surfaceforcings.mass_balance=smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+
+%sigma_on_partition=AreaAverageOntoPartition(md,sigma);
+%sigma_on_grids=sigma_on_partition(md.part+1); %just to check in case
+%md.variables.thickness=normal_uncertain('scaled_Thickness',1,1);
+%md.variables.thickness.stddev=sigma_on_partition;
+
+%Dakota inputs,outputs
+md.qmu.variables.surface_mass_balance=normal_uncertain('scaled_SurfaceforcingsMassBalance',1,0.1);
+md.qmu.responses.IceVolume=response_function('IceVolume',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%%  nond_sampling study
+md.qmu.method     =dakota_method('nond_samp');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+'seed',1234,...
+'samples',20,...
+'sample_type','lhs');
+
+%%  a variety of parameters
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+md.qmu.isdakota=1;
+
+md.transient.requested_outputs=IceVolumeEnum();
+
+md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+%md.debug.valgrind=1;
+%md.verbose.solution=true;
+md=solve(md,TransientSolutionEnum,'overwrite','y');
Index: /issm/trunk-jpl-damage/test/NightlyRun/runme.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/runme.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/runme.m	(revision 11330)
@@ -0,0 +1,214 @@
+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'     'nightly' (nightly run/ daily run)
+%                      'ismip'  : validation of ismip-hom tests
+%                      'eismint': validation of eismint tests
+%                      'thermal': validation of thermal tests
+%                      'mesh'   : validation of mesh tests
+%                      ...
+%      'procedure'     'check' : run the test (default)
+%                      'update': update the archive
+%                      'model' : prepare the model but no test is run
+%
+%   Usage:
+%      md=runme(varargin);
+%
+%   Examples:
+%      runme;
+%      runme('exclude',101);
+%      md=runme('id',102,'procedure','model');
+
+%Get ISSM_TIER variable
+ISSM_TIER=issmtier();
+
+%Check inputs
+% {{{1
+if nargout>1
+	help runme
+	error('runme error message: bad usage');
+end
+
+%recover options
+options=pairoptions(varargin{:});
+% }}}
+
+%Process options
+%GET benchmark {{{1
+benchmark=getfieldvalue(options,'benchmark','nightly');
+if ~ismember(benchmark,{'all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing'})
+	disp('runme warning: benchmark not supported, defaulting to test ''nightly''')
+	benchmark='nighlty';
+end
+% }}}
+%GET procedure {{{1
+procedure=getfieldvalue(options,'procedure','check');
+if ~ismember(procedure,{'check','update'})
+	disp('runme warning: procedure not supported, defaulting to test ''check''')
+	procedure='check';
+end
+% }}}
+%GET output {{{1
+output=getfieldvalue(options,'output','none');
+if ~ismember(output,{'nightly','daily','none'})
+	disp('runme warning: output not supported, defaulting to test ''none''')
+	output='none';
+end
+% }}}
+%GET RANK and NUMPROCS for mutlithreaded runs  {{{1
+rank=getfieldvalue(options,'rank',1);
+numprocs=getfieldvalue(options,'numprocs',1);
+if (numprocs<rank), numprocs=1; end
+% }}}
+%GET ids  {{{1
+list=dir;%use dir, as it seems to act OS independent
+list_ids=[];
+for i=1:numel(list),
+	if ( strncmp(list(i).name,'test',4) &...                         %File name must start with 'test'
+			strncmp(fliplr(list(i).name),fliplr('.m'),2)&...           %File name must end by '.m'
+			~strcmp(list(i).name,'test.m'))                            %File name must be different than 'test.m'
+		list_ids(end+1)=eval(list(i).name(5:end-2));                  %Keep test id only (skip 'test' and '.m')
+	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 exculde {{{1
+exclude_ids=getfieldvalue(options,'exclude',[]);
+exclude_ids=[exclude_ids];
+pos=find(ismember(test_ids,exclude_ids));
+test_ids(pos)=[];
+% }}}
+%Process Ids according to benchmarks{{{1
+if strcmpi(benchmark,'nightly'),
+	test_ids=intersect(test_ids,[1:999]);
+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,'validation'),
+	test_ids=intersect(test_ids,[1001:1999]);
+elseif strcmpi(benchmark,'tranforcing'),
+	test_ids=intersect(test_ids,[1501:1502]);
+end
+% }}}
+
+%Loop over tests and launch sequence
+root=pwd;
+for id=test_ids,
+	try,
+
+		%Execute test
+		eval(['cd ' root ]);
+		id_string=IdToName(id);
+		eval(['test' num2str(id)]);
+
+		%UPDATE ARCHIVE?
+		archive_name=['Archive' num2str(id) ];
+		if strcmpi(procedure,'update'),
+
+			if ~strcmp(oshostname(),'larsen');
+				error(['Nighlty run archives must be saved on "larsen" (hostname is "' oshostname() '")']);
+			end
+			for k=1:length(field_names),
+				field=field_values{k};
+				eval([ archive_name '_field' num2str(k) ' =  field ;']);
+			end
+			eval(['save ../Archives/' archive_name ' ' archive_name '_field*']);
+			disp(sprintf(['File ./../Archives/' archive_name ' saved\n']));
+
+			%ELSE: CHECK TEST
+		else,
+
+			%load archive
+			load(['../Archives/' archive_name ]);
+
+			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
+					eval(['archive=' 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));
+					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:
+					directory=strsplit(pwd,'/');
+					message=getReport(me2);
+					if strcmpi(output,'nightly')
+						fid=fopen([ISSM_TIER '/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));
+					elseif strcmpi(output,'daily');
+						fid=fopen([ISSM_TIER '/dailylog/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
+						rethrow(me2);
+					end
+				end
+			end
+		end
+
+	catch me,
+
+		%something went wrong, print failure message:
+		directory=strsplit(pwd,'/');
+		message=getReport(me);
+		if strcmpi(output,'nightly')
+			fid=fopen([ISSM_TIER '/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'));
+		elseif strcmpi(output,'daily');
+			fid=fopen([ISSM_TIER '/dailylog/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
+			rethrow(me);
+		end
+	end
+end
+
+%output md if requested
+if nargout==1
+	varargout{1}=md;
+end
Index: /issm/trunk-jpl-damage/test/NightlyRun/test101.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test101.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test101.m	(revision 11330)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test102.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test102.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test102.m	(revision 11330)
@@ -0,0 +1,22 @@
+md=triangle(model,'../Exp/Square.exp',50000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.diagnostic.requested_outputs=StressTensorEnum;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure',...
+	'StressTensorxx','StressTensoryy','StressTensorxy'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.StressTensorxx),...
+	(md.results.DiagnosticSolution.StressTensoryy),...
+	(md.results.DiagnosticSolution.StressTensorxy),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test103.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test103.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test103.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test104.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test104.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test104.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test105.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test105.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test105.m	(revision 11330)
@@ -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,'pattyn','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test106.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test106.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test106.m	(revision 11330)
@@ -0,0 +1,27 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.diagnostic.requested_outputs=StressTensorEnum;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure',...
+	'StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.StressTensorxx),...
+	(md.results.DiagnosticSolution.StressTensoryy),...
+	(md.results.DiagnosticSolution.StressTensorzz),...
+	(md.results.DiagnosticSolution.StressTensorxy),...
+	(md.results.DiagnosticSolution.StressTensorxz),...
+	(md.results.DiagnosticSolution.StressTensoryz),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test107.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test107.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test107.m	(revision 11330)
@@ -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.cluster=none;
+md=setflowequation(md,'stokes','all');
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test108.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test108.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test108.m	(revision 11330)
@@ -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,'stokes','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-08,1e-08,1e-07,1e-08,1e-08};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test109.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test109.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test109.m	(revision 11330)
@@ -0,0 +1,13 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test110.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test110.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test110.m	(revision 11330)
@@ -0,0 +1,13 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1101.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1101.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1101.m	(revision 11330)
@@ -0,0 +1,136 @@
+%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 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,'pattyn','all');
+
+	%Create dirichlet on the bed only
+	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+	pos=find(md.mesh.vertexonbed);
+	md.diagnostic.spcvx(pos)=0;
+	md.diagnostic.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.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
+
+	%Compute the diagnostic
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,DiagnosticSolutionEnum);
+
+	%Plot the results and save them
+	vx=(md.results.DiagnosticSolution.Vx);
+	vy=(md.results.DiagnosticSolution.Vy);
+	vz=(md.results.DiagnosticSolution.Vz);
+	results{i}=md.results.DiagnosticSolution;
+	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(['ismipapattynvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipapattynvx' 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(['ismipapattynvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipapattynvy' 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(['ismipapattynvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipapattynvz' 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(['ismipapattynvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipapattynvxsec' 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('ismipapattynminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipapattynminvx.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('ismipapattynmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipapattynmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA ']);
+end
+%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 i=1:6,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1102.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1102.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1102.m	(revision 11330)
@@ -0,0 +1,146 @@
+%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 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,'stokes','all');
+
+	%Create dirichlet on the bed only
+	pos=find(md.mesh.vertexonbed);
+	md.diagnostic.spcvx(pos)=0;
+	md.diagnostic.spcvy(pos)=0;
+	md.diagnostic.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.vertexonbed);
+	%posx2=find(md.mesh.x==max(md.mesh.x) &  md.mesh.y~=0 & md.mesh.y~=max(md.mesh.y) & ~md.mesh.vertexonbed);
+
+	%posy=find(md.mesh.y==0 & md.mesh.x~=0 & md.mesh.x~=max(md.mesh.x) & ~md.mesh.vertexonbed); %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.vertexonbed);
+
+	%md.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
+
+	%Compute the diagnostic
+	md.diagnostic.abstol=NaN;
+	md.diagnostic.reltol=NaN;
+	md.diagnostic.restol=1;
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,DiagnosticSolutionEnum);
+
+	%Plot the results and save them
+	vx=(md.results.DiagnosticSolution.Vx);
+	vy=(md.results.DiagnosticSolution.Vy);
+	vz=(md.results.DiagnosticSolution.Vz);
+	pressure=(md.results.DiagnosticSolution.Pressure);
+	results{i}=md.results.DiagnosticSolution;
+	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(['ismipastokesvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipastokesvx' 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(['ismipastokesvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipastokesvy' 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(['ismipastokesvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipastokesvz' 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(['ismipastokesvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipastokesvxsec' 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('ismipastokesminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipastokesminvx.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('ismipastokesmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipastokesmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA ']);
+end
+%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 i=1:6,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1103.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1103.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1103.m	(revision 11330)
@@ -0,0 +1,127 @@
+%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={};
+
+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,'pattyn','all');
+
+	%Create dirichlet on the bed only
+	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mesh.vertexonbed);
+	md.diagnostic.spcvx(pos)=0;
+	md.diagnostic.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.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
+
+	%Compute the diagnostic
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,DiagnosticSolutionEnum);
+
+	%Plot the results and save them
+	vx=(md.results.DiagnosticSolution.Vx);
+	vy=(md.results.DiagnosticSolution.Vy);
+	vz=(md.results.DiagnosticSolution.Vz);
+	results{i}=md.results.DiagnosticSolution;
+	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(['ismipbpattynvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipbpattynvx' 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(['ismipbpattynvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipbpattynvz' 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(['ismipbpattynvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipbpattynvxsec' 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('ismipbpattynminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipbpattynminvx.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('ismipbpattynmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipbpattynmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB ']);
+end
+%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 i=1:6,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1104.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1104.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1104.m	(revision 11330)
@@ -0,0 +1,81 @@
+%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 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,'pattyn','all');
+
+	%Create dirichlet on the bed only
+	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+	pos=find(md.mesh.vertexonbed);
+	md.diagnostic.spcvx(pos)=0;
+	md.diagnostic.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.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
+
+	%Compute the diagnostic
+	md.diagnostic.abstol=NaN;
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,DiagnosticSolutionEnum);
+	pos=find(md.mesh.x==0 | md.mesh.y==0 | md.mesh.x==max(md.mesh.x) | md.mesh.y==max(md.mesh.y));
+	md.diagnostic.spcvx(pos)=md.results.DiagnosticSolution.Vx(pos);
+	md.diagnostic.spcvy(pos)=md.results.DiagnosticSolution.Vy(pos);
+	md.diagnostic.vertex_pairing=[];
+	md=setflowequation(md,'stokes','all');
+	md=solve(md,DiagnosticSolutionEnum);
+
+	%Plot the results and save them
+	vx=(md.results.DiagnosticSolution.Vx);
+	vy=(md.results.DiagnosticSolution.Vy);
+	vz=(md.results.DiagnosticSolution.Vz);
+	results{i}=md.results.DiagnosticSolution;
+
+	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
+end
+
+%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-08,1e-08,...
+	1e-08,1e-07,1e-07,...
+};
+field_values={};
+for i=1:6,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1105.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1105.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1105.m	(revision 11330)
@@ -0,0 +1,159 @@
+%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 i=1:length(L_list),
+	L=L_list{i};  %in m (3 times the desired lenght 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,'pattyn','all'); 
+
+	%Create MPCs to have periodic boundary conditions
+	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+	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.diagnostic.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.vertexonbed);
+	md.diagnostic.spcvx(pos)=0;
+	md.diagnostic.spcvy(pos)=0;
+	if(L==5000),
+		md.diagnostic.spcvx(pos)=15.66;
+		md.diagnostic.spcvy(pos)=-0.1967;
+	elseif(L==10000),
+		md.diagnostic.spcvx(pos)=16.04;
+		md.diagnostic.spcvy(pos)=-0.1977;
+	elseif(L==20000),
+		md.diagnostic.spcvx(pos)=16.53;
+		md.diagnostic.spcvy(pos)=-1.27;
+	elseif(L==40000),
+		md.diagnostic.spcvx(pos)=17.23;
+		md.diagnostic.spcvy(pos)=-3.17;
+	elseif(L==80000),
+		md.diagnostic.spcvx(pos)=16.68;
+		md.diagnostic.spcvy(pos)=-2.69;
+	elseif(L==160000),
+		md.diagnostic.spcvx(pos)=16.03;
+		md.diagnostic.spcvy(pos)=-1.27;
+	end
+	
+	%Spc the bed at zero for vz
+	pos=find(md.mesh.vertexonbed);
+	md.diagnostic.spcvz(pos)=0;
+
+	%Compute the diagnostic
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,DiagnosticSolutionEnum);
+
+	%Plot the results and save them
+	vx=(md.results.DiagnosticSolution.Vx);
+	vy=(md.results.DiagnosticSolution.Vy);
+	vz=(md.results.DiagnosticSolution.Vz);
+	results{i}=md.results.DiagnosticSolution;
+	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(['ismipcpattynvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipcpattynvx' 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(['ismipcpattynvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipcpattynvy' 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(['ismipcpattynvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipcpattynvz' 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(['ismipcpattynvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipcpattynvxsec' 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('ismipcpattynminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipcpattynminvx.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('ismipcpattynmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipcpattynmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC ']);
+end
+%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-08,...
+	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 i=1:6,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1106.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1106.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1106.m	(revision 11330)
@@ -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};
+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.diagnostic.spcvx(pos)=0;
+	md.diagnostic.spcvy(pos)=0;
+	if(L==5000),
+		md.diagnostic.spcvx(pos)=15.66;
+		md.diagnostic.spcvy(pos)=-0.1967;
+	elseif(L==10000),
+		md.diagnostic.spcvx(pos)=16.04;
+		md.diagnostic.spcvy(pos)=-0.1977;
+	elseif(L==20000),
+		md.diagnostic.spcvx(pos)=16.53;
+		md.diagnostic.spcvy(pos)=-1.27;
+	elseif(L==40000),
+		md.diagnostic.spcvx(pos)=17.23;
+		md.diagnostic.spcvy(pos)=-3.17;
+	elseif(L==80000),
+		md.diagnostic.spcvx(pos)=16.68;
+		md.diagnostic.spcvy(pos)=-2.69;
+	elseif(L==160000),
+		md.diagnostic.spcvx(pos)=16.03;
+		md.diagnostic.spcvy(pos)=-1.27;
+	end
+
+	md=setflowequation(md,'stokes','all'); 
+
+	%Compute the diagnostic
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,DiagnosticSolutionEnum);
+
+	%Plot the results and save them
+	vx=(md.results.DiagnosticSolution.Vx);
+	vy=(md.results.DiagnosticSolution.Vy);
+	vz=(md.results.DiagnosticSolution.Vz);
+	results{i}=md.results.DiagnosticSolution;
+
+	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
+end
+
+%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-12,1e-12,...
+	1e-12,1e-12,1e-12,...
+	1e-12,1e-12,1e-12,...
+	1e-12,1e-11,1e-12,...
+};
+field_values={};
+for i=1:6,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1107.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1107.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1107.m	(revision 11330)
@@ -0,0 +1,148 @@
+%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 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,'pattyn','all');
+
+	%We need one grd on dirichlet: the 4 corners are set to zero
+	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+	%Create MPCs to have periodic boundary conditions
+	posx=find(md.mesh.x==0 & ~(md.mesh.y==0 & md.mesh.vertexonbed) & ~(md.mesh.y==L & md.mesh.vertexonbed));
+	posx2=find(md.mesh.x==max(md.mesh.x) & ~(md.mesh.y==0 & md.mesh.vertexonbed) & ~(md.mesh.y==L & md.mesh.vertexonbed));
+
+	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.diagnostic.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.vertexonbed);
+	md.diagnostic.spcvy(:)=0;
+	md.diagnostic.spcvx(pos)=0;
+	if(L==5000),
+		md.diagnostic.spcvx(pos)=16.0912;
+	elseif(L==10000),
+		md.diagnostic.spcvx(pos)=16.52;
+	elseif(L==20000),
+		md.diagnostic.spcvx(pos)=17.77;
+	elseif(L==40000),
+		md.diagnostic.spcvx(pos)=19.88;
+	elseif(L==80000),
+		md.diagnostic.spcvx(pos)=18.65;
+	elseif(L==160000),
+		md.diagnostic.spcvx(pos)=16.91;
+	end
+	
+	%Spc the bed at zero for vz
+	pos=find(md.mesh.vertexonbed);
+	md.diagnostic.spcvz(pos)=0;
+
+	%Compute the diagnostic
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,DiagnosticSolutionEnum);
+
+	%Plot the results and save them
+	vx=(md.results.DiagnosticSolution.Vx);
+	vy=(md.results.DiagnosticSolution.Vy);
+	vz=(md.results.DiagnosticSolution.Vz);
+	results{i}=md.results.DiagnosticSolution;
+	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(['ismipdpattynvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipdpattynvx' 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(['ismipdpattynvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipdpattynvz' 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(['ismipdpattynvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipdpattynvxsec' 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('ismipdpattynminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipdpattynminvx.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('ismipdpattynmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipdpattynmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD ']);
+end
+%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-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-07,...
+};
+field_values={};
+for i=1:6,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1108.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1108.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1108.m	(revision 11330)
@@ -0,0 +1,89 @@
+%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 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,'pattyn','all');
+
+	%We need one grd on dirichlet: the 4 corners are set to zero
+	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	
+	pos=find(md.mesh.vertexonbed & (md.mesh.x==0 | md.mesh.x==max(md.mesh.x)) & (md.mesh.y==0 | md.mesh.y==max(md.mesh.y)));
+	md.diagnostic.spcvx(pos)=0;
+	md.diagnostic.spcvy(pos)=0;
+	md.diagnostic.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.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
+
+	%Compute the diagnostic
+	md.cluster=generic('name',oshostname(),'np',8);
+	md.verbose=verbose('convergence',true);
+	md=solve(md,DiagnosticSolutionEnum);
+	md.diagnostic.reltol=NaN;
+	md.diagnostic.abstol=NaN;
+	md.diagnostic.vertex_pairing=[];
+	%We need one grd on dirichlet: the 4 corners are set to zero
+	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	pos=find(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.diagnostic.spcvx(pos)=md.results.DiagnosticSolution.Vx(pos);
+	md.diagnostic.spcvy(pos)=md.results.DiagnosticSolution.Vy(pos);
+	md=setflowequation(md,'stokes','all');
+	md=solve(md,DiagnosticSolutionEnum);
+
+	%Plot the results and save them
+	vx=(md.results.DiagnosticSolution.Vx);
+	vy=(md.results.DiagnosticSolution.Vy);
+	vz=(md.results.DiagnosticSolution.Vz);
+	results{i}=md.results.DiagnosticSolution;
+
+	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
+end
+
+%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-08,...
+	1e-08,1e-08,1e-08,...
+	1e-08,1e-07,1e-07,...
+	1e-07,1e-06,1e-07,...
+};
+field_values={};
+for i=1:6,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1109.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1109.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1109.m	(revision 11330)
@@ -0,0 +1,109 @@
+%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,'pattyn','all');
+	elseif i==2 | i==4,
+		md=setflowequation(md,'stokes','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.diagnostic.vertex_pairing=[posx,posx2];
+
+	%Create spcs on the bed 
+	pos=find(md.mesh.vertexonbed);
+	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvx(pos)=0;
+	md.diagnostic.spcvy(pos)=0;
+	md.diagnostic.spcvz(pos)=0;
+
+	%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.diagnostic.spcvx(pos)=NaN;
+		md.diagnostic.spcvy(pos)=NaN;
+		md.diagnostic.spcvz(pos)=NaN;
+	end
+
+	%Compute the diagnostic
+	md.cluster=generic('name',oshostname(),'np',8);
+	md=solve(md,DiagnosticSolutionEnum);
+
+	vx=(md.results.DiagnosticSolution.Vx);
+	vy=(md.results.DiagnosticSolution.Vy);
+	vz=(md.results.DiagnosticSolution.Vz);
+	results{i}=md.results.DiagnosticSolution;
+
+	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('ismipepattynvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipepattynvxfrozen.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('ismipestokesvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipestokesvxfrozen.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('ismipepattynvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipepattynvxsliding.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('ismipestokesvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipestokesvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestE ']);
+		end
+	end
+end
+%Fields and tolerances to track changes
+field_names     ={ ...
+	'VxPattynSliding','VyPattynSliding','VzPattynSliding',...
+	'VxStokesSliding','VyStokesSliding','VzStokesSliding',...
+	'VxPattynFrozen','VyPattynFrozen','VzPattynFrozen',...
+	'VxStokesFrozen','VyStokesFrozen','VzStokesFrozen'
+};
+field_tolerances={...
+	1e-06,1e-05,1e-05,...
+	1e-06,1e-06,1e-06,...
+	1e-06,1e-05,1e-04,...
+	1e-06,1e-06,1e-06,...
+};
+field_values={};
+for i=1:4,
+	result=results{i};
+	field_values={field_values{:},...
+		(result.Vx),...
+		(result.Vy),...
+		(result.Vz),...
+		};
+end
Index: /issm/trunk-jpl-damage/test/NightlyRun/test111.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test111.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test111.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md.prognostic.stabilization=3;
+md.prognostic.spcthickness=md.geometry.thickness;
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1110.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1110.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1110.m	(revision 11330)
@@ -0,0 +1,128 @@
+%This test is a test from the ISMP-HOM Intercomparison project
+%TestF 
+printingflag=false;
+
+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,'pattyn','all');
+	else
+		md=setflowequation(md,'stokes','all');
+	end
+
+	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	if (i==1 | i==3),
+		%Create dirichlet on the bed if no slip
+		pos=find(md.mesh.vertexonbed);
+		md.diagnostic.spcvx(pos)=0;
+		md.diagnostic.spcvy(pos)=0;
+		md.diagnostic.spcvz(pos)=0;
+	else
+		pos=find(md.mesh.vertexonbed & (md.mesh.x==0 | md.mesh.x==max(md.mesh.x)) & (md.mesh.y==0 | md.mesh.y==max(md.mesh.y)));
+		md.diagnostic.spcvx(pos)=100; %because we need a dirichlet somewhere
+		md.diagnostic.spcvy(pos)=0;
+		md.diagnostic.spcvz(pos)=0;
+	end
+	pos=find(~md.mesh.vertexonbed);
+	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.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
+	md.prognostic.vertex_pairing=[posx,posx2;posy,posy2];
+
+	md.timestepping.time_step=3;
+	md.timestepping.final_time=300;
+	md.settings.output_frequency=50;
+	md.prognostic.stabilization=1;
+	md.diagnostic.maxiter=1;
+
+	%Compute the diagnostic
+	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('ismipfpattynvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfpattynvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF ']);
+		elseif i==2,
+			printmodel('ismipfpattynvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfpattynvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF ']);
+		elseif i==3,
+			printmodel('ismipfstokesvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfstokesvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF ']);
+		elseif i==4,
+			printmodel('ismipfstokesvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfstokesvxsliding.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('ismipfpattyndeltasurfacefrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfpattyndeltasurfacefrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF ']);
+		elseif i==2,
+			printmodel('ismipfpattyndeltasurfacesliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfpattyndeltasurfacesliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF ']);
+		elseif i==3,
+			printmodel('ismipfstokesdeltasurfacefrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfstokesdeltasurfacefrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF ']);
+		elseif i==4,
+			printmodel('ismipfstokesdeltasurfacesliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfstokesdeltasurfacesliding.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-09,1e-09,1e-08,1e-09,...
+	1e-08,1e-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/trunk-jpl-damage/test/NightlyRun/test112.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test112.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test112.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.prognostic.stabilization=3;
+md.prognostic.spcthickness=md.geometry.thickness;
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test113.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test113.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test113.m	(revision 11330)
@@ -0,0 +1,14 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md=extrude(md,5,3);
+md.cluster=none;
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test114.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test114.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test114.m	(revision 11330)
@@ -0,0 +1,14 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md=extrude(md,5,3);
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test115.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test115.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test115.m	(revision 11330)
@@ -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,'macayeal','all');
+md.timestepping.time_step=0;
+md.cluster=none;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test116.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test116.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test116.m	(revision 11330)
@@ -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,'macayeal','all');
+md.timestepping.time_step=0;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test117.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test117.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test117.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution(1).Temperature),...
+	(md.results.ThermalSolution(1).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test118.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test118.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test118.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution(1).Temperature),...
+	(md.results.ThermalSolution(1).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test119.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test119.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test119.m	(revision 11330)
@@ -0,0 +1,39 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+
+
+
+
+
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test120.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test120.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test120.m	(revision 11330)
@@ -0,0 +1,36 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1201.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1201.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1201.m	(revision 11330)
@@ -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 prognostic 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,'macayeal','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.prognostic.stabilization=0;
+	else
+		md.prognostic.stabilization=stabilization;
+	end
+
+	%spc thickness
+	pos=find(md.mesh.y>199999.9);
+	times=0:1:500;
+	md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices+1,length(times));
+	md.prognostic.spcthickness(end,:)=times;
+	md.prognostic.spcthickness(pos,:)=repmat(500+100*sin(2*pi*times/200),length(pos),1);
+	if stabilization==3,
+		pos=find(isnan(md.prognostic.spcthickness)); md.prognostic.spcthickness(pos)=500; %No NaN for DG
+	end
+
+	%solve
+	md.transient.isdiagnostic=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     ={ ...
+	'ThicknessArtDigg','ThicknessNoArtDiff','ThicknessDG' ...
+};
+field_tolerances={...
+	1e-13, 1e-13, 1e-13...
+};
+field_values={
+	results{1}, ...
+	results{2}, ...
+	results{3}, ...
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1202.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1202.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1202.m	(revision 11330)
@@ -0,0 +1,41 @@
+%Test on the diagnostic model and the prognostic 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,'macayeal','all'); %MacAyeal's model and 2d
+
+%Compute solution for MacAyeal's model 
+md.cluster=generic('name',oshostname(),'np',8);
+md=solve(md,DiagnosticSolutionEnum);
+
+%plot results
+vx=(md.results.DiagnosticSolution.Vx);
+vy=(md.results.DiagnosticSolution.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/trunk-jpl-damage/test/NightlyRun/test1203.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1203.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1203.m	(revision 11330)
@@ -0,0 +1,44 @@
+%Test on the diagnostic model and the prognostic 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,'macayeal','all'); %MacAyeal'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.diagnostic.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 MacAyeal's model 
+md.cluster=generic('name',oshostname(),'np',8);
+md=solve(md,DiagnosticSolutionEnum);
+
+vx=(md.results.DiagnosticSolution.Vx);
+vy=(md.results.DiagnosticSolution.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/trunk-jpl-damage/test/NightlyRun/test1204.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1204.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1204.m	(revision 11330)
@@ -0,0 +1,56 @@
+%Test on the diagnostic model and the prognostic 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,'macayeal','all'); %MacAyeal'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.diagnostic.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 MacAyeal's model 
+md.cluster=generic('name',oshostname(),'np',8);
+md=solve(md,DiagnosticSolutionEnum);
+
+%plot results
+md.initialization.vx=(md.results.DiagnosticSolution.Vx);
+md.initialization.vy=(md.results.DiagnosticSolution.Vy);
+
+md.timestepping.time_step=1;
+md.timestepping.final_time=5000;
+md.prognostic.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/trunk-jpl-damage/test/NightlyRun/test1205.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1205.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1205.m	(revision 11330)
@@ -0,0 +1,99 @@
+%The aim of this program is to compare a model with an analytical solution given in MacAyeal 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,'hutter','all');
+
+%Spc the nodes on the bed
+pos=find(md.mesh.vertexonbed);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.spcvz(pos)=0;
+
+%Now we can solve the problem 
+md.cluster=generic('name',oshostname(),'np',8);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Calculate the depth averaged velocity field (2d):
+vx=(md.results.DiagnosticSolution.Vx);
+vy=(md.results.DiagnosticSolution.Vy);
+vel=zeros(md.mesh.numberofvertices2d,1);
+
+node_vel=0;
+for i=1:md.mesh.numberofvertices2d
+	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;
+	node_vel=0;
+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('hutterstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+	system(['mv hutterstatic.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/trunk-jpl-damage/test/NightlyRun/test1206.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1206.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1206.m	(revision 11330)
@@ -0,0 +1,98 @@
+%The aim of this program is to compare a model with an analytical solution given in MacAyeal 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,'pattyn','all');
+
+%Spc the nodes on the bed
+pos=find(md.mesh.vertexonbed);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.spcvz(pos)=0;
+
+%Now we can solve the problem 
+md.cluster=generic('name',oshostname(),'np',8);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Calculate the depth averaged velocity field (2d):
+vx=(md.results.DiagnosticSolution.Vx);
+vy=(md.results.DiagnosticSolution.Vy);
+vel=zeros(md.mesh.numberofvertices2d,1);
+
+node_vel=0;
+for i=1:md.mesh.numberofvertices2d
+	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;
+	node_vel=0;
+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('pattynstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+	system(['mv pattynstatic.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/trunk-jpl-damage/test/NightlyRun/test1207.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1207.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1207.m	(revision 11330)
@@ -0,0 +1,98 @@
+%The aim of this program is to compare a model with an analytical solution given in MacAyeal 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,'stokes','all');
+
+%Spc the nodes on the bed
+pos=find(md.mesh.vertexonbed);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.spcvz(pos)=0;
+
+%Now we can solve the problem 
+md.cluster=generic('name',oshostname(),'np',8);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Calculate the depth averaged velocity field (2d):
+vx=(md.results.DiagnosticSolution.Vx);
+vy=(md.results.DiagnosticSolution.Vy);
+vel=zeros(md.mesh.numberofvertices2d,1);
+
+node_vel=0;
+for i=1:md.mesh.numberofvertices2d
+	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;
+	node_vel=0;
+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('stokesstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+	system(['mv stokesstatic.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/trunk-jpl-damage/test/NightlyRun/test1208.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1208.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1208.m	(revision 11330)
@@ -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,'hutter','all');
+
+%Spc the nodes on the bed
+pos=find(md.mesh.vertexonbed);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.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.prognostic.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','Bed','Surface','Temperature','BasalforcingsMeltingRate'};
+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(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).Bed),...
+	(md.results.TransientSolution(end).Surface),...
+	(md.results.TransientSolution(end).Temperature),...
+	(md.results.TransientSolution(end).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test121.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test121.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test121.m	(revision 11330)
@@ -0,0 +1,45 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test122.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test122.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test122.m	(revision 11330)
@@ -0,0 +1,49 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names={...
+	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test123.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test123.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test123.m	(revision 11330)
@@ -0,0 +1,14 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,SurfaceSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test124.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test124.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test124.m	(revision 11330)
@@ -0,0 +1,14 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SurfaceSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test125.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test125.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test125.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,SurfaceSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test126.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test126.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test126.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SurfaceSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test127.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test127.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test127.m	(revision 11330)
@@ -0,0 +1,14 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,BedSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test128.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test128.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test128.m	(revision 11330)
@@ -0,0 +1,14 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BedSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test129.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test129.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test129.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,BedSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test130.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test130.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test130.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BedSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1301.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1301.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1301.m	(revision 11330)
@@ -0,0 +1,47 @@
+% 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,'Pattyn','all');
+
+%Some conditions specific to melting test
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+md.initialization.temperature=273.15*ones(md.mesh.numberofvertices,1);
+pos=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.BasalforcingsMeltingRate;
+relative=abs((comp_melting-melting)./melting)*100;
+relative(find(comp_melting==melting))=0;
+plotmodel(md,'data',comp_melting,'title','Modeled melting','data',melting,'title','Analytical melting',...
+	'data',comp_melting-melting,'title','Absolute error','data',relative,'title','Relative error [%]',...
+	'layer#all',1,'caxis#2',[1.02964 1.02966]*10^-4,'FontSize#all',20,'figposition','mathieu')
+if printingflag, 
+	set(gcf,'Color','w')
+	printmodel('thermalmelting','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+	system(['mv thermalmelting.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Thermal ']);
+end
+
+
+%Fields and tolerances to track changes
+field_names     ={'BasalMelting'};
+field_tolerances={1e-08};
+field_values    ={comp_melting};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1302.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1302.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1302.m	(revision 11330)
@@ -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,'Pattyn','all'); 
+
+%Thermal boundary conditions
+pos1=find(md.mesh.elementonbed);     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/trunk-jpl-damage/test/NightlyRun/test1303.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1303.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1303.m	(revision 11330)
@@ -0,0 +1,43 @@
+% 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,'Pattyn','all');
+pos1=find(md.mesh.elementonbed);     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/trunk-jpl-damage/test/NightlyRun/test1304.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1304.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1304.m	(revision 11330)
@@ -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,'Pattyn','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/trunk-jpl-damage/test/NightlyRun/test131.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test131.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test131.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test132.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test132.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test132.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test133.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test133.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test133.m	(revision 11330)
@@ -0,0 +1,17 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,5,1);
+%Add boundary conditions on thickness on the border
+pos=find(md.mesh.vertexonboundary);
+md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test134.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test134.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test134.m	(revision 11330)
@@ -0,0 +1,17 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,5,1);
+%Add boundary conditions on thickness on the border
+pos=find(md.mesh.vertexonboundary);
+md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test135.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test135.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test135.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test136.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test136.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test136.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test137.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test137.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test137.m	(revision 11330)
@@ -0,0 +1,25 @@
+
+%Simple mesh
+md=bamg(model,'domain','../Exp/Square.exp','hmax',100000);
+x1=md.mesh.x;
+y1=md.mesh.y;
+
+%hVertices
+md=bamg(model,'domain','../Exp/Square.exp','hmax',300000,'hvertices',[10000 100000 400000 100000]');
+x2=md.mesh.x;
+y2=md.mesh.y;
+
+%big mesh
+t0=clock;
+md=bamg(model,'domain','../Exp/Square.exp','hmax',3000);
+nbelements=md.mesh.numberofelements;
+elapsedtime=etime(clock,t0);
+
+%Fields and tolerances to track changes
+field_names     ={'x1' 'y1' 'x2' 'y2' 'nbelements' 'elapsed time'};
+field_tolerances={1e-13 1e-13 1e-13 1e-13 1e-13 0.5};
+field_values={...
+	x1, y1,...
+	x2, y2,...
+	nbelements,elapsedtime...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test139.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test139.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test139.m	(revision 11330)
@@ -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,1);
+md=setflowequation(md,'macayeal','all');
+md.timestepping.time_step=0;
+md.cluster=none;
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md=solve(md,EnthalpySolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Enthalpy','Waterfraction','Temperature'};
+field_tolerances={1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.EnthalpySolution.Enthalpy),...
+	(md.results.EnthalpySolution.Waterfraction),...
+	(md.results.EnthalpySolution.Temperature),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test140.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test140.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test140.m	(revision 11330)
@@ -0,0 +1,19 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.timestepping.time_step=0;
+md.cluster=generic('name',oshostname(),'np',3);
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+%md=solve(md,ThermalSolutionEnum);
+md=solve(md,EnthalpySolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Enthalpy','Waterfraction','Temperature'};
+field_tolerances={1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.EnthalpySolution.Enthalpy),...
+	(md.results.EnthalpySolution.Waterfraction),...
+	(md.results.EnthalpySolution.Temperature),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1401.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1401.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1401.m	(revision 11330)
@@ -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/trunk-jpl-damage/test/NightlyRun/test1402.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1402.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1402.m	(revision 11330)
@@ -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/trunk-jpl-damage/test/NightlyRun/test141.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test141.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test141.m	(revision 11330)
@@ -0,0 +1,25 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.cluster=none;
+md=solve(md,EnthalpySolutionEnum);
+
+%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.EnthalpySolution(1).Enthalpy),...
+	(md.results.EnthalpySolution(1).Waterfraction),...
+	(md.results.EnthalpySolution(1).Temperature),...
+	(md.results.EnthalpySolution(2).Enthalpy),...
+	(md.results.EnthalpySolution(2).Waterfraction),...
+	(md.results.EnthalpySolution(2).Temperature),...
+	(md.results.EnthalpySolution(3).Enthalpy),...
+	(md.results.EnthalpySolution(3).Waterfraction),...
+	(md.results.EnthalpySolution(3).Temperature),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test142.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test142.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test142.m	(revision 11330)
@@ -0,0 +1,26 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+%md=solve(md,ThermalSolutionEnum);
+md=solve(md,EnthalpySolutionEnum);
+
+%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.EnthalpySolution(1).Enthalpy),...
+	(md.results.EnthalpySolution(1).Waterfraction),...
+	(md.results.EnthalpySolution(1).Temperature),...
+	(md.results.EnthalpySolution(2).Enthalpy),...
+	(md.results.EnthalpySolution(2).Waterfraction),...
+	(md.results.EnthalpySolution(2).Temperature),...
+	(md.results.EnthalpySolution(3).Enthalpy),...
+	(md.results.EnthalpySolution(3).Waterfraction),...
+	(md.results.EnthalpySolution(3).Temperature),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1501.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1501.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1501.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isthermal=0;
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=2000;
+
+%Solve for thinning rate -> -1 * surface mass balance
+smb= 2*ones(md.mesh.numberofvertices,1);   
+md.surfaceforcings.mass_balance= smb;
+md.basalforcings.melting_rate= smb;
+
+md=solve(md,PrognosticSolutionEnum);
+
+for i=1:10
+	 md=solve(md,PrognosticSolutionEnum);
+	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.PrognosticSolution.Thickness)-md.geometry.thickness);
+end
+
+%Set up transient
+smb = md.surfaceforcings.mass_balance;
+
+tooth= [ [ones(400,1)*(smb') - 10]' [ones(400,1)*(smb')]' ];
+smb=[ [ones(399,1)*(smb')]' smb  tooth tooth];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1:2000];
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4', ...
+	'Vx5','Vy5','Vel5','Pressure5','Bed5','Surface5','Thickness5','SurfaceforcingsMassBalance5'};
+field_tolerances={1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(400).Vx),...
+	(md.results.TransientSolution(400).Vy),...
+	(md.results.TransientSolution(400).Vel),...
+	(md.results.TransientSolution(400).Pressure),...
+	(md.results.TransientSolution(400).Bed),...
+	(md.results.TransientSolution(400).Surface),...
+	(md.results.TransientSolution(400).Thickness),...
+	(md.results.TransientSolution(400).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(800).Vx),...
+	(md.results.TransientSolution(800).Vy),...
+	(md.results.TransientSolution(800).Vel),...
+	(md.results.TransientSolution(800).Pressure),...
+	(md.results.TransientSolution(800).Bed),...
+	(md.results.TransientSolution(800).Surface),...
+	(md.results.TransientSolution(800).Thickness),...
+	(md.results.TransientSolution(800).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(1200).Vx),...
+	(md.results.TransientSolution(1200).Vy),...
+	(md.results.TransientSolution(1200).Vel),...
+	(md.results.TransientSolution(1200).Pressure),...
+	(md.results.TransientSolution(1200).Bed),...
+	(md.results.TransientSolution(1200).Surface),...
+	(md.results.TransientSolution(1200).Thickness),...
+	(md.results.TransientSolution(1200).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(1600).Vx),...
+	(md.results.TransientSolution(1600).Vy),...
+	(md.results.TransientSolution(1600).Vel),...
+	(md.results.TransientSolution(1600).Pressure),...
+	(md.results.TransientSolution(1600).Bed),...
+	(md.results.TransientSolution(1600).Surface),...
+	(md.results.TransientSolution(1600).Thickness),...
+	(md.results.TransientSolution(1600).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2000).Vx),...
+	(md.results.TransientSolution(2000).Vy),...
+	(md.results.TransientSolution(2000).Vel),...
+	(md.results.TransientSolution(2000).Pressure),...
+	(md.results.TransientSolution(2000).Bed),...
+	(md.results.TransientSolution(2000).Surface),...
+	(md.results.TransientSolution(2000).Thickness),...
+	(md.results.TransientSolution(2000).SurfaceforcingsMassBalance),...
+	};
+
+if printingflag,
+
+	starttime = 360;
+	endtime = 2000;
+	res = 40;
+	ts = [starttime:res:endtime];
+
+	index = md.mesh.elements;
+	x1=md.mesh.x(index(:,1)); x2=md.mesh.x(index(:,2)); x3=md.mesh.x(index(:,3));
+	y1=md.mesh.y(index(:,1)); y2=md.mesh.y(index(:,2)); y3=md.mesh.y(index(:,3));
+	areas=(0.5*((x2-x1).*(y3-y1)-(y2-y1).*(x3-x1)));
+
+	thickness = [];
+	volume = [];
+	massbal = [];
+	velocity = [];
+	for t=starttime:endtime
+		thickness = [thickness (md.results.TransientSolution(t).Thickness)];
+		volume = [volume 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/trunk-jpl-damage/test/NightlyRun/test1502.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1502.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1502.m	(revision 11330)
@@ -0,0 +1,213 @@
+printingflag = false;
+
+md=triangle(model,'../Exp/Square.exp',450000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md=extrude(md,3,1);
+md.cluster=generic('name',oshostname(),'np',2);
+md.transient.isthermal=0;
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=2000;
+
+%Solve for thinning rate -> -1 * surface mass balance
+smb= 2*ones(md.mesh.numberofvertices,1);   
+md.surfaceforcings.mass_balance= smb;
+md.basalforcings.melting_rate= smb;
+
+md=solve(md,PrognosticSolutionEnum);
+
+for i=1:10
+	 md=solve(md,PrognosticSolutionEnum);
+	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.PrognosticSolution.Thickness)-md.geometry.thickness);
+end
+
+%Set up transient
+smb = md.surfaceforcings.mass_balance;
+
+tooth= [ [ones(400,1)*(smb') - 10]' [ones(400,1)*(smb')]' ];
+smb=[ [ones(399,1)*(smb')]' smb  tooth tooth];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1:2000];
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4', ...
+	'Vx5','Vy5','Vz5','Vel5','Pressure5','Bed5','Surface5','Thickness5','SurfaceforcingsMassBalance5'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(400).Vx),...
+	(md.results.TransientSolution(400).Vy),...
+	(md.results.TransientSolution(400).Vz),...
+	(md.results.TransientSolution(400).Vel),...
+	(md.results.TransientSolution(400).Pressure),...
+	(md.results.TransientSolution(400).Bed),...
+	(md.results.TransientSolution(400).Surface),...
+	(md.results.TransientSolution(400).Thickness),...
+	(md.results.TransientSolution(400).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(800).Vx),...
+	(md.results.TransientSolution(800).Vy),...
+	(md.results.TransientSolution(800).Vz),...
+	(md.results.TransientSolution(800).Vel),...
+	(md.results.TransientSolution(800).Pressure),...
+	(md.results.TransientSolution(800).Bed),...
+	(md.results.TransientSolution(800).Surface),...
+	(md.results.TransientSolution(800).Thickness),...
+	(md.results.TransientSolution(800).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(1200).Vx),...
+	(md.results.TransientSolution(1200).Vy),...
+	(md.results.TransientSolution(1200).Vz),...
+	(md.results.TransientSolution(1200).Vel),...
+	(md.results.TransientSolution(1200).Pressure),...
+	(md.results.TransientSolution(1200).Bed),...
+	(md.results.TransientSolution(1200).Surface),...
+	(md.results.TransientSolution(1200).Thickness),...
+	(md.results.TransientSolution(1200).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(1600).Vx),...
+	(md.results.TransientSolution(1600).Vy),...
+	(md.results.TransientSolution(1600).Vz),...
+	(md.results.TransientSolution(1600).Vel),...
+	(md.results.TransientSolution(1600).Pressure),...
+	(md.results.TransientSolution(1600).Bed),...
+	(md.results.TransientSolution(1600).Surface),...
+	(md.results.TransientSolution(1600).Thickness),...
+	(md.results.TransientSolution(1600).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2000).Vx),...
+	(md.results.TransientSolution(2000).Vy),...
+	(md.results.TransientSolution(2000).Vz),...
+	(md.results.TransientSolution(2000).Vel),...
+	(md.results.TransientSolution(2000).Pressure),...
+	(md.results.TransientSolution(2000).Bed),...
+	(md.results.TransientSolution(2000).Surface),...
+	(md.results.TransientSolution(2000).Thickness),...
+	(md.results.TransientSolution(2000).SurfaceforcingsMassBalance),...
+	};
+
+if printingflag,
+
+	starttime = 360;
+	endtime = 2000;
+	res = 40;
+	ts = [starttime:res:endtime];
+
+	index = md.mesh.elements;
+	x1=md.mesh.x(index(:,1)); x2=md.mesh.x(index(:,2)); x3=md.mesh.x(index(:,3));
+	y1=md.mesh.y(index(:,1)); y2=md.mesh.y(index(:,2)); y3=md.mesh.y(index(:,3));
+	areas=(0.5*((x2-x1).*(y3-y1)-(y2-y1).*(x3-x1)));
+
+	thickness = [];
+	volume = [];
+	massbal = [];
+	velocity = [];
+	for t=starttime:endtime
+		thickness = [thickness (md.results.TransientSolution(t).Thickness)];
+		volume = [volume 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/trunk-jpl-damage/test/NightlyRun/test1601.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1601.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1601.m	(revision 11330)
@@ -0,0 +1,45 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.diagnostic.spcvx(find(md.mesh.y>0))=NaN;
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+
+md.cluster=generic('name',oshostname,'np',2);
+md=solve(md,DiagnosticSolutionEnum);
+vel0=md.results.DiagnosticSolution.Vel;
+
+theta=30*pi/180;
+x=md.mesh.x;
+y=md.mesh.y;
+md.mesh.x=cos(theta)*x-sin(theta)*y;
+md.mesh.y=sin(theta)*x+cos(theta)*y;
+
+md.diagnostic.referential(:,1:3)=repmat([cos(theta),sin(theta),0],md.mesh.numberofvertices,1);
+md.diagnostic.referential(:,4:6)=repmat([0,0,1],md.mesh.numberofvertices,1);
+md=solve(md,DiagnosticSolutionEnum);
+vel1=md.results.DiagnosticSolution.Vel;
+
+plotmodel(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
+disp(['Error between Cartesian and rotated CS: ' num2str(max(abs(vel0-vel1))/(max(abs(vel0))+eps)) ]);
+
+%Now, put CS back to normal except on the side where the spc are applied
+pos=find(x==0 | x==1000000);
+md.diagnostic.referential(:)=NaN;
+md.diagnostic.referential(pos,1:3)=repmat([cos(theta),sin(theta),0],size(pos,1),1);
+md.diagnostic.referential(pos,4:6)=repmat([0,0,1],size(pos,1),1);
+md=solve(md,DiagnosticSolutionEnum);
+vel2=md.results.DiagnosticSolution.Vel;
+
+plotmodel(md,'data',vel0,'data',vel2,'data',vel2-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
+disp(['Error between Cartesian and rotated CS: ' num2str(max(abs(vel0-vel2))/(max(abs(vel0))+eps)) ]);
+
+%Fields and tolerances to track changes
+field_names     ={'vel1','vel2'};
+field_tolerances={1e-11,1e-11};
+field_values={...
+	vel1, ...
+	vel2, ...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test1602.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test1602.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test1602.m	(revision 11330)
@@ -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,'pattyn','all');
+md.diagnostic.spcvx(find(md.mesh.y>0))=NaN;
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+
+md.cluster=generic('name',oshostname,'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+vel0=md.results.DiagnosticSolution.Vel;
+
+theta=30*pi/180;
+x=md.mesh.x;
+y=md.mesh.y;
+md.mesh.x=cos(theta)*x-sin(theta)*y;
+md.mesh.y=sin(theta)*x+cos(theta)*y;
+
+md.diagnostic.referential(:,1:3)=repmat([cos(theta),sin(theta),0],md.mesh.numberofvertices,1);
+md.diagnostic.referential(:,4:6)=repmat([0,0,1],md.mesh.numberofvertices,1);
+md=solve(md,DiagnosticSolutionEnum);
+vel1=md.results.DiagnosticSolution.Vel;
+
+plotmodel(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference','view#all',2)
+disp(['Error between Cartesian and rotated CS: ' num2str(max(abs(vel0-vel1))/(max(abs(vel0))+eps)) ]);
+
+%Fields and tolerances to track changes
+field_names     ={'vel1'};
+field_tolerances={1e-9};
+field_values={...
+	vel1, ...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test201.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test201.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test201.m	(revision 11330)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test202.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test202.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test202.m	(revision 11330)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test203.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test203.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test203.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test204.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test204.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test204.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test205.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test205.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test205.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'pattyn','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test206.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test206.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test206.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test207.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test207.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test207.m	(revision 11330)
@@ -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.cluster=none;
+md=setflowequation(md,'stokes','all');
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test208.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test208.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test208.m	(revision 11330)
@@ -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,'stokes','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-08,1e-08,1e-07,1e-08,1e-08};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test209.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test209.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test209.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'pattyn','../Exp/SquareHalfRight.exp','fill','macayeal','coupling','penalties');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-05,1e-05,1e-05,1e-05,1e-05};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test210.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test210.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test210.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'pattyn','../Exp/SquareHalfRight.exp','fill','macayeal','coupling','penalties');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-05,1e-05,1e-05,1e-05,1e-05};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test211.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test211.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test211.m	(revision 11330)
@@ -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,'macayeal','all');
+md.timestepping.time_step=0;
+md.cluster=none;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test212.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test212.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test212.m	(revision 11330)
@@ -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,'macayeal','all');
+md.timestepping.time_step=0;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test213.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test213.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test213.m	(revision 11330)
@@ -0,0 +1,19 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature1','MeltingRate1','Temperature2','BasalforcingsMeltingRate2','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution(1).Temperature),...
+	(md.results.ThermalSolution(1).BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution(2).Temperature),...
+	(md.results.ThermalSolution(2).BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution(3).Temperature),...
+	(md.results.ThermalSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test214.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test214.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test214.m	(revision 11330)
@@ -0,0 +1,19 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature1','BasalforcingsMeltingRate1','Temperature2','BasalforcingsMeltingRate2','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution(1).Temperature),...
+	(md.results.ThermalSolution(1).BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution(2).Temperature),...
+	(md.results.ThermalSolution(2).BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution(3).Temperature),...
+	(md.results.ThermalSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test215.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test215.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test215.m	(revision 11330)
@@ -0,0 +1,33 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test216.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test216.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test216.m	(revision 11330)
@@ -0,0 +1,33 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test217.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test217.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test217.m	(revision 11330)
@@ -0,0 +1,45 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test218.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test218.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test218.m	(revision 11330)
@@ -0,0 +1,48 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,...
+	1e-13,1e-13,1e-09,1e-13,1e-13,1e-11,1e-11,1e-11,1e-13,1e-8};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test219.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test219.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test219.m	(revision 11330)
@@ -0,0 +1,45 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-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-09,1e-09,1e-09,1e-09,1e-06};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test220.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test220.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test220.m	(revision 11330)
@@ -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,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
+	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test221.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test221.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test221.m	(revision 11330)
@@ -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,'stokes','all');
+md.diagnostic.reltol=NaN;
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-08,1e-08,1e-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-08,1e-08,1e-08,1e-08,1e-08,...
+						1e-08,1e-08,1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test222.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test222.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test222.m	(revision 11330)
@@ -0,0 +1,50 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'stokes','all');
+md.diagnostic.reltol=NaN;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names={...
+	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={...
+	1e-08,1e-08,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,...
+	1e-08,1e-08,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06,...
+	1e-07,1e-07,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test223.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test223.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test223.m	(revision 11330)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=none;
+md.verbose=verbose('all');
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyBbar),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test224.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test224.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test224.m	(revision 11330)
@@ -0,0 +1,33 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyBbar),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test225.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test225.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test225.m	(revision 11330)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyB),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test226.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test226.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test226.m	(revision 11330)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyB),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test227.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test227.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test227.m	(revision 11330)
@@ -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,'pattyn','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyB),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test228.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test228.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test228.m	(revision 11330)
@@ -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,'pattyn','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyB),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test229.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test229.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test229.m	(revision 11330)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'stokes','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyB),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test230.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test230.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test230.m	(revision 11330)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'stokes','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyB),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test232.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test232.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test232.m	(revision 11330)
@@ -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/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%rift settings
+md.rifts.riftstruct.fill=MelangeEnum();
+md.rifts.riftstruct.fraction=0;
+md.diagnostic.rift_penalty_lock=2;
+md.diagnostic.rift_penalty_threshold=0;
+md.rifts.riftstruct.fractionincrement=.1;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-11,1e-11,1e-11,1e-11};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test233.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test233.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test233.m	(revision 11330)
@@ -0,0 +1,69 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+
+%redo the parameter file for this special shelf. 
+%constant thickness, constrained (vy=0) flow into an icefront, 
+%from 0 m/yr at the grounding line.
+
+%tighten
+md.diagnostic.restol=10^-4;
+
+%needed later
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+
+di=md.materials.rho_ice/md.materials.rho_water;
+
+h=1000;
+md.geometry.thickness=h*ones(md.mesh.numberofvertices,1);
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+%Initial velocity and pressure
+md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+md.initialization.vy=zeros(md.mesh.numberofvertices,1);
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%Boundary conditions:
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+%constrain flanks to 0 normal velocity
+pos=find(md.mesh.x==xmin | md.mesh.x==xmax);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvz(pos)=NaN;
+
+%constrain grounding line to 0 velocity
+pos=find(md.mesh.y==ymin);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+
+%icefront
+nodeonicefront=zeros(md.mesh.numberofvertices,1);
+pos=find(md.mesh.y==ymax); nodeonicefront(pos)=1;
+pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2))); diagnostic.icefront=md.mesh.segments(pos,:);
+diagnostic.icefront=[diagnostic.icefront 1*md.mask.elementonfloatingice(diagnostic.icefront(:,end))];
+md.diagnostic.icefront=diagnostic.icefront;
+
+md=solve(md,DiagnosticSolutionEnum);
+
+%create analytical solution: strain rate is constant = ((rho_ice*g*h)/4B)^3 (Paterson, 4th Edition, page 292.
+%ey_c=(md.materials.rho_ice*md.constants.g*(1-di)*md.geometry.thickness./(4*md.materials.rheology_B)).^3;
+%vy_c=ey_c.*md.mesh.y*md.constants.yts;
+
+%Fields and tolerances to track changes
+field_names     ={'Vy'};
+field_tolerances={1e-13};
+field_values={(md.results.DiagnosticSolution.Vy)};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test234.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test234.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test234.m	(revision 11330)
@@ -0,0 +1,69 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%redo the parameter file for this special shelf. 
+%constant thickness, constrained (vy=0) flow into an icefront, 
+%from 0 m/yr at the grounding line.
+
+%tighten
+md.diagnostic.restol=10^-4;
+
+%needed later
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+
+di=md.materials.rho_ice/md.materials.rho_water;
+
+h=1000;
+md.geometry.thickness=h*ones(md.mesh.numberofvertices,1);
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+%Initial velocity and pressure
+md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+md.initialization.vy=zeros(md.mesh.numberofvertices,1);
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%Boundary conditions:
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+%constrain flanks to 0 normal velocity
+pos=find(md.mesh.x==xmin | md.mesh.x==xmax);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvz(pos)=NaN;
+
+%constrain grounding line to 0 velocity
+pos=find(md.mesh.y==ymin);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+
+%icefront
+nodeonicefront=zeros(md.mesh.numberofvertices,1);
+pos=find(md.mesh.y==ymax); nodeonicefront(pos)=1;
+pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2))); diagnostic.icefront=md.mesh.segments(pos,:);
+diagnostic.icefront=[diagnostic.icefront 1*md.mask.elementonfloatingice(diagnostic.icefront(:,end))];
+md.diagnostic.icefront=diagnostic.icefront;
+
+md=solve(md,DiagnosticSolutionEnum);
+
+%create analytical solution: strain rate is constant = ((rho_ice*g*h)/4B)^3 (Paterson, 4th Edition, page 292.
+%ey_c=(md.materials.rho_ice*md.constants.g*(1-di)*md.geometry.thickness./(4*md.materials.rheology_B)).^3;
+%vy_c=ey_c.*md.mesh.y*md.constants.yts;
+
+%Fields and tolerances to track changes
+field_names     ={'Vy'};
+field_tolerances={1e-13};
+field_values={(md.results.DiagnosticSolution.Vy)};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test235.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test235.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test235.m	(revision 11330)
@@ -0,0 +1,92 @@
+md=squaremesh(model,1000000,1000000,5,5);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+
+%redo the parameter file for this special shelf. 
+%constant thickness, constrained (vy=0) flow into an icefront, 
+%from 0 m/yr at the grounding line.
+
+%needed later
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+
+di=md.materials.rho_ice/md.materials.rho_water;
+
+h=1000;
+md.geometry.thickness=h*ones(md.mesh.numberofvertices,1);
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+%Initial velocity and pressure
+md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+md.initialization.vy=zeros(md.mesh.numberofvertices,1);
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%Boundary conditions:
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+%constrain flanks to 0 normal velocity
+pos=find(md.mesh.x==xmin | md.mesh.x==xmax);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvz(pos)=NaN;
+
+%constrain grounding line to 0 velocity
+pos=find(md.mesh.y==ymin);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+
+%icefront
+nodeonicefront=zeros(md.mesh.numberofvertices,1);
+pos=find(md.mesh.y==ymax); nodeonicefront(pos)=1;
+pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2))); diagnostic.icefront=md.mesh.segments(pos,:);
+diagnostic.icefront=[diagnostic.icefront 1*md.mask.elementonfloatingice(diagnostic.icefront(:,end))];
+md.diagnostic.icefront=diagnostic.icefront;
+
+%partitioning
+md.qmu.numberofpartitions=md.mesh.numberofvertices;
+md=partitioner(md,'package','linear','npart',md.qmu.numberofpartitions);
+md.qmu.partition=md.qmu.partition-1;
+
+%Dakota options
+%variables
+md.qmu.variables.rheology_B=normal_uncertain('scaled_MaterialsRheologyB',1,.5);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+%imperative! 
+md.diagnostic.reltol=10^-10; %tighten for qmu analysese
+md.qmu.isdakota=1;
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+
+%Fields and tolerances to track changes
+md=tres(md,'dakota');
+md.results.dakota.importancefactors=importancefactors(md,'scaled_MaterialsRheologyB','MaxVel')';
+field_names     ={'importancefactors'};
+field_tolerances={1e-10};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test236.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test236.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test236.m	(revision 11330)
@@ -0,0 +1,92 @@
+md=squaremesh(model,1000000,1000000,5,5);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%redo the parameter file for this special shelf. 
+%constant thickness, constrained (vy=0) flow into an icefront, 
+%from 0 m/yr at the grounding line.
+
+%needed later
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+
+di=md.materials.rho_ice/md.materials.rho_water;
+
+h=1000;
+md.geometry.thickness=h*ones(md.mesh.numberofvertices,1);
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+%Initial velocity and pressure
+md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+md.initialization.vy=zeros(md.mesh.numberofvertices,1);
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%Boundary conditions:
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+%constrain flanks to 0 normal velocity
+pos=find(md.mesh.x==xmin | md.mesh.x==xmax);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvz(pos)=NaN;
+
+%constrain grounding line to 0 velocity
+pos=find(md.mesh.y==ymin);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+
+%icefront
+nodeonicefront=zeros(md.mesh.numberofvertices,1);
+pos=find(md.mesh.y==ymax); nodeonicefront(pos)=1;
+pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2))); diagnostic.icefront=md.mesh.segments(pos,:);
+diagnostic.icefront=[diagnostic.icefront 1*md.mask.elementonfloatingice(diagnostic.icefront(:,end))];
+md.diagnostic.icefront=diagnostic.icefront;
+
+%partitioning
+md.qmu.numberofpartitions=md.mesh.numberofvertices;
+md=partitioner(md,'package','linear','npart',md.qmu.numberofpartitions);
+md.qmu.partition=md.qmu.partition-1;
+
+%Dakota options
+%variables
+md.qmu.variables.rheology_B=normal_uncertain('scaled_MaterialsRheologyB',1,.05);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+%imperative! 
+md.diagnostic.reltol=10^-10; %tighten for qmu analysese
+md.qmu.isdakota=1;
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+
+%Fields and tolerances to track changes
+md=tres(md,'dakota');
+md.results.dakota.importancefactors=importancefactors(md,'scaled_MaterialsRheologyB','MaxVel')';
+field_names     ={'importancefactors'};
+field_tolerances={1e-10};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test237.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test237.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test237.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'pattyn','../Exp/SquareHalfRight.exp','fill','macayeal');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test238.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test238.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test238.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'pattyn','../Exp/SquareHalfRight.exp','fill','macayeal');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test239.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test239.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test239.m	(revision 11330)
@@ -0,0 +1,17 @@
+md=triangle(model,'../Exp/Square.exp',120000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,2,1);
+md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','pattyn');
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test240.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test240.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test240.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',120000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,2,1);
+md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','pattyn');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-06,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test241.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test241.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test241.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',120000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,2,1);
+md.diagnostic.viscosity_overshoot=0.0;
+md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','macayeal');
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test242.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test242.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test242.m	(revision 11330)
@@ -0,0 +1,19 @@
+md=triangle(model,'../Exp/Square.exp',120000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,2,1);
+md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','macayeal');
+md.cluster=generic('name',oshostname(),'np',3);
+md.diagnostic.viscosity_overshoot=0;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-06,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test243.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test243.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test243.m	(revision 11330)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md.prognostic.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test244.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test244.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test244.m	(revision 11330)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.prognostic.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test245.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test245.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test245.m	(revision 11330)
@@ -0,0 +1,35 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.geometry.bed=md.geometry.bed+50; md.geometry.surface=md.geometry.surface+50;
+md.cluster=none;
+md.prognostic.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test246.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test246.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test246.m	(revision 11330)
@@ -0,0 +1,35 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.geometry.bed=md.geometry.bed+50; md.geometry.surface=md.geometry.surface+50;
+md.cluster=generic('name',oshostname(),'np',3);
+md.prognostic.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test247.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test247.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test247.m	(revision 11330)
@@ -0,0 +1,46 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=none;
+md.prognostic.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-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-09,1e-09,1e-09,1e-09,1e-06};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test248.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test248.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test248.m	(revision 11330)
@@ -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,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.prognostic.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
+	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test249.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test249.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test249.m	(revision 11330)
@@ -0,0 +1,47 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.geometry.bed=md.geometry.bed+50; md.geometry.surface=md.geometry.surface+50;
+md.cluster=none;
+md.prognostic.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-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-09,1e-09,1e-09,1e-09,1e-06};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test250.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test250.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test250.m	(revision 11330)
@@ -0,0 +1,50 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.geometry.bed=md.geometry.bed+50; md.geometry.surface=md.geometry.surface+50;
+md.cluster=generic('name',oshostname(),'np',3);
+md.prognostic.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
+	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test251.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test251.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test251.m	(revision 11330)
@@ -0,0 +1,35 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md.timestepping.time_adapt=1;
+md.timestepping.final_time=10;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test252.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test252.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test252.m	(revision 11330)
@@ -0,0 +1,35 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_adapt=1;
+md.timestepping.final_time=10;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test253.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test253.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test253.m	(revision 11330)
@@ -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,'pattyn','all');
+md.cluster=none;
+md.timestepping.time_adapt=1;
+md.timestepping.final_time=10;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+						1e-09,1e-09,1e-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};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test254.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test254.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test254.m	(revision 11330)
@@ -0,0 +1,50 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_adapt=1;
+md.timestepping.final_time=10;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
+	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test255.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test255.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test255.m	(revision 11330)
@@ -0,0 +1,64 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+%Set up transient
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test256.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test256.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test256.m	(revision 11330)
@@ -0,0 +1,64 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+%Set up transient
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test257.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test257.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test257.m	(revision 11330)
@@ -0,0 +1,64 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+%Set up transient
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*2 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test258.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test258.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test258.m	(revision 11330)
@@ -0,0 +1,64 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+%Set up transient
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*2 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test259.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test259.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test259.m	(revision 11330)
@@ -0,0 +1,69 @@
+md=triangle(model,'../Exp/Square.exp',350000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+%Set up transient
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3',...
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceMassbalance4'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test260.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test260.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test260.m	(revision 11330)
@@ -0,0 +1,69 @@
+md=triangle(model,'../Exp/Square.exp',350000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+%Set up transient
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3',...
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceMassbalance4'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test261.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test261.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test261.m	(revision 11330)
@@ -0,0 +1,69 @@
+md=triangle(model,'../Exp/Square.exp',350000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+%Set up transient
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*2 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3',...
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceMassbalance4'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test262.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test262.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test262.m	(revision 11330)
@@ -0,0 +1,69 @@
+md=triangle(model,'../Exp/Square.exp',350000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+%Set up transient
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*2 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3',...
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceMassbalance4'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test263.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test263.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test263.m	(revision 11330)
@@ -0,0 +1,24 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+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=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature1','BasalforcingsMeltingRate1','Temperature2','BasalforcingsMeltingRate2','Temperature3','BasalforcingsMeltingRate3','Temperature4','BasalforcingsMeltingRate4'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution(1).Temperature),...
+	(md.results.ThermalSolution(1).BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution(2).Temperature),...
+	(md.results.ThermalSolution(2).BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution(3).Temperature),...
+	(md.results.ThermalSolution(3).BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution(4).Temperature),...
+	(md.results.ThermalSolution(4).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test264.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test264.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test264.m	(revision 11330)
@@ -0,0 +1,24 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.thermal.spctemperature=[md.thermal.spctemperature, md.thermal.spctemperature+5, md.thermal.spctemperature+10, md.thermal.spctemperature+15; 1.5 2.5 3.5 4];
+md.timestepping.time_step=1;
+md.timestepping.final_time=4;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature1','BasalforcingsMeltingRate1','Temperature2','BasalforcingsMeltingRate2','Temperature3','BasalforcingsMeltingRate3','Temperature4','BasalforcingsMeltingRate4'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution(1).Temperature),...
+	(md.results.ThermalSolution(1).BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution(2).Temperature),...
+	(md.results.ThermalSolution(2).BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution(3).Temperature),...
+	(md.results.ThermalSolution(3).BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution(4).Temperature),...
+	(md.results.ThermalSolution(4).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test265.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test265.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test265.m	(revision 11330)
@@ -0,0 +1,62 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=none;
+md.thermal.spctemperature=[md.thermal.spctemperature, md.thermal.spctemperature+5; 1 2];
+md.timestepping.time_step=0.5;
+md.timestepping.final_time=2;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3',...
+					   'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','Temperature4','BasalforcingsMeltingRate4'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09, ...
+						1e-09,1e-09,1e-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-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-09,1e-06};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).Temperature),...
+	(md.results.TransientSolution(4).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test266.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test266.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test266.m	(revision 11330)
@@ -0,0 +1,62 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.thermal.spctemperature=[md.thermal.spctemperature, md.thermal.spctemperature+5; 1 2];
+md.timestepping.time_step=0.5;
+md.timestepping.final_time=2;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3', ...
+					   'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','Temperature4','BasalforcingsMeltingRate4'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09, ...
+						1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-07, ...
+						1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06, ...
+						1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).Temperature),...
+	(md.results.TransientSolution(4).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test267.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test267.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test267.m	(revision 11330)
@@ -0,0 +1,72 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+%Dakota options
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.surface_mass_balance=normal_uncertain('scaled_SurfaceforcingsMassBalance',1,0.1);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.IceVolume=response_function('IceVolume',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.massFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%mass flux profiles
+md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp'};
+md.qmu.mass_flux_profile_directory=pwd;
+
+%%  nond_sampling study
+md.qmu.method=dakota_method('nond_samp');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),'seed',1234,'samples',20,'sample_type','lhs');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+md.qmu.isdakota=1;
+
+md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+md.transient.requested_outputs=IceVolumeEnum();
+
+%solve
+md=solve(md,TransientSolutionEnum,'overwrite','y');
+md=tres(md,'dakota');
+
+%Fields and tolerances to track changes
+md.results.dakota.importancefactors=[];
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).mean];
+end
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'importancefactors'};
+field_tolerances={1e-11};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test268.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test268.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test268.m	(revision 11330)
@@ -0,0 +1,72 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+%Dakota options
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.surface_mass_balance=normal_uncertain('scaled_SurfaceforcingsMassBalance',1,100);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.IceVolume=response_function('IceVolume',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.massFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%mass flux profiles
+md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp'};
+md.qmu.mass_flux_profile_directory=pwd;
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+md.qmu.params.fd_gradient_step_size='0.1';
+md.qmu.isdakota=1;
+
+md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+md.transient.requested_outputs=IceVolumeEnum();
+
+%solve
+md=solve(md,TransientSolutionEnum,'overwrite','y');
+md=tres(md,'dakota');
+
+%Fields and tolerances to track changes
+md.results.dakota.importancefactors=[];
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).mean];
+end
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'importancefactors'};
+field_tolerances={1e-11};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test301.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test301.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test301.m	(revision 11330)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test302.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test302.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test302.m	(revision 11330)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test303.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test303.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test303.m	(revision 11330)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'hutter','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test304.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test304.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test304.m	(revision 11330)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'hutter','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test305.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test305.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test305.m	(revision 11330)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'hutter','../Exp/SquareHalfRight.exp','fill','macayeal');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test306.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test306.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test306.m	(revision 11330)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'hutter','../Exp/SquareHalfRight.exp','fill','macayeal');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test307.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test307.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test307.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test308.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test308.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test308.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test309.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test309.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test309.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,5,2);
+md=setflowequation(md,'hutter','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test310.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test310.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test310.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,5,2);
+md=setflowequation(md,'hutter','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test311.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test311.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test311.m	(revision 11330)
@@ -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,'hutter','../Exp/SquareHalfRight.exp','fill','macayeal');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test312.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test312.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test312.m	(revision 11330)
@@ -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,'hutter','../Exp/SquareHalfRight.exp','fill','macayeal');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test313.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test313.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test313.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test314.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test314.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test314.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test315.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test315.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test315.m	(revision 11330)
@@ -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.cluster=none;
+md=setflowequation(md,'stokes','all');
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test316.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test316.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test316.m	(revision 11330)
@@ -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,'stokes','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test317.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test317.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test317.m	(revision 11330)
@@ -0,0 +1,13 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test318.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test318.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test318.m	(revision 11330)
@@ -0,0 +1,13 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test319.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test319.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test319.m	(revision 11330)
@@ -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,'macayeal','all');
+md.prognostic.stabilization=3;
+md.prognostic.spcthickness=md.geometry.thickness;
+md.cluster=none;
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test320.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test320.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test320.m	(revision 11330)
@@ -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,'macayeal','all');
+md.prognostic.stabilization=3;
+md.prognostic.spcthickness=md.geometry.thickness;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test321.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test321.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test321.m	(revision 11330)
@@ -0,0 +1,14 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md=extrude(md,5,0.5);
+md.cluster=none;
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test322.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test322.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test322.m	(revision 11330)
@@ -0,0 +1,14 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md=extrude(md,5,0.5);
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test323.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test323.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test323.m	(revision 11330)
@@ -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,'macayeal','all');
+md.timestepping.time_step=0;
+md.cluster=none;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test324.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test324.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test324.m	(revision 11330)
@@ -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,'macayeal','all');
+md.timestepping.time_step=0;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test325.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test325.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test325.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution(1).Temperature),...
+	(md.results.ThermalSolution(1).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test326.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test326.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test326.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution(1).Temperature),...
+	(md.results.ThermalSolution(1).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test327.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test327.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test327.m	(revision 11330)
@@ -0,0 +1,37 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'hutter','all');
+md.cluster=none;
+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-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test328.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test328.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test328.m	(revision 11330)
@@ -0,0 +1,33 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'hutter','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%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(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test329.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test329.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test329.m	(revision 11330)
@@ -0,0 +1,47 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,5,1.2);
+md=setflowequation(md,'hutter','all');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-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};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test330.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test330.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test330.m	(revision 11330)
@@ -0,0 +1,47 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,5,1.2);
+md=setflowequation(md,'hutter','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-13,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...,
+						1e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-10,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test331.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test331.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test331.m	(revision 11330)
@@ -0,0 +1,33 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test332.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test332.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test332.m	(revision 11330)
@@ -0,0 +1,33 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test333.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test333.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test333.m	(revision 11330)
@@ -0,0 +1,47 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-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,1e-10,1e-10,...
+						1e-9,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test334.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test334.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test334.m	(revision 11330)
@@ -0,0 +1,47 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+						1e-09,1e-09,1e-10,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+						1e-09,5e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test335.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test335.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test335.m	(revision 11330)
@@ -0,0 +1,23 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,4,1);
+md=setflowequation(md,'hutter','all');
+md.cluster=none;
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13
+};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test336.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test336.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test336.m	(revision 11330)
@@ -0,0 +1,22 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,4,1);
+md=setflowequation(md,'hutter','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13
+};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test337.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test337.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test337.m	(revision 11330)
@@ -0,0 +1,33 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=0*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=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test338.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test338.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test338.m	(revision 11330)
@@ -0,0 +1,33 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test339.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test339.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test339.m	(revision 11330)
@@ -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,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test340.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test340.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test340.m	(revision 11330)
@@ -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,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test341.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test341.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test341.m	(revision 11330)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[102*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test342.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test342.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test342.m	(revision 11330)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[102*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-08,1e-07,1e-10,1e-10,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test343.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test343.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test343.m	(revision 11330)
@@ -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,'stokes','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[104*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test344.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test344.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test344.m	(revision 11330)
@@ -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,'stokes','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[104*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-06,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test345.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test345.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test345.m	(revision 11330)
@@ -0,0 +1,35 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md.timestepping.time_adapt=1;
+md.timestepping.final_time=600;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test346.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test346.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test346.m	(revision 11330)
@@ -0,0 +1,35 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_adapt=1;
+md.timestepping.final_time=600;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test347.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test347.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test347.m	(revision 11330)
@@ -0,0 +1,49 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,4,1.2);
+md=setflowequation(md,'hutter','all');
+md.cluster=none;
+md.timestepping.time_adapt=1;
+md.timestepping.final_time=500;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+					   %'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+%	(md.results.TransientSolution(3).Vx),...
+%	(md.results.TransientSolution(3).Vy),...
+%	(md.results.TransientSolution(3).Vz),...
+%	(md.results.TransientSolution(3).Vel),...
+%	(md.results.TransientSolution(3).Pressure),...
+%	(md.results.TransientSolution(3).Bed),...
+%	(md.results.TransientSolution(3).Surface),...
+%	(md.results.TransientSolution(3).Thickness),...
+%	(md.results.TransientSolution(3).Temperature),...
+%	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test348.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test348.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test348.m	(revision 11330)
@@ -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,'hutter','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_adapt=1;
+md.timestepping.final_time=500;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+					   %'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-13,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...,
+						5*1e-11,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-10,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+%	(md.results.TransientSolution(3).Vx),...
+%	(md.results.TransientSolution(3).Vy),...
+%	(md.results.TransientSolution(3).Vz),...
+%	(md.results.TransientSolution(3).Vel),...
+%	(md.results.TransientSolution(3).Pressure),...
+%	(md.results.TransientSolution(3).Bed),...
+%	(md.results.TransientSolution(3).Surface),...
+%	(md.results.TransientSolution(3).Thickness),...
+%	(md.results.TransientSolution(3).Temperature),...
+%	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test349.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test349.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test349.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.timestepping.time_step=0;
+md.cluster=none;
+md=solve(md,EnthalpySolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Enthalpy','Waterfraction','Temperature'};
+field_tolerances={1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.EnthalpySolution.Enthalpy),...
+	(md.results.EnthalpySolution.Waterfraction),...
+	(md.results.EnthalpySolution.Temperature),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test350.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test350.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test350.m	(revision 11330)
@@ -0,0 +1,20 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.timestepping.time_step=0;
+md.cluster=generic('name',oshostname(),'np',3);
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+%md.debug.valgrind=1;
+md=solve(md,EnthalpySolutionEnum);
+%md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Enthalpy','Waterfraction','Temperature'};
+field_tolerances={1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.EnthalpySolution.Enthalpy),...
+	(md.results.EnthalpySolution.Waterfraction),...
+	(md.results.EnthalpySolution.Temperature),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test351.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test351.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test351.m	(revision 11330)
@@ -0,0 +1,25 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.cluster=none;
+md=solve(md,EnthalpySolutionEnum);
+
+%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.EnthalpySolution(1).Enthalpy),...
+	(md.results.EnthalpySolution(1).Waterfraction),...
+	(md.results.EnthalpySolution(1).Temperature),...
+	(md.results.EnthalpySolution(2).Enthalpy),...
+	(md.results.EnthalpySolution(2).Waterfraction),...
+	(md.results.EnthalpySolution(2).Temperature),...
+	(md.results.EnthalpySolution(3).Enthalpy),...
+	(md.results.EnthalpySolution(3).Waterfraction),...
+	(md.results.EnthalpySolution(3).Temperature),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test352.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test352.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test352.m	(revision 11330)
@@ -0,0 +1,26 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+%md=solve(md,ThermalSolutionEnum);
+md=solve(md,EnthalpySolutionEnum);
+
+%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.EnthalpySolution(1).Enthalpy),...
+	(md.results.EnthalpySolution(1).Waterfraction),...
+	(md.results.EnthalpySolution(1).Temperature),...
+	(md.results.EnthalpySolution(2).Enthalpy),...
+	(md.results.EnthalpySolution(2).Waterfraction),...
+	(md.results.EnthalpySolution(2).Temperature),...
+	(md.results.EnthalpySolution(3).Enthalpy),...
+	(md.results.EnthalpySolution(3).Waterfraction),...
+	(md.results.EnthalpySolution(3).Temperature),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test401.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test401.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test401.m	(revision 11330)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test402.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test402.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test402.m	(revision 11330)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test403.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test403.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test403.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test404.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test404.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test404.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test405.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test405.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test405.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test406.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test406.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test406.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test407.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test407.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test407.m	(revision 11330)
@@ -0,0 +1,17 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'stokes','all');
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test408.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test408.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test408.m	(revision 11330)
@@ -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,'stokes','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-07,1e-07,1e-06,1e-07,1e-07};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test409.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test409.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test409.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','penalties');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-05,1e-05,1e-05,1e-05,1e-05};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test410.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test410.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test410.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','penalties');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-05,1e-05,1e-05,1e-05,1e-05};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test411.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test411.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test411.m	(revision 11330)
@@ -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,'pattyn','all');
+md.cluster=none;
+md.timestepping.time_step=0;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test412.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test412.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test412.m	(revision 11330)
@@ -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,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test413.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test413.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test413.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,4,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=none;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution(1).Temperature),...
+	(md.results.ThermalSolution(1).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test414.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test414.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test414.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,4,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution(1).Temperature),...
+	(md.results.ThermalSolution(1).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test415.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test415.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test415.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test416.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test416.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test416.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test417.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test417.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test417.m	(revision 11330)
@@ -0,0 +1,45 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','penalties');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test418.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test418.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test418.m	(revision 11330)
@@ -0,0 +1,48 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','penalties');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={...
+	1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,...
+	1e-03,1e-03,1e-02,1e-03,1e-02,1e-04,1e-01,1e-03,1e-01,1e-01,...
+	1e-02,1e-02,1e-01,1e-02,1e-01,1e-04,1e-04,1e-04,1e-04,1e-01};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test419.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test419.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test419.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13
+};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test420.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test420.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test420.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-10,1e-10,1e-09,1e-10,1e-13,1e-10,1e-06};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test421.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test421.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test421.m	(revision 11330)
@@ -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,'pattyn','all');
+md.cluster=none;
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test422.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test422.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test422.m	(revision 11330)
@@ -0,0 +1,22 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-09,1e-09,1e-08,1e-09,1e-09,1e-08,1e-05
+};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test423.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test423.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test423.m	(revision 11330)
@@ -0,0 +1,45 @@
+md=triangle(model,'../Exp/Square.exp',300000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+
+%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,.01);
+%md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,.01*ones(md.qmu.numberofpartitions,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]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+
+%imperative! 
+md.diagnostic.reltol=10^-5; %tighten for qmu analysese
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+
+%Fields and tolerances to track changes
+md=tres(md,'dakota');
+md.results.dakota.importancefactors=importancefactors(md,'scaled_FrictionCoefficient','MaxVel')';
+field_names     ={'importancefactors'};
+field_tolerances={1e-10};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test424.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test424.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test424.m	(revision 11330)
@@ -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,'macayeal','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='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+%imperative! 
+md.diagnostic.reltol=10^-5; %tighten for qmu analysese
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+
+%Fields and tolerances to track changes
+md=tres(md,'dakota');
+md.results.dakota.importancefactors=importancefactors(md,'scaled_FrictionCoefficient','MaxVel')';
+field_names     ={'importancefactors'};
+field_tolerances={1e-10};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test425.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test425.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test425.m	(revision 11330)
@@ -0,0 +1,45 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+
+%Dakota options
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.rho_ice=normal_uncertain('MaterialsRhoIce',md.materials.rho_ice,0.01);
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+
+%imperative!
+md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+md.qmu.isdakota=1;
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+
+%Fields and tolerances to track changes
+md=tres(md,'dakota');
+md.results.dakota.importancefactors=importancefactors(md,'scaled_FrictionCoefficient','MaxVel')';
+field_names     ={'importancefactors'};
+field_tolerances={1e-10};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test426.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test426.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test426.m	(revision 11330)
@@ -0,0 +1,45 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%Dakota options
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.rho_ice=normal_uncertain('MaterialsRhoIce',md.materials.rho_ice,0.01);
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+
+%imperative!
+md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+md.qmu.isdakota=1;
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+
+%Fields and tolerances to track changes
+md=tres(md,'dakota');
+md.results.dakota.importancefactors=importancefactors(md,'scaled_FrictionCoefficient','MaxVel')';
+field_names     ={'importancefactors'};
+field_tolerances={1e-10};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test427.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test427.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test427.m	(revision 11330)
@@ -0,0 +1,71 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md.materials.rho_ice=10^7; %involved in the mass flux, make it easy
+md.geometry.thickness(:)=1; %make it easy
+
+%constrain all velocities to 1 m/yr, in the y-direction
+md.diagnostic.spcvx(:)=0;
+md.diagnostic.spcvy(:)=1;
+md.diagnostic.spcvz(:)=0;
+
+%Dakota options
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux7=response_function('indexed_MassFlux_7',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%mass flux profiles
+md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp','../Exp/Square.exp'};
+md.qmu.mass_flux_profile_directory=pwd;
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+md.qmu.isdakota=1;
+md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=tres(md,'dakota');
+
+%Fields and tolerances to track changes
+
+%ok, mass flux of 3 profiles should be -3 Gt/yr -3 Gt/yr and the sum, which is -6 Gt/yr
+%we recover those mass fluxes through the mean of the response.
+%also, we recover the max velo, which should be 1m/yr. 
+%we put all that data in the importancefactors, which we will use to test for success.
+%also, check that the stddev are 0.
+md.results.dakota.importancefactors=[];
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).mean];
+end
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'importancefactors'};
+field_tolerances={1e-11};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test428.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test428.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test428.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.materials.rho_ice=10^7; %involved in the mass flux, make it easy
+md.geometry.thickness(:)=1; %make it easy
+
+%constrain all velocities to 1 m/yr, in the y-direction
+md.diagnostic.spcvx=zeros(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=zeros(md.mesh.numberofvertices,1);
+
+%Dakota options
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux7=response_function('indexed_MassFlux_7',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%mass flux profiles
+md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp','../Exp/Square.exp'};
+md.qmu.mass_flux_profile_directory=pwd;
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+md.qmu.isdakota=1;
+md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=tres(md,'dakota');
+
+%Fields and tolerances to track changes
+%ok, mass flux of 3 profiles should be -3 Gt/yr -3 Gt/yr and the sum, which is -6 Gt/yr
+%we recover those mass fluxes through the mean of the response.
+%also, we recover the max velo, which should be 1m/yr. 
+%we put all that data in the importancefactors, which we will use to test for success.
+%also, check that the stddev are 0.
+md.results.dakota.importancefactors=[];
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).mean];
+end
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'importancefactors'};
+field_tolerances={1e-11};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test429.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test429.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test429.m	(revision 11330)
@@ -0,0 +1,38 @@
+md=triangle(model,'../Exp/Square.exp',170000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.timestepping.time_step=0;
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=none;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.SteadystateSolution.Gradient1),...
+	md.results.SteadystateSolution.J,...
+	(md.results.SteadystateSolution.FrictionCoefficient),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test430.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test430.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test430.m	(revision 11330)
@@ -0,0 +1,38 @@
+md=triangle(model,'../Exp/Square.exp',170000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.timestepping.time_step=0;
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
+field_tolerances={1e-10,1e-10,1e-11,1e-13,1e-10,1e-09,1e-10,1e-8,1e-10,1e-6};
+field_values={...
+	(md.results.SteadystateSolution.Gradient1),...
+	md.results.SteadystateSolution.J,...
+	(md.results.SteadystateSolution.FrictionCoefficient),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test431.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test431.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test431.m	(revision 11330)
@@ -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,'pattyn','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[102*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.timestepping.time_step=0;
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=none;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
+field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06};
+field_values={...
+	(md.results.SteadystateSolution.Gradient1),...
+	md.results.SteadystateSolution.J,...
+	(md.results.SteadystateSolution.FrictionCoefficient),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test432.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test432.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test432.m	(revision 11330)
@@ -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,'pattyn','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[102*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.timestepping.time_step=0;
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
+field_tolerances={1e-08,1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-07,1e-08,1e-05};
+field_values={...
+	(md.results.SteadystateSolution.Gradient1),...
+	md.results.SteadystateSolution.J,...
+	(md.results.SteadystateSolution.FrictionCoefficient),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test434.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test434.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test434.m	(revision 11330)
@@ -0,0 +1,73 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.materials.rho_ice=10^7; %involved in the mass flux, make it easy
+md.geometry.thickness(:)=1; %make it easy
+
+%constrain all velocities to 1 m/yr, in the y-direction
+md.diagnostic.spcvx(:)=0;
+md.diagnostic.spcvy(:)=1;
+md.diagnostic.spcvz(:)=0;
+
+%Dakota options
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
+
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux7=response_function('indexed_MassFlux_7',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%mass flux profiles
+md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp','../Exp/Square.exp'};
+md.qmu.mass_flux_profile_directory=pwd;
+
+
+%%  nond_sampling study
+
+md.qmu.method     =dakota_method('nond_samp');
+md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),...
+'seed',1234,...
+'samples',20,...
+'sample_type','lhs');
+
+%%  a variety of parameters
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+md.qmu.isdakota=1;
+
+md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+
+%Fields and tolerances to track changes
+md=tres(md,'dakota');
+
+%ok, mass flux of 3 profiles should be -3 Gt/yr -3 Gt/yr and the sum, which is -6 Gt/yr
+%we recover those mass fluxes through the mean of the response.
+%also, we recover the max velo, which should be 1m/yr. 
+%we put all that data in the montecarlo field, which we will use to test for success.
+%also, check that the stddev are 0.
+md.results.dakota.montecarlo=[];
+for i=1:8,
+	md.results.dakota.montecarlo=[md.results.dakota.montecarlo md.results.dakota.dresp_out(i).mean];
+end
+for i=1:8,
+	md.results.dakota.montecarlo=[md.results.dakota.montecarlo md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'montecarlo'};
+field_tolerances={1e-11};
+field_values={...
+         md.results.dakota.montecarlo,...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test435.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test435.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test435.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+
+%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/trunk-jpl-damage/test/NightlyRun/test437.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test437.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test437.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','tiling');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test438.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test438.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test438.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test439.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test439.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test439.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+
+%partitioning
+md.qmu.numberofpartitions=10;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions);
+md.qmu.partition=md.qmu.partition-1;
+md.qmu.isdakota=1;
+
+%Dakota options
+%variables
+md.qmu.variables.rho_ice=normal_uncertain('MaterialsRhoIce',md.materials.rho_ice,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('scaled_Thickness',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+
+%imperative! 
+md.diagnostic.reltol=10^-5; %tighten for qmu analysese
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=tres(md,'dakota');
+
+%test on thickness
+h=zeros(md.qmu.numberofpartitions,1);
+for i=1:md.qmu.numberofpartitions,
+	h(i)=md.qmu.results.dresp_out(i).mean;
+end
+
+%project onto grid
+thickness=h(md.qmu.partition+1);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-11};
+field_values={thickness};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test440.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test440.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test440.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%partitioning
+md.qmu.numberofpartitions=10;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions);
+md.qmu.partition=md.qmu.partition-1;
+md.qmu.isdakota=1;
+
+%Dakota options
+%variables
+md.qmu.variables.rho_ice=normal_uncertain('MaterialsRhoIce',md.materials.rho_ice,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('scaled_Thickness',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+
+%imperative! 
+md.diagnostic.reltol=10^-5; %tighten for qmu analysese
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=tres(md,'dakota');
+
+%test on thickness
+h=zeros(md.qmu.numberofpartitions,1);
+for i=1:md.qmu.numberofpartitions,
+	h(i)=md.qmu.results.dresp_out(i).mean;
+end
+
+%project onto grid
+thickness=h(md.qmu.partition+1);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-10};
+field_values={thickness};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test441.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test441.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test441.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','tiling');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test442.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test442.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test442.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','pattyn');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-08,1e-09,1e-05,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test443.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test443.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test443.m	(revision 11330)
@@ -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,'stokes','../Exp/SquareHalfRight.exp','fill','macayeal','coupling','tiling');
+md.cluster=none;
+md.diagnostic.reltol=0.4;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-06,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test444.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test444.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test444.m	(revision 11330)
@@ -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,'stokes','../Exp/SquareHalfRight.exp','fill','macayeal');
+md.cluster=generic('name',oshostname(),'np',3);
+md.diagnostic.reltol=0.4;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-06,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test445.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test445.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test445.m	(revision 11330)
@@ -0,0 +1,37 @@
+radius=1e6;
+shelfextent=2e5;
+
+md=roundmesh(model,radius,200000);
+%fix center node to 0,0
+rad=sqrt(md.mesh.x.^2+md.mesh.y.^2);
+pos=find(rad==min(rad));
+md.mesh.x(pos)=0; md.mesh.y(pos)=0; %the closest node to the center is changed to be exactly at the center
+xelem=md.mesh.x(md.mesh.elements)*[1;1;1]/3;
+yelem=md.mesh.y(md.mesh.elements)*[1;1;1]/3;
+rad=sqrt(xelem.^2+yelem.^2);
+flags=zeros(md.mesh.numberofelements,1);
+pos=find(rad>=(radius-shelfextent));
+flags(pos)=1;
+md=setmask(md,flags,''); 
+md=parameterize(md,'../Par/RoundSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+
+md.transient.isthermal=0;
+md.transient.isprognostic=0;
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+
+%test different grounding line dynamics
+md.groundingline.migration='AgressiveMigration';
+md=solve(md,TransientSolutionEnum);
+element_on_iceshelf_agressive=(md.results.TransientSolution.MaskElementonfloatingice);
+
+md.groundingline.migration='SoftMigration';
+md=solve(md,TransientSolutionEnum);
+element_on_iceshelf_soft=(md.results.TransientSolution.MaskElementonfloatingice);
+
+%Fields and tolerances to track changes
+field_names     ={'ElementOnIceShelfAgressive','ElementOnIceShelfSoft'};
+field_tolerances={1e-13,1e-13};
+field_values={element_on_iceshelf_agressive,element_on_iceshelf_soft};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test446.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test446.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test446.m	(revision 11330)
@@ -0,0 +1,37 @@
+radius=1e6;
+shelfextent=2e5;
+
+md=roundmesh(model,radius,50000);
+%fix center node to 0,0
+rad=sqrt(md.mesh.x.^2+md.mesh.y.^2);
+pos=find(rad==min(rad));
+md.mesh.x(pos)=0; md.mesh.y(pos)=0; %the closest node to the center is changed to be exactly at the center
+xelem=md.mesh.x(md.mesh.elements)*[1;1;1]/3;
+yelem=md.mesh.y(md.mesh.elements)*[1;1;1]/3;
+rad=sqrt(xelem.^2+yelem.^2);
+flags=zeros(md.mesh.numberofelements,1);
+pos=find(rad>=(radius-shelfextent));
+flags(pos)=1;
+md=setmask(md,flags,''); 
+md=parameterize(md,'../Par/RoundSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.transient.isthermal=0;
+md.transient.isprognostic=0;
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+
+%test different grounding line dynamics.
+md.groundingline.migration='AgressiveMigration';
+md=solve(md,TransientSolutionEnum);
+element_on_iceshelf_agressive=(md.results.TransientSolution.MaskElementonfloatingice);
+
+md.groundingline.migration='SoftMigration';
+md=solve(md,TransientSolutionEnum);
+element_on_iceshelf_soft=(md.results.TransientSolution.MaskElementonfloatingice);
+
+%Fields and tolerances to track changes
+field_names     ={'ElementOnIceShelfAgressive','ElementOnIceShelfSoft'};
+field_tolerances={1e-13,1e-13};
+field_values={element_on_iceshelf_agressive,element_on_iceshelf_soft};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test447.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test447.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test447.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.thickness(:)=1000;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md.surfaceforcings.mass_balance(:)=100;
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='AgressiveMigration';
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
+	'Bed2','Surface2','Thickness2','Floatingice2',...
+	'Bed3','Surface3','Thickness3','Floatingice3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test448.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test448.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test448.m	(revision 11330)
@@ -0,0 +1,41 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.thickness(:)=1000;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md.surfaceforcings.mass_balance(:)=100;
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='AgressiveMigration';
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
+	'Bed2','Surface2','Thickness2','Floatingice2',...
+	'Bed3','Surface3','Thickness3','Floatingice3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test449.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test449.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test449.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.thickness(:)=1300;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md.surfaceforcings.mass_balance(:)=-150;
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='SoftMigration';
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
+	'Bed2','Surface2','Thickness2','Floatingice2',...
+	'Bed3','Surface3','Thickness3','Floatingice3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test450.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test450.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test450.m	(revision 11330)
@@ -0,0 +1,41 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.thickness(:)=1300;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md.surfaceforcings.mass_balance(:)=-150;
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='SoftMigration';
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
+	'Bed2','Surface2','Thickness2','Floatingice2',...
+	'Bed3','Surface3','Thickness3','Floatingice3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test451.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test451.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test451.m	(revision 11330)
@@ -0,0 +1,42 @@
+md=triangle(model,'../Exp/Square.exp',350000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.cluster=none;
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.thickness(:)=1000;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md.surfaceforcings.mass_balance(:)=100;
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='AgressiveMigration';
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
+	'Bed2','Surface2','Thickness2','Floatingice2',...
+	'Bed3','Surface3','Thickness3','Floatingice3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test452.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test452.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test452.m	(revision 11330)
@@ -0,0 +1,43 @@
+md=triangle(model,'../Exp/Square.exp',350000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.cluster=none;
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.thickness(:)=1000;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md.surfaceforcings.mass_balance(:)=100;
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='AgressiveMigration';
+md.cluster=generic('name',oshostname(),'np',3);
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
+	'Bed2','Surface2','Thickness2','Floatingice2',...
+	'Bed3','Surface3','Thickness3','Floatingice3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-11,1e-11,1e-11,1e-13,...
+	1e-10,1e-10,1e-10,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test453.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test453.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test453.m	(revision 11330)
@@ -0,0 +1,41 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.thickness(:)=1300;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+
+md.surfaceforcings.mass_balance(:)=-150;
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='SoftMigration';
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
+	'Bed2','Surface2','Thickness2','Floatingice2',...
+	'Bed3','Surface3','Thickness3','Floatingice3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test454.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test454.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test454.m	(revision 11330)
@@ -0,0 +1,41 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.thickness(:)=1300;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md=setflowequation(md,'macayeal','all');
+md=extrude(md,3,1);
+
+md.surfaceforcings.mass_balance(:)=-150;
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='SoftMigration';
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
+	'Bed2','Surface2','Thickness2','Floatingice2',...
+	'Bed3','Surface3','Thickness3','Floatingice3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,...
+	1e-10,1e-11,1e-10,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test501.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test501.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test501.m	(revision 11330)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Pig.exp',20000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test502.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test502.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test502.m	(revision 11330)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Pig.exp',20000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test503.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test503.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test503.m	(revision 11330)
@@ -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,'pattyn','all');
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test504.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test504.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test504.m	(revision 11330)
@@ -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,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test505.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test505.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test505.m	(revision 11330)
@@ -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=extrude(md,3,0.9);
+md=setflowequation(md,'stokes','all');
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test506.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test506.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test506.m	(revision 11330)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Pig.exp',20000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,0.9);
+md=setflowequation(md,'stokes','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test507.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test507.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test507.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test508.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test508.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test508.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test509.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test509.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test509.m	(revision 11330)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-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).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test510.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test510.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test510.m	(revision 11330)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test511.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test511.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test511.m	(revision 11330)
@@ -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,'pattyn','all');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test512.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test512.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test512.m	(revision 11330)
@@ -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,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-12,1e-11,1e-12,1e-11,1e-12,1e-12,...
+						1e-11,1e-11,1e-09,1e-11,1e-11,1e-10,1e-11,1e-10,1e-11,1e-08};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test513.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test513.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test513.m	(revision 11330)
@@ -0,0 +1,35 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,2,1);
+md=setflowequation(md,'stokes','all');
+md.cluster=none;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+%The thickness wants to be lower than 1 so we contrain it to 1
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-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).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test514.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test514.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test514.m	(revision 11330)
@@ -0,0 +1,35 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,2,1);
+md=setflowequation(md,'stokes','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+%The thickness wants to be lower than 1 so we contrain it to 1
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test515.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test515.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test515.m	(revision 11330)
@@ -0,0 +1,22 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,4,1.1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13
+};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test516.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test516.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test516.m	(revision 11330)
@@ -0,0 +1,22 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,4,1.1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-08
+};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test517.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test517.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test517.m	(revision 11330)
@@ -0,0 +1,22 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=none;
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13
+};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test518.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test518.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test518.m	(revision 11330)
@@ -0,0 +1,22 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06
+};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test519.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test519.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test519.m	(revision 11330)
@@ -0,0 +1,22 @@
+md=triangle(model,'../Exp/Pig.exp',20000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,2,1);
+md=setflowequation(md,'stokes','all');
+md.cluster=none;
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06
+};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test520.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test520.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test520.m	(revision 11330)
@@ -0,0 +1,22 @@
+md=triangle(model,'../Exp/Pig.exp',20000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,2,1);
+md=setflowequation(md,'stokes','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06
+};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test521.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test521.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test521.m	(revision 11330)
@@ -0,0 +1,39 @@
+md=triangle(model,'../Exp/Pig.exp',10000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+
+%impose hydrostatic equilibrium (required by Stokes)
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md=extrude(md,3,1);
+md=setflowequation(md,'stokes','all');
+md=modelextract(md,md.mask.elementonfloatingice);
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^8*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyB' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyB),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test522.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test522.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test522.m	(revision 11330)
@@ -0,0 +1,39 @@
+md=triangle(model,'../Exp/Pig.exp',10000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+
+%impose hydrostatic equilibrium (required by Stokes)
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md=extrude(md,3,1);
+md=setflowequation(md,'stokes','all');
+md=modelextract(md,md.mask.elementonfloatingice);
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^8*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyB' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-11,1e-12,1e-12,1e-09,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyB),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test523.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test523.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test523.m	(revision 11330)
@@ -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,'pattyn','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=none;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test524.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test524.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test524.m	(revision 11330)
@@ -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,'pattyn','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test525.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test525.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test525.m	(revision 11330)
@@ -0,0 +1,39 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+md.timestepping.time_step=0;
+
+md.thermal.penalty_lock=5;
+md.cluster=none;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.SteadystateSolution.Gradient1),...
+	md.results.SteadystateSolution.J,...
+	(md.results.SteadystateSolution.FrictionCoefficient),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test526.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test526.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test526.m	(revision 11330)
@@ -0,0 +1,39 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+md.timestepping.time_step=0;
+
+md.thermal.penalty_lock=5;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
+field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-6,1e-6,1e-6,1e-6,1e-6,1e-06};
+field_values={...
+	(md.results.SteadystateSolution.Gradient1),...
+	md.results.SteadystateSolution.J,...
+	(md.results.SteadystateSolution.FrictionCoefficient),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test527.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test527.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test527.m	(revision 11330)
@@ -0,0 +1,56 @@
+%Simple mesh 1
+hVertices=10000*ones(27,1);
+hVertices(1:5)=1000;
+md=bamg(model,'domain','../Exp/Pig.exp','hmax',20000,'hVertices',hVertices,'gradation',3,'geometricalmetric',1);
+x1=md.mesh.x;
+y1=md.mesh.y;
+
+%Simple mesh 2
+md=bamg(model,'domain','../Exp/Pig.exp','hmax',10000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+x2=md.mesh.x;
+y2=md.mesh.y;
+
+%refine existing mesh 1
+hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,md.inversion.vy_obs,'node');
+metric=ComputeMetric(hessian,2/9,1,1000,25*10^3,[]);
+md.miscellaneous.dummy=metric;
+md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1);
+x3=md2.mesh.x;
+y3=md2.mesh.y;
+
+%refine existing mesh 2
+md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1,'anisomax',1);
+x4=md2.mesh.x;
+y4=md2.mesh.y;
+
+%refine existing mesh 3
+hVertices=NaN*ones(md.mesh.numberofvertices,1);
+hVertices(find(md.mesh.vertexonboundary))=500;
+md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1,'anisomax',1,'hVertices',hVertices);
+x5=md2.mesh.x;
+y5=md2.mesh.y;
+
+%refine existing mesh 4
+md2=bamg(md,'field',md.inversion.vy_obs,'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1,'Hessiantype',0,'err',1);
+x6=md2.mesh.x;
+y6=md2.mesh.y;
+
+%refine existing mesh 5
+md2=bamg(md,'field',[md.inversion.vy_obs md.geometry.thickness],'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1,'Hessiantype',1,'err',[10 100]); 
+x7=md2.mesh.x;
+y7=md2.mesh.y;
+
+%Fields and tolerances to track changes
+field_names     ={'x1' 'y1' 'x2' 'y2' 'x3' 'y3' 'x4' 'y4' 'x5' 'y5' 'x6' 'y6'  'x7' 'y7' };
+field_tolerances={1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13};
+field_values={...
+	x1, y1,...
+	y2, y2,...
+	y3, y3,...
+	y4, y4,...
+	y5, y5,...
+	y6, y6,...
+	y7, y7,...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test529.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test529.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test529.m	(revision 11330)
@@ -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,'pattyn','all');
+md.thermal.stabilization=2;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature1','BasalforcingsMeltingRate1', ...
+				      'Temperature2','BasalforcingsMeltingRate2'};
+field_tolerances={1e-13,1e-9,1e-13,1e-9};
+field_values={...
+	(md.results.ThermalSolution(1).Temperature),...
+	(md.results.ThermalSolution(1).BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution(2).Temperature),...
+	(md.results.ThermalSolution(2).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test530.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test530.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test530.m	(revision 11330)
@@ -0,0 +1,19 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.thermal.stabilization=2;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature1','BasalforcingsMeltingRate1', ...
+				      'Temperature2','BasalforcingsMeltingRate2'};
+field_tolerances={1e-13,1e-8,1e-13,1e-8};
+field_values={...
+	(md.results.ThermalSolution(1).Temperature),...
+	(md.results.ThermalSolution(1).BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution(2).Temperature),...
+	(md.results.ThermalSolution(2).BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test531.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test531.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test531.m	(revision 11330)
@@ -0,0 +1,17 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.thermal.stabilization=2;
+md.timestepping.time_step=0;
+md.thermal.penalty_threshold=40;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-12};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test532.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test532.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test532.m	(revision 11330)
@@ -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,'pattyn','all');
+md.thermal.stabilization=2;
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0;
+md.thermal.penalty_threshold=40;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-11,1e-11};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test601.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test601.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test601.m	(revision 11330)
@@ -0,0 +1,13 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test602.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test602.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test602.m	(revision 11330)
@@ -0,0 +1,13 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test603.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test603.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test603.m	(revision 11330)
@@ -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,'macayeal','all');
+md.prognostic.stabilization=3;
+md.prognostic.spcthickness=md.geometry.thickness;
+md.cluster=none;
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test604.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test604.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test604.m	(revision 11330)
@@ -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,'macayeal','all');
+md.prognostic.stabilization=3;
+md.prognostic.spcthickness=md.geometry.thickness;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test605.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test605.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test605.m	(revision 11330)
@@ -0,0 +1,14 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=extrude(md,6,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test606.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test606.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test606.m	(revision 11330)
@@ -0,0 +1,14 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=extrude(md,6,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test607.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test607.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test607.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md=solve(md,SurfaceSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test608.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test608.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test608.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SurfaceSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test609.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test609.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test609.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=extrude(md,5,1.5);
+md=setflowequation(md,'pattyn','all');
+md.cluster=none;
+md=solve(md,SurfaceSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test610.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test610.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test610.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=extrude(md,5,1.5);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SurfaceSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test611.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test611.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test611.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md=solve(md,BedSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test612.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test612.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test612.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BedSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test613.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test613.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test613.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=extrude(md,2,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,BedSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test614.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test614.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test614.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=extrude(md,2,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BedSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test615.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test615.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test615.m	(revision 11330)
@@ -0,0 +1,13 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=none;
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test616.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test616.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test616.m	(revision 11330)
@@ -0,0 +1,13 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test617.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test617.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test617.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=meshconvert(md);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+md.balancethickness.stabilization=3;
+md.cluster=none;
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test618.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test618.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test618.m	(revision 11330)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=meshconvert(md);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+md.balancethickness.stabilization=3;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test619.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test619.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test619.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=none;
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test620.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test620.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test620.m	(revision 11330)
@@ -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,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test621.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test621.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test621.m	(revision 11330)
@@ -0,0 +1,31 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.nsteps=2;
+md.prognostic.stabilization=1;
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'BalancethicknessThickeningRate'};
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.min_parameters=-50*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=50*ones(md.mesh.numberofvertices,1);
+md.inversion.cost_functions=201*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10/md.constants.yts*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+
+md.cluster=none;
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'BalancethicknessThickeningRate' 'Thickness'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+field_values={...
+	(md.results.BalancethicknessSolution.Gradient1),...
+	md.results.BalancethicknessSolution.J,...
+	(md.results.BalancethicknessSolution.BalancethicknessThickeningRate),...
+	(md.results.BalancethicknessSolution.Thickness)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test622.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test622.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test622.m	(revision 11330)
@@ -0,0 +1,31 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.nsteps=2;
+md.prognostic.stabilization=1;
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'BalancethicknessThickeningRate'};
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.min_parameters=-50*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=50*ones(md.mesh.numberofvertices,1);
+md.inversion.cost_functions=201*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10/md.constants.yts*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'BalancethicknessThickeningRate' 'Thickness'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+field_values={...
+	(md.results.BalancethicknessSolution.Gradient1),...
+	md.results.BalancethicknessSolution.J,...
+	(md.results.BalancethicknessSolution.BalancethicknessThickeningRate),...
+	(md.results.BalancethicknessSolution.Thickness)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test623.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test623.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test623.m	(revision 11330)
@@ -0,0 +1,32 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=meshconvert(md);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.nsteps=2;
+md.balancethickness.stabilization=3;
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'BalancethicknessThickeningRate'};
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.min_parameters=-50*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=50*ones(md.mesh.numberofvertices,1);
+md.inversion.cost_functions=201*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10/md.constants.yts*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+
+md.cluster=none;
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'BalancethicknessThickeningRate' 'Thickness'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+field_values={...
+	(md.results.BalancethicknessSolution.Gradient1),...
+	md.results.BalancethicknessSolution.J,...
+	(md.results.BalancethicknessSolution.BalancethicknessThickeningRate),...
+	(md.results.BalancethicknessSolution.Thickness)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test624.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test624.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test624.m	(revision 11330)
@@ -0,0 +1,32 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=meshconvert(md);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.nsteps=2;
+md.balancethickness.stabilization=3;
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'BalancethicknessThickeningRate'};
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.min_parameters=-50*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=50*ones(md.mesh.numberofvertices,1);
+md.inversion.cost_functions=201*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10/md.constants.yts*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'BalancethicknessThickeningRate' 'Thickness'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+field_values={...
+	(md.results.BalancethicknessSolution.Gradient1),...
+	md.results.BalancethicknessSolution.J,...
+	(md.results.BalancethicknessSolution.BalancethicknessThickeningRate),...
+	(md.results.BalancethicknessSolution.Thickness)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test625.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test625.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test625.m	(revision 11330)
@@ -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,'macayeal','all');
+
+%Ice sheet only
+md=modelextract(md,md.mask.elementongroundedice);
+pos=find(md.mesh.vertexonboundary);
+md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
+
+%control parameters
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.iscontrol=1;
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.nsteps=2;
+md.inversion.control_parameters={'Vx' 'Vy'};
+md.balancethickness.stabilization=1;
+md.inversion.gradient_scaling=[10/md.constants.yts*ones(md.inversion.nsteps,1) 10/md.constants.yts*ones(md.inversion.nsteps,1)];
+md.inversion.min_parameters=[-2000*ones(md.mesh.numberofvertices,1) -2000*ones(md.mesh.numberofvertices,1)];
+md.inversion.max_parameters=[+2000*ones(md.mesh.numberofvertices,1) +2000*ones(md.mesh.numberofvertices,1)];
+md.inversion.cost_functions=201*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+
+md.cluster=none;
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient1' 'Gradient2' 'Misfits' 'Vx' 'Vy' 'Thickness'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+field_values={...
+	(md.results.BalancethicknessSolution.Gradient1),...
+	(md.results.BalancethicknessSolution.Gradient2),...
+	md.results.BalancethicknessSolution.J,...
+	(md.results.BalancethicknessSolution.Vx),...
+	(md.results.BalancethicknessSolution.Vy),...
+	(md.results.BalancethicknessSolution.Thickness)
+};
Index: /issm/trunk-jpl-damage/test/NightlyRun/test626.m
===================================================================
--- /issm/trunk-jpl-damage/test/NightlyRun/test626.m	(revision 11330)
+++ /issm/trunk-jpl-damage/test/NightlyRun/test626.m	(revision 11330)
@@ -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,'macayeal','all');
+
+%Ice sheet only
+md=modelextract(md,md.mask.elementongroundedice);
+pos=find(md.mesh.vertexonboundary);
+md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
+
+%control parameters
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.iscontrol=1;
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.nsteps=2;
+md.inversion.control_parameters={'Vx' 'Vy'};
+md.balancethickness.stabilization=1;
+md.inversion.gradient_scaling=[10/md.constants.yts*ones(md.inversion.nsteps,1) 10/md.constants.yts*ones(md.inversion.nsteps,1)];
+md.inversion.min_parameters=[-2000*ones(md.mesh.numberofvertices,1) -2000*ones(md.mesh.numberofvertices,1)];
+md.inversion.max_parameters=[+2000*ones(md.mesh.numberofvertices,1) +2000*ones(md.mesh.numberofvertices,1)];
+md.inversion.cost_functions=201*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient1' 'Gradient2' 'Misfits' 'Vx' 'Vy' 'Thickness'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+field_values={...
+	(md.results.BalancethicknessSolution.Gradient1),...
+	(md.results.BalancethicknessSolution.Gradient2),...
+	md.results.BalancethicknessSolution.J,...
+	(md.results.BalancethicknessSolution.Vx),...
+	(md.results.BalancethicknessSolution.Vy),...
+	(md.results.BalancethicknessSolution.Thickness)
+};
Index: /issm/trunk-jpl-damage/test/Par/79North.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/79North.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/79North.par	(revision 11330)
@@ -0,0 +1,52 @@
+%Start defining model parameters here
+
+%Geometry and observation
+load('../Data/79North.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);
+md.geometry.surface  =InterpFromMeshToMesh2d(index,x,y,surface,md.mesh.x,md.mesh.y);
+md.geometry.thickness=InterpFromMeshToMesh2d(index,x,y,thickness,md.mesh.x,md.mesh.y);
+md.geometry.bed=md.geometry.surface-md.geometry.thickness;
+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
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient=50*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Ice shelf melting and surface mass balance 
+md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
+pos=zeros(md.mesh.numberofvertices,1);
+pos(md.mesh.elements(find(md.mask.elementonfloatingice),:))=1;
+md.basalforcings.melting_rate(find(pos))=10;
+md.surfaceforcings.mass_balance=15*ones(md.mesh.numberofvertices,1);
+
+%Numerical parameters
+md.diagnostic.viscosity_overshoot=0.3;
+md.prognostic.stabilization=1;
+md.thermal.stabilization=1;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.timestepping.time_step=1;
+md.timestepping.final_time=3;
+md.diagnostic.restol=0.05;
+md.diagnostic.reltol=0.005;
+md.steadystate.reltol=0.005;
+md.diagnostic.abstol=NaN;
+
+%Boundary conditions:
+md=SetMarineIceSheetBC(md);
+pos=find(md.mesh.vertexonboundary);
+md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
+md.prognostic.spcthickness(pos)=md.geometry.thickness(pos);
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/trunk-jpl-damage/test/Par/ISMIPA.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/ISMIPA.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/ISMIPA.par	(revision 11330)
@@ -0,0 +1,22 @@
+%Ok, start defining model parameters here
+
+disp('      creating thickness');
+md.geometry.surface=-md.mesh.x*tan(0.5*pi/180);
+md.geometry.bed=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.bed;
+
+disp('      creating drag');
+md.friction.coefficient=200*ones(md.mesh.numberofvertices,1); %q=1.
+%Take care of iceshelves: no basal drag
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient(md.mesh.elements(pos,:))=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=6.8067*10^7*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+disp('      boundary conditions for diagnostic model');
+%Create node on boundary fist (because we cannot use mesh)
+md=SetIceSheetBC(md);
Index: /issm/trunk-jpl-damage/test/Par/ISMIPB.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/ISMIPB.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/ISMIPB.par	(revision 11330)
@@ -0,0 +1,22 @@
+%Ok, start defining model parameters here
+
+disp('      creating thickness');
+md.geometry.surface=-md.mesh.x*tan(0.5*pi/180);
+md.geometry.bed=md.geometry.surface-1000+500*sin(md.mesh.x*2*pi/max(md.mesh.x));
+md.geometry.thickness=md.geometry.surface-md.geometry.bed;
+
+disp('      creating drag');
+md.friction.coefficient=200*ones(md.mesh.numberofvertices,1); %q=1.
+%Take care of iceshelves: no basal drag
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient(md.mesh.elements(pos,:))=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=6.8067*10^7*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+disp('      boundary conditions for diagnostic model');
+%Create node on boundary fist (because we cannot use mesh)
+md=SetIceSheetBC(md);
Index: /issm/trunk-jpl-damage/test/Par/ISMIPC.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/ISMIPC.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/ISMIPC.par	(revision 11330)
@@ -0,0 +1,23 @@
+%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.bed=md.geometry.surface-1000;
+md.geometry.thickness=md.geometry.surface-md.geometry.bed;
+
+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.bed)));
+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))));
+%Take care of iceshelves: no basal drag
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=zeros(md.mesh.numberofelements,1);
+
+disp('      creating flow law paramter');
+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 diagnostic model: ');
+%Create node on boundary fist (because wi can not use mesh)
+md=SetIceSheetBC(md);
Index: /issm/trunk-jpl-damage/test/Par/ISMIPD.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/ISMIPD.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/ISMIPD.par	(revision 11330)
@@ -0,0 +1,22 @@
+%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.bed=md.geometry.surface-1000;
+md.geometry.thickness=md.geometry.surface-md.geometry.bed;
+
+disp('      creating drag');
+md.friction.coefficient=sqrt(md.constants.yts.*(1000+1000*sin(md.mesh.x*2*pi/max(md.mesh.x))));
+%Take care of iceshelves: no basal drag
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=zeros(md.mesh.numberofelements,1);
+
+disp('      creating flow law paramter');
+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 diagnostic model: ');
+%Create node on boundary fist (because wi can not use mesh)
+md=SetIceSheetBC(md);
Index: /issm/trunk-jpl-damage/test/Par/ISMIPE.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/ISMIPE.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/ISMIPE.par	(revision 11330)
@@ -0,0 +1,31 @@
+%Ok, start defining model parameters here
+
+disp('      creating thickness');
+data=load('../Data/ISMIPE.data','-mat');
+data=data.data;
+md.geometry.surface=zeros(md.mesh.numberofvertices,1);
+md.geometry.bed=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.bed(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.bed;
+md.geometry.thickness(find(~md.geometry.thickness))=0.01;
+md.geometry.bed=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 paramter');
+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 diagnostic model: ');
+%Create node on boundary fist (because wi can not use mesh)
+md=SetIceSheetBC(md);
Index: /issm/trunk-jpl-damage/test/Par/ISMIPF.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/ISMIPF.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/ISMIPF.par	(revision 11330)
@@ -0,0 +1,46 @@
+%Ok, start defining model parameters here
+md.verbose=2;
+
+disp('      creating thickness');
+md.geometry.surface=-md.mesh.x*tan(3*pi/180);
+%md.geometry.bed=md.geometry.surface-1000;
+md.geometry.bed=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.bed;
+
+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 paramter');
+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 diagnostic model');
+%Create node on boundary fist (because we cannot use mesh)
+md=SetIceSheetBC(md);
+md.diagnostic.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.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.prognostic.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.prognostic.stabilization=1;
+md.thermal.stabilization=1;
+md.thermal.penalty_threshold=10^5;
Index: /issm/trunk-jpl-damage/test/Par/Pig.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/Pig.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/Pig.par	(revision 11330)
@@ -0,0 +1,46 @@
+%Start defining model parameters here
+
+%Geometry and observation
+load('../Data/Pig.data','-mat');
+md.inversion.vx_obs   =InterpFromMeshToMesh2d(index,x,y,vx_obs,md.mesh.x,md.mesh.y);
+md.inversion.vy_obs   =InterpFromMeshToMesh2d(index,x,y,vy_obs,md.mesh.x,md.mesh.y);
+md.geometry.surface  =InterpFromMeshToMesh2d(index,x,y,surface,md.mesh.x,md.mesh.y);
+md.geometry.thickness=InterpFromMeshToMesh2d(index,x,y,thickness,md.mesh.x,md.mesh.y);
+md.geometry.bed=md.geometry.surface-md.geometry.thickness;
+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
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient=50*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.diagnostic.viscosity_overshoot=0.3;
+md.prognostic.stabilization=1;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.timestepping.time_step=1;
+md.timestepping.final_time=2;
+md.diagnostic.restol=0.05;
+md.diagnostic.reltol=1;
+md.steadystate.reltol=1;
+md.diagnostic.abstol=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/trunk-jpl-damage/test/Par/RoundSheetEISMINT.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/RoundSheetEISMINT.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/RoundSheetEISMINT.par	(revision 11330)
@@ -0,0 +1,59 @@
+%Ok, start defining model parameters here
+disp('      creating thickness');
+md.geometry.thickness=10*ones(md.mesh.numberofvertices,1);
+md.geometry.bed=zeros(md.mesh.numberofvertices,1);
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+disp('      creating drag');
+md.friction.coefficient=20*ones(md.mesh.numberofvertices,1); %q=1. %no drag is specified in the analytical solution
+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 paramter');
+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 diagnostic model: ');
+md=SetMarineIceSheetBC(md,'../Exp/RoundFrontEISMINT.exp');
+
+radius=sqrt((md.mesh.x).*md.mesh.x+(md.mesh.y).*md.mesh.y);
+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.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.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/trunk-jpl-damage/test/Par/RoundSheetShelf.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/RoundSheetShelf.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/RoundSheetShelf.par	(revision 11330)
@@ -0,0 +1,113 @@
+%Start defining model parameters here
+
+di=md.materials.rho_ice/md.materials.rho_water;
+rad=1e6;
+shelfextent=2e5;
+%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.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+
+pos=find(md.mask.vertexongroundedice);
+md.geometry.bed(pos)=md.geometry.bed(pos)-300*(radius(pos)-(rad-shelfextent))/(rad-shelfextent);
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+pos=find(radius<200000);
+md.geometry.thickness(pos)=100;
+md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20;
+md.geometry.surface(pos)=md.geometry.bed(pos)+md.geometry.thickness(pos);
+
+
+pos=find(md.mesh.x<.2*1e6 & md.mesh.x>-.2*1e6 & md.mesh.y>0);
+md.geometry.thickness(pos)=100;
+md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20;
+md.geometry.surface(pos)=md.geometry.bed(pos)+md.geometry.thickness(pos);
+
+pos=find(md.mesh.x<.1*1e6 & md.mesh.x>-.1*1e6 & md.mesh.y<-.5*1e6 & md.mesh.y>-.6*1e6);
+md.geometry.thickness(pos)=100;
+md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20;
+md.geometry.surface(pos)=md.geometry.bed(pos)+md.geometry.thickness(pos);
+
+%plug holes into the ice sheet, to test for grounding line migration. 
+di=md.materials.rho_ice/md.materials.rho_water;
+rad=sqrt(md.mesh.x.^2+md.mesh.y.^2);
+pos=find(rad<200000);
+md.geometry.thickness(pos)=100;
+md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20;
+md.geometry.surface(pos)=md.geometry.bed(pos)+md.geometry.thickness(pos);
+
+pos=find(md.mesh.x<.2*1e6 & md.mesh.x>-.2*1e6 & md.mesh.y>0);
+md.geometry.thickness(pos)=100;
+md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20;
+md.geometry.surface(pos)=md.geometry.bed(pos)+md.geometry.thickness(pos);
+
+pos=find(md.mesh.x<.1*1e6 & md.mesh.x>-.1*1e6 & md.mesh.y<-.5*1e6 & md.mesh.y>-.6*1e6);
+md.geometry.thickness(pos)=100;
+md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20;
+md.geometry.surface(pos)=md.geometry.bed(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.melting_rate=zeros(md.mesh.numberofvertices,1);
+pos=find(md.mask.vertexonfloatingice);md.basalforcings.melting_rate(pos)=10;
+md.basalforcings.geothermalflux=ones(md.mesh.numberofvertices,1);
+
+%Friction
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.diagnostic.viscosity_overshoot=0.0;
+md.prognostic.stabilization=1;
+md.thermal.stabilization=1;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.diagnostic.restol=0.05;
+md.diagnostic.reltol=0.05;
+md.steadystate.reltol=0.05;
+md.diagnostic.abstol=NaN;
+md.timestepping.time_step=5;
+md.timestepping.final_time=5;
+
+%bathymetry and grounding line migration:
+md.groundingline.migration='AgressiveMigration';
+md.geometry.bathymetry=md.geometry.bed;
+pos=find(md.mask.vertexonfloatingice); md.geometry.bathymetry(pos)=md.geometry.bed(pos)-900;
+
+%Deal with boundary conditions:
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+pos=find(md.mesh.x==0 & md.mesh.y==0);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+
+pressureload=md.mesh.segments;
+pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end)) + 0*md.mask.elementongroundedice(pressureload(:,end))];
+md.diagnostic.icefront=pressureload;
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.thermal.spctemperature=737*ones(md.mesh.numberofvertices,1);
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/trunk-jpl-damage/test/Par/RoundSheetStaticEISMINT.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/RoundSheetStaticEISMINT.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/RoundSheetStaticEISMINT.par	(revision 11330)
@@ -0,0 +1,54 @@
+disp('      creating thickness');
+hmin=0.01;
+hmax=2756.7;
+radius=(sqrt((md.mesh.x).^2+(md.mesh.y).^2));
+radiusmax=max(radius);
+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.bed=0*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+disp('      creating drag');
+md.friction.coefficient=20*ones(md.mesh.numberofvertices,1); %q=1. %no drag is specified in the analytical solution
+%Take care of iceshelves: no basal drag
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient(md.mesh.elements(pos,:))=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 paramter');
+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 diagnostic model: ');
+md=SetMarineIceSheetBC(md,'../Exp/RoundFrontEISMINT.exp');
+
+radius=sqrt((md.mesh.x).*md.mesh.x+(md.mesh.y).*md.mesh.y);
+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.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.spcvz(pos)=0;
Index: /issm/trunk-jpl-damage/test/Par/SquareEISMINT.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/SquareEISMINT.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/SquareEISMINT.par	(revision 11330)
@@ -0,0 +1,46 @@
+%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.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+disp('      creating drag');
+md.friction.coefficient=200*ones(md.mesh.numberofvertices,1); %q=1.
+%Take care of iceshelves: no basal drag
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient(md.mesh.elements(pos,:))=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 paramter');
+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.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.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.prognostic.spcthickness(pos)=500;
+md.prognostic.stabilization=0; %Better result with no artificial diffusivity
+md.thermal.stabilization=0; 
+md.timestepping.final_time=500;
+md.timestepping.time_step=1;
Index: /issm/trunk-jpl-damage/test/Par/SquareSheetConstrained.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/SquareSheetConstrained.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/SquareSheetConstrained.par	(revision 11330)
@@ -0,0 +1,50 @@
+%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+20;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+%Initial velocity 
+load('../Data/SquareSheetConstrained.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);
+
+%Friction
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.diagnostic.viscosity_overshoot=0.0;
+md.prognostic.stabilization=1;
+md.thermal.stabilization=1;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.diagnostic.restol=0.05;
+md.steadystate.reltol=0.05;
+md.diagnostic.reltol=0.05;
+md.diagnostic.abstol=NaN;
+md.timestepping.time_step=1;
+md.timestepping.final_time=3;
+
+%Boundary conditions:
+md=SetIceSheetBC(md);
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/trunk-jpl-damage/test/Par/SquareSheetShelf.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/SquareSheetShelf.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/SquareSheetShelf.par	(revision 11330)
@@ -0,0 +1,57 @@
+%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;
+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.bed(pos)=bed_sheet;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+%Initial velocity 
+load('../Data/SquareSheetShelf.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);
+
+%Accumulation and 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.diagnostic.viscosity_overshoot=0.0;
+md.prognostic.stabilization=1;
+md.thermal.stabilization=1;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.diagnostic.restol=0.05;
+md.steadystate.reltol=0.05;
+md.diagnostic.reltol=0.05;
+md.diagnostic.abstol=NaN;
+md.timestepping.time_step=1;
+md.timestepping.final_time=3;
+
+%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/trunk-jpl-damage/test/Par/SquareShelf.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/SquareShelf.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/SquareShelf.par	(revision 11330)
@@ -0,0 +1,50 @@
+%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 and pressure
+load('../Data/SquareShelf.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);
+
+%Friction
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.diagnostic.viscosity_overshoot=0.3;
+md.prognostic.stabilization=1;
+md.thermal.stabilization=1;
+md.settings.waitonlock=30;
+md.verbose=verbose(0);
+md.diagnostic.restol=0.10;
+md.steadystate.reltol=0.02;
+md.diagnostic.reltol=0.02;
+md.diagnostic.abstol=NaN;
+md.timestepping.time_step=1;
+md.timestepping.final_time=3;
+
+%Boundary conditions:
+md=SetIceShelfBC(md,'../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/trunk-jpl-damage/test/Par/SquareShelfConstrained.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/SquareShelfConstrained.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/SquareShelfConstrained.par	(revision 11330)
@@ -0,0 +1,54 @@
+%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('../Data/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.diagnostic.viscosity_overshoot=0.0;
+md.prognostic.stabilization=1;
+md.thermal.stabilization=1;
+md.verbose=verbose(0);
+md.settings.waitonlock=30;
+md.diagnostic.restol=0.05;
+md.diagnostic.reltol=0.05;
+md.steadystate.reltol=0.05;
+md.diagnostic.abstol=NaN;
+md.timestepping.time_step=1;
+md.timestepping.final_time=3;
+
+%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/trunk-jpl-damage/test/Par/SquareThermal.par
===================================================================
--- /issm/trunk-jpl-damage/test/Par/SquareThermal.par	(revision 11330)
+++ /issm/trunk-jpl-damage/test/Par/SquareThermal.par	(revision 11330)
@@ -0,0 +1,43 @@
+%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.bed=-1000*ones(md.mesh.numberofvertices,1);
+md.geometry.surface=md.geometry.bed+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); %q=1.
+%Take care of iceshelves: no basal drag
+pos=find(md.mask.elementonfloatingice);
+md.friction.coefficient(md.mesh.elements(pos,:))=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 paramter');
+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.melting_rate=0*ones(md.mesh.numberofvertices,1)/md.constants.yts; %1m/a
+
+%Deal with boundary conditions:
+
+disp('      boundary conditions for diagnostic 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); 
+pos=find(md.mask.elementongroundedice);md.basalforcings.geothermalflux(md.mesh.elements(pos,:))=1*10^-3; %1 mW/m^2
